1 /*
2  * Copyright (c) 2017 Linaro Limited
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/logging/log.h>
8 LOG_MODULE_REGISTER(net_test, CONFIG_NET_SOCKETS_LOG_LEVEL);
9 
10 #include <zephyr/ztest_assert.h>
11 #include <zephyr/posix/fcntl.h>
12 #include <zephyr/net/net_context.h>
13 #include <zephyr/net/socket.h>
14 #include <zephyr/net/loopback.h>
15 
16 #include "../../socket_helpers.h"
17 
18 #define TEST_STR_SMALL "test"
19 
20 #define TEST_STR_LONG \
21 	"The Zephyr Project, a Linux Foundation hosted Collaboration " \
22 	"Project, is an open source collaborative effort uniting leaders " \
23 	"from across the industry to build a best-in-breed small, scalable, " \
24 	"real-time operating system (RTOS) optimized for resource-" \
25 	"constrained devices, across multiple architectures."
26 
27 #define MY_IPV4_ADDR "127.0.0.1"
28 #define MY_IPV6_ADDR "::1"
29 
30 #define ANY_PORT 0
31 #define SERVER_PORT 4242
32 
33 #define MAX_CONNS 5
34 
35 #define TCP_TEARDOWN_TIMEOUT K_SECONDS(3)
36 #define THREAD_SLEEP 50 /* ms */
37 
test_bind(int sock,struct sockaddr * addr,socklen_t addrlen)38 static void test_bind(int sock, struct sockaddr *addr, socklen_t addrlen)
39 {
40 	zassert_equal(zsock_bind(sock, addr, addrlen),
41 		      0,
42 		      "bind failed with error %d", errno);
43 }
44 
test_listen(int sock)45 static void test_listen(int sock)
46 {
47 	zassert_equal(zsock_listen(sock, MAX_CONNS),
48 		      0,
49 		      "listen failed with error %d", errno);
50 }
51 
test_connect(int sock,struct sockaddr * addr,socklen_t addrlen)52 static void test_connect(int sock, struct sockaddr *addr, socklen_t addrlen)
53 {
54 	zassert_equal(zsock_connect(sock, addr, addrlen),
55 		      0,
56 		      "connect failed with error %d", errno);
57 
58 	if (IS_ENABLED(CONFIG_NET_TC_THREAD_PREEMPTIVE)) {
59 		/* Let the connection proceed */
60 		k_msleep(THREAD_SLEEP);
61 	}
62 }
63 
test_send(int sock,const void * buf,size_t len,int flags)64 static void test_send(int sock, const void *buf, size_t len, int flags)
65 {
66 	zassert_equal(zsock_send(sock, buf, len, flags),
67 		      len,
68 		      "send failed");
69 }
70 
test_sendto(int sock,const void * buf,size_t len,int flags,const struct sockaddr * addr,socklen_t addrlen)71 static void test_sendto(int sock, const void *buf, size_t len, int flags,
72 			const struct sockaddr *addr, socklen_t addrlen)
73 {
74 	zassert_equal(zsock_sendto(sock, buf, len, flags, addr, addrlen),
75 		      len,
76 		      "send failed");
77 }
78 
test_accept(int sock,int * new_sock,struct sockaddr * addr,socklen_t * addrlen)79 static void test_accept(int sock, int *new_sock, struct sockaddr *addr,
80 			socklen_t *addrlen)
81 {
82 	zassert_not_null(new_sock, "null newsock");
83 
84 	*new_sock = zsock_accept(sock, addr, addrlen);
85 	zassert_true(*new_sock >= 0, "accept failed");
86 }
87 
test_accept_timeout(int sock,int * new_sock,struct sockaddr * addr,socklen_t * addrlen)88 static void test_accept_timeout(int sock, int *new_sock, struct sockaddr *addr,
89 				socklen_t *addrlen)
90 {
91 	zassert_not_null(new_sock, "null newsock");
92 
93 	*new_sock = zsock_accept(sock, addr, addrlen);
94 	zassert_equal(*new_sock, -1, "accept succeed");
95 	zassert_equal(errno, EAGAIN, "");
96 }
97 
test_fcntl(int sock,int cmd,int val)98 static void test_fcntl(int sock, int cmd, int val)
99 {
100 	zassert_equal(zsock_fcntl(sock, cmd, val), 0, "fcntl failed");
101 }
102 
test_recv(int sock,int flags)103 static void test_recv(int sock, int flags)
104 {
105 	ssize_t recved = 0;
106 	char rx_buf[30] = {0};
107 
108 	recved = zsock_recv(sock, rx_buf, sizeof(rx_buf), flags);
109 	zassert_equal(recved,
110 		      strlen(TEST_STR_SMALL),
111 		      "unexpected received bytes");
112 	zassert_equal(strncmp(rx_buf, TEST_STR_SMALL, strlen(TEST_STR_SMALL)),
113 		      0,
114 		      "unexpected data");
115 }
116 
test_recvfrom(int sock,int flags,struct sockaddr * addr,socklen_t * addrlen)117 static void test_recvfrom(int sock,
118 			  int flags,
119 			  struct sockaddr *addr,
120 			  socklen_t *addrlen)
121 {
122 	ssize_t recved = 0;
123 	char rx_buf[30] = {0};
124 
125 	recved = zsock_recvfrom(sock, rx_buf, sizeof(rx_buf), flags, addr, addrlen);
126 	zassert_equal(recved,
127 		      strlen(TEST_STR_SMALL),
128 		      "unexpected received bytes");
129 	zassert_equal(strncmp(rx_buf, TEST_STR_SMALL, strlen(TEST_STR_SMALL)),
130 		      0,
131 		      "unexpected data");
132 }
133 
test_recvmsg(int sock,struct msghdr * msg,int flags,size_t expected,int line)134 static void test_recvmsg(int sock,
135 			 struct msghdr *msg,
136 			 int flags,
137 			 size_t expected,
138 			 int line)
139 {
140 	ssize_t recved;
141 
142 	recved = zsock_recvmsg(sock, msg, flags);
143 
144 	zassert_equal(recved, expected,
145 		      "line %d, unexpected received bytes (%d vs %d)",
146 		      line, recved, expected);
147 }
148 
test_shutdown(int sock,int how)149 static void test_shutdown(int sock, int how)
150 {
151 	zassert_equal(zsock_shutdown(sock, how),
152 		      0,
153 		      "shutdown failed");
154 }
155 
test_close(int sock)156 static void test_close(int sock)
157 {
158 	zassert_equal(zsock_close(sock),
159 		      0,
160 		      "close failed");
161 }
162 
163 /* Test that EOF handling works correctly. Should be called with socket
164  * whose peer socket was closed.
165  */
test_eof(int sock)166 static void test_eof(int sock)
167 {
168 	char rx_buf[1];
169 	ssize_t recved;
170 
171 	/* Test that EOF properly detected. */
172 	recved = zsock_recv(sock, rx_buf, sizeof(rx_buf), 0);
173 	zassert_equal(recved, 0, "");
174 
175 	/* Calling again should be OK. */
176 	recved = zsock_recv(sock, rx_buf, sizeof(rx_buf), 0);
177 	zassert_equal(recved, 0, "");
178 
179 	/* Calling when TCP connection is fully torn down should be still OK. */
180 	k_sleep(TCP_TEARDOWN_TIMEOUT);
181 	recved = zsock_recv(sock, rx_buf, sizeof(rx_buf), 0);
182 	zassert_equal(recved, 0, "");
183 }
184 
calc_net_context(struct net_context * context,void * user_data)185 static void calc_net_context(struct net_context *context, void *user_data)
186 {
187 	int *count = user_data;
188 
189 	(*count)++;
190 }
191 
192 /* Wait until the number of TCP contexts reaches a certain level
193  *   exp_num_contexts : The number of contexts to wait for
194  *   timeout :		The time to wait for
195  */
wait_for_n_tcp_contexts(int exp_num_contexts,k_timeout_t timeout)196 int wait_for_n_tcp_contexts(int exp_num_contexts, k_timeout_t timeout)
197 {
198 	uint32_t start_time = k_uptime_get_32();
199 	uint32_t time_diff;
200 	int context_count = 0;
201 
202 	/* After the client socket closing, the context count should be 1 less */
203 	net_context_foreach(calc_net_context, &context_count);
204 
205 	time_diff = k_uptime_get_32() - start_time;
206 
207 	/* Eventually the client socket should be cleaned up */
208 	while (context_count != exp_num_contexts) {
209 		context_count = 0;
210 		net_context_foreach(calc_net_context, &context_count);
211 		k_sleep(K_MSEC(50));
212 		time_diff = k_uptime_get_32() - start_time;
213 
214 		if (K_MSEC(time_diff).ticks > timeout.ticks) {
215 			return -ETIMEDOUT;
216 		}
217 	}
218 
219 	return 0;
220 }
221 
test_context_cleanup(void)222 static void test_context_cleanup(void)
223 {
224 	zassert_equal(wait_for_n_tcp_contexts(0, TCP_TEARDOWN_TIMEOUT),
225 		      0,
226 		      "Not all TCP contexts properly cleaned up");
227 }
228 
229 
ZTEST_USER(net_socket_tcp,test_v4_send_recv)230 ZTEST_USER(net_socket_tcp, test_v4_send_recv)
231 {
232 	/* Test if send() and recv() work on a ipv4 stream socket. */
233 	int c_sock;
234 	int s_sock;
235 	int new_sock;
236 	struct sockaddr_in c_saddr;
237 	struct sockaddr_in s_saddr;
238 	struct sockaddr addr;
239 	socklen_t addrlen = sizeof(addr);
240 
241 	prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &c_sock, &c_saddr);
242 	prepare_sock_tcp_v4(MY_IPV4_ADDR, SERVER_PORT, &s_sock, &s_saddr);
243 
244 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
245 	test_listen(s_sock);
246 
247 	test_connect(c_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
248 	test_send(c_sock, TEST_STR_SMALL, strlen(TEST_STR_SMALL), 0);
249 
250 	test_accept(s_sock, &new_sock, &addr, &addrlen);
251 	zassert_equal(addrlen, sizeof(struct sockaddr_in), "wrong addrlen");
252 
253 	test_recv(new_sock, ZSOCK_MSG_PEEK);
254 	test_recv(new_sock, 0);
255 
256 	test_close(c_sock);
257 	test_eof(new_sock);
258 
259 	test_close(new_sock);
260 	test_close(s_sock);
261 
262 	k_sleep(TCP_TEARDOWN_TIMEOUT);
263 }
264 
ZTEST_USER(net_socket_tcp,test_v6_send_recv)265 ZTEST_USER(net_socket_tcp, test_v6_send_recv)
266 {
267 	/* Test if send() and recv() work on a ipv6 stream socket. */
268 	int c_sock;
269 	int s_sock;
270 	int new_sock;
271 	struct sockaddr_in6 c_saddr;
272 	struct sockaddr_in6 s_saddr;
273 	struct sockaddr addr;
274 	socklen_t addrlen = sizeof(addr);
275 
276 	prepare_sock_tcp_v6(MY_IPV6_ADDR, ANY_PORT, &c_sock, &c_saddr);
277 	prepare_sock_tcp_v6(MY_IPV6_ADDR, SERVER_PORT, &s_sock, &s_saddr);
278 
279 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
280 	test_listen(s_sock);
281 
282 	test_connect(c_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
283 	test_send(c_sock, TEST_STR_SMALL, strlen(TEST_STR_SMALL), 0);
284 
285 	test_accept(s_sock, &new_sock, &addr, &addrlen);
286 	zassert_equal(addrlen, sizeof(struct sockaddr_in6), "wrong addrlen");
287 
288 	test_recv(new_sock, ZSOCK_MSG_PEEK);
289 	test_recv(new_sock, 0);
290 
291 	test_close(c_sock);
292 	test_eof(new_sock);
293 
294 	test_close(new_sock);
295 	test_close(s_sock);
296 
297 	k_sleep(TCP_TEARDOWN_TIMEOUT);
298 }
299 
300 /* Test the stack behavior with a resonable sized block data, be sure to have multiple packets */
301 #define TEST_LARGE_TRANSFER_SIZE 60000
302 #define TEST_PRIME 811
303 
304 #define TCP_SERVER_STACK_SIZE 2048
305 
306 K_THREAD_STACK_DEFINE(tcp_server_stack_area, TCP_SERVER_STACK_SIZE);
307 struct k_thread tcp_server_thread_data;
308 
309 /* A thread that receives, while the other part transmits */
tcp_server_block_thread(void * vps_sock,void * unused2,void * unused3)310 void tcp_server_block_thread(void *vps_sock, void *unused2, void *unused3)
311 {
312 	int new_sock;
313 	struct sockaddr addr;
314 	int *ps_sock = (int *)vps_sock;
315 	socklen_t addrlen = sizeof(addr);
316 
317 	test_accept(*ps_sock, &new_sock, &addr, &addrlen);
318 	zassert_true(addrlen == sizeof(struct sockaddr_in)
319 		|| addrlen == sizeof(struct sockaddr_in6), "wrong addrlen");
320 
321 	/* Check the received data */
322 	ssize_t recved = 0;
323 	ssize_t total_received = 0;
324 	int iteration = 0;
325 	uint8_t buffer[256];
326 
327 	while (total_received < TEST_LARGE_TRANSFER_SIZE) {
328 		/* Compute the remaining contents */
329 		size_t chunk_size = sizeof(buffer);
330 		size_t remain = TEST_LARGE_TRANSFER_SIZE - total_received;
331 
332 		if (chunk_size > remain) {
333 			chunk_size = remain;
334 		}
335 
336 		recved = zsock_recv(new_sock, buffer, chunk_size, 0);
337 
338 		zassert(recved > 0, "received bigger then 0",
339 			"Error receiving bytes %i bytes, got %i on top of %i in iteration %i, errno %i",
340 			chunk_size,	recved, total_received, iteration, errno);
341 
342 		/* Validate the contents */
343 		for (int i = 0; i < recved; i++) {
344 			int total_idx = i + total_received;
345 			uint8_t expValue = (total_idx * TEST_PRIME) & 0xff;
346 
347 			zassert_equal(buffer[i], expValue, "Unexpected data at %i", total_idx);
348 		}
349 
350 		total_received += recved;
351 		iteration++;
352 	}
353 
354 	test_close(new_sock);
355 }
356 
test_send_recv_large_common(int tcp_nodelay,int family)357 void test_send_recv_large_common(int tcp_nodelay, int family)
358 {
359 	int rv;
360 	int c_sock;
361 	int s_sock;
362 	struct sockaddr *c_saddr = NULL;
363 	struct sockaddr *s_saddr = NULL;
364 	size_t addrlen = 0;
365 
366 	struct sockaddr_in c_saddr_in;
367 	struct sockaddr_in s_saddr_in;
368 	struct sockaddr_in6 c_saddr_in6;
369 	struct sockaddr_in6 s_saddr_in6;
370 
371 	if (family == AF_INET) {
372 		prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &c_sock, &c_saddr_in);
373 		c_saddr = (struct sockaddr *) &c_saddr_in;
374 		prepare_sock_tcp_v4(MY_IPV4_ADDR, SERVER_PORT, &s_sock, &s_saddr_in);
375 		s_saddr = (struct sockaddr *) &s_saddr_in;
376 		addrlen = sizeof(s_saddr_in);
377 	} else if (family == AF_INET6) {
378 		prepare_sock_tcp_v6(MY_IPV6_ADDR, ANY_PORT, &c_sock, &c_saddr_in6);
379 		c_saddr = (struct sockaddr *) &c_saddr_in6;
380 		prepare_sock_tcp_v6(MY_IPV6_ADDR, SERVER_PORT, &s_sock, &s_saddr_in6);
381 		s_saddr = (struct sockaddr *) &s_saddr_in6;
382 		addrlen = sizeof(s_saddr_in6);
383 	} else {
384 		zassert_unreachable();
385 	}
386 
387 	test_bind(s_sock, s_saddr, addrlen);
388 	test_listen(s_sock);
389 
390 	(void)k_thread_create(&tcp_server_thread_data, tcp_server_stack_area,
391 		K_THREAD_STACK_SIZEOF(tcp_server_stack_area),
392 		tcp_server_block_thread,
393 		&s_sock, NULL, NULL,
394 		k_thread_priority_get(k_current_get()), 0, K_NO_WAIT);
395 
396 	test_connect(c_sock, s_saddr, addrlen);
397 
398 	rv = zsock_setsockopt(c_sock, IPPROTO_TCP, TCP_NODELAY, (char *) &tcp_nodelay, sizeof(int));
399 	zassert_equal(rv, 0, "setsockopt failed (%d)", rv);
400 
401 	/* send piece by piece */
402 	ssize_t total_send = 0;
403 	int iteration = 0;
404 	uint8_t buffer[256];
405 
406 	while (total_send < TEST_LARGE_TRANSFER_SIZE) {
407 		/* Fill the buffer with a known pattern */
408 		for (int i = 0; i < sizeof(buffer); i++) {
409 			int total_idx = i + total_send;
410 
411 			buffer[i] = (total_idx * TEST_PRIME) & 0xff;
412 		}
413 
414 		size_t chunk_size = sizeof(buffer);
415 		size_t remain = TEST_LARGE_TRANSFER_SIZE - total_send;
416 
417 		if (chunk_size > remain) {
418 			chunk_size = remain;
419 		}
420 
421 		int send_bytes = zsock_send(c_sock, buffer, chunk_size, 0);
422 
423 		zassert(send_bytes > 0, "send_bytes bigger then 0",
424 			"Error sending %i bytes on top of %i, got %i in iteration %i, errno %i",
425 			chunk_size, total_send, send_bytes, iteration, errno);
426 		total_send += send_bytes;
427 		iteration++;
428 	}
429 
430 	/* join the thread, to wait for the receiving part */
431 	zassert_equal(k_thread_join(&tcp_server_thread_data, K_SECONDS(60)), 0,
432 			"Not successfully wait for TCP thread to finish");
433 
434 	test_close(s_sock);
435 	test_close(c_sock);
436 
437 	k_sleep(TCP_TEARDOWN_TIMEOUT);
438 }
439 
440 /* Control the packet drop ratio at the loopback adapter 8 */
set_packet_loss_ratio(void)441 static void set_packet_loss_ratio(void)
442 {
443 	/* drop one every 8 packets */
444 	zassert_equal(loopback_set_packet_drop_ratio(0.125f), 0,
445 		"Error setting packet drop rate");
446 }
447 
restore_packet_loss_ratio(void)448 static void restore_packet_loss_ratio(void)
449 {
450 	/* no packet dropping any more */
451 	zassert_equal(loopback_set_packet_drop_ratio(0.0f), 0,
452 		"Error setting packet drop rate");
453 }
454 
ZTEST(net_socket_tcp,test_v4_send_recv_large_normal)455 ZTEST(net_socket_tcp, test_v4_send_recv_large_normal)
456 {
457 	test_send_recv_large_common(0, AF_INET);
458 }
459 
ZTEST(net_socket_tcp,test_v4_send_recv_large_packet_loss)460 ZTEST(net_socket_tcp, test_v4_send_recv_large_packet_loss)
461 {
462 	set_packet_loss_ratio();
463 	test_send_recv_large_common(0, AF_INET);
464 	restore_packet_loss_ratio();
465 }
466 
ZTEST(net_socket_tcp,test_v4_send_recv_large_no_delay)467 ZTEST(net_socket_tcp, test_v4_send_recv_large_no_delay)
468 {
469 	set_packet_loss_ratio();
470 	test_send_recv_large_common(1, AF_INET);
471 	restore_packet_loss_ratio();
472 }
473 
ZTEST(net_socket_tcp,test_v6_send_recv_large_normal)474 ZTEST(net_socket_tcp, test_v6_send_recv_large_normal)
475 {
476 	test_send_recv_large_common(0, AF_INET6);
477 }
478 
ZTEST(net_socket_tcp,test_v6_send_recv_large_packet_loss)479 ZTEST(net_socket_tcp, test_v6_send_recv_large_packet_loss)
480 {
481 	set_packet_loss_ratio();
482 	test_send_recv_large_common(0, AF_INET6);
483 	restore_packet_loss_ratio();
484 }
485 
ZTEST(net_socket_tcp,test_v6_send_recv_large_no_delay)486 ZTEST(net_socket_tcp, test_v6_send_recv_large_no_delay)
487 {
488 	set_packet_loss_ratio();
489 	test_send_recv_large_common(1, AF_INET6);
490 	restore_packet_loss_ratio();
491 }
492 
ZTEST(net_socket_tcp,test_v4_broken_link)493 ZTEST(net_socket_tcp, test_v4_broken_link)
494 {
495 	/* Test if the data stops transmitting after the send returned with a timeout. */
496 	int c_sock;
497 	int s_sock;
498 	int new_sock;
499 	struct sockaddr_in c_saddr;
500 	struct sockaddr_in s_saddr;
501 	struct sockaddr addr;
502 	socklen_t addrlen = sizeof(addr);
503 
504 	struct timeval optval = {
505 		.tv_sec = 0,
506 		.tv_usec = 500000,
507 	};
508 
509 	struct net_stats before;
510 	struct net_stats after;
511 	uint32_t start_time, time_diff;
512 	ssize_t recved;
513 	int rv;
514 	uint8_t rx_buf[10];
515 
516 	restore_packet_loss_ratio();
517 
518 	prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &c_sock, &c_saddr);
519 	prepare_sock_tcp_v4(MY_IPV4_ADDR, SERVER_PORT, &s_sock, &s_saddr);
520 
521 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
522 	test_listen(s_sock);
523 
524 	test_connect(c_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
525 	test_send(c_sock, TEST_STR_SMALL, strlen(TEST_STR_SMALL), 0);
526 
527 	test_accept(s_sock, &new_sock, &addr, &addrlen);
528 	zassert_equal(addrlen, sizeof(struct sockaddr_in), "wrong addrlen");
529 
530 	rv = zsock_setsockopt(new_sock, SOL_SOCKET, SO_RCVTIMEO, &optval,
531 			      sizeof(optval));
532 	zassert_equal(rv, 0, "setsockopt failed (%d)", errno);
533 
534 	test_recv(new_sock, ZSOCK_MSG_PEEK);
535 	test_recv(new_sock, 0);
536 
537 	/* At this point break the interface */
538 	zassert_equal(loopback_set_packet_drop_ratio(1.0f), 0,
539 		"Error setting packet drop rate");
540 
541 	test_send(c_sock, TEST_STR_SMALL, strlen(TEST_STR_SMALL), 0);
542 
543 	/* At this point break the interface */
544 	start_time = k_uptime_get_32();
545 
546 	/* Test the loopback packet loss: message should never arrive */
547 	recved = zsock_recv(new_sock, rx_buf, sizeof(rx_buf), 0);
548 	time_diff = k_uptime_get_32() - start_time;
549 
550 	zassert_equal(recved, -1, "Unexpected return code");
551 	zassert_equal(errno, EAGAIN, "Unexpected errno value: %d", errno);
552 	zassert_true(time_diff >= 500, "Expected timeout after 500ms but "
553 			"was %dms", time_diff);
554 
555 	/* Reading from client should indicate the socket has been closed */
556 	recved = zsock_recv(c_sock, rx_buf, sizeof(rx_buf), 0);
557 	zassert_equal(recved, -1, "Unexpected return code");
558 	zassert_equal(errno, ETIMEDOUT, "Unexpected errno value: %d", errno);
559 
560 	/* At this point there should be no traffic any more, get the current counters */
561 	net_mgmt(NET_REQUEST_STATS_GET_ALL, NULL, &before, sizeof(before));
562 
563 	k_sleep(K_MSEC(CONFIG_NET_TCP_INIT_RETRANSMISSION_TIMEOUT));
564 	k_sleep(K_MSEC(CONFIG_NET_TCP_INIT_RETRANSMISSION_TIMEOUT));
565 
566 	net_mgmt(NET_REQUEST_STATS_GET_ALL, NULL, &after, sizeof(after));
567 
568 	zassert_equal(before.ipv4.sent, after.ipv4.sent, "Data sent afer connection timeout");
569 
570 	test_close(c_sock);
571 	test_close(new_sock);
572 	test_close(s_sock);
573 
574 	restore_packet_loss_ratio();
575 
576 	k_sleep(TCP_TEARDOWN_TIMEOUT);
577 }
578 
ZTEST_USER(net_socket_tcp,test_v4_sendto_recvfrom)579 ZTEST_USER(net_socket_tcp, test_v4_sendto_recvfrom)
580 {
581 	int c_sock;
582 	int s_sock;
583 	int new_sock;
584 	struct sockaddr_in c_saddr;
585 	struct sockaddr_in s_saddr;
586 	struct sockaddr addr;
587 	socklen_t addrlen = sizeof(addr);
588 
589 	prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &c_sock, &c_saddr);
590 	prepare_sock_tcp_v4(MY_IPV4_ADDR, SERVER_PORT, &s_sock, &s_saddr);
591 
592 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
593 	test_listen(s_sock);
594 
595 	test_connect(c_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
596 	test_sendto(c_sock, TEST_STR_SMALL, strlen(TEST_STR_SMALL), 0,
597 		    (struct sockaddr *)&s_saddr, sizeof(s_saddr));
598 
599 	test_accept(s_sock, &new_sock, &addr, &addrlen);
600 	zassert_equal(addrlen, sizeof(struct sockaddr_in), "wrong addrlen");
601 
602 	test_recvfrom(new_sock, ZSOCK_MSG_PEEK, &addr, &addrlen);
603 	zassert_equal(addrlen, sizeof(struct sockaddr_in), "wrong addrlen");
604 
605 	test_recvfrom(new_sock, 0, &addr, &addrlen);
606 	zassert_equal(addrlen, sizeof(struct sockaddr_in), "wrong addrlen");
607 
608 	test_close(new_sock);
609 	test_close(s_sock);
610 	test_close(c_sock);
611 
612 	k_sleep(TCP_TEARDOWN_TIMEOUT);
613 }
614 
ZTEST_USER(net_socket_tcp,test_v6_sendto_recvfrom)615 ZTEST_USER(net_socket_tcp, test_v6_sendto_recvfrom)
616 {
617 	int c_sock;
618 	int s_sock;
619 	int new_sock;
620 	struct sockaddr_in6 c_saddr;
621 	struct sockaddr_in6 s_saddr;
622 	struct sockaddr addr;
623 	socklen_t addrlen = sizeof(addr);
624 
625 	prepare_sock_tcp_v6(MY_IPV6_ADDR, ANY_PORT, &c_sock, &c_saddr);
626 
627 	prepare_sock_tcp_v6(MY_IPV6_ADDR, SERVER_PORT, &s_sock, &s_saddr);
628 
629 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
630 	test_listen(s_sock);
631 
632 	test_connect(c_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
633 	test_sendto(c_sock, TEST_STR_SMALL, strlen(TEST_STR_SMALL), 0,
634 		    (struct sockaddr *)&s_saddr, sizeof(s_saddr));
635 
636 	test_accept(s_sock, &new_sock, &addr, &addrlen);
637 	zassert_equal(addrlen, sizeof(struct sockaddr_in6), "wrong addrlen");
638 
639 	test_recvfrom(new_sock, ZSOCK_MSG_PEEK, &addr, &addrlen);
640 	zassert_equal(addrlen, sizeof(struct sockaddr_in6), "wrong addrlen");
641 
642 	test_recvfrom(new_sock, 0, &addr, &addrlen);
643 	zassert_equal(addrlen, sizeof(struct sockaddr_in6), "wrong addrlen");
644 
645 	test_close(new_sock);
646 	test_close(s_sock);
647 	test_close(c_sock);
648 
649 	k_sleep(TCP_TEARDOWN_TIMEOUT);
650 }
651 
ZTEST_USER(net_socket_tcp,test_v4_sendto_recvfrom_null_dest)652 ZTEST_USER(net_socket_tcp, test_v4_sendto_recvfrom_null_dest)
653 {
654 	/* For a stream socket, sendto() should ignore NULL dest address */
655 	int c_sock;
656 	int s_sock;
657 	int new_sock;
658 	struct sockaddr_in c_saddr;
659 	struct sockaddr_in s_saddr;
660 	struct sockaddr addr;
661 	socklen_t addrlen = sizeof(addr);
662 
663 	prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &c_sock, &c_saddr);
664 	prepare_sock_tcp_v4(MY_IPV4_ADDR, SERVER_PORT, &s_sock, &s_saddr);
665 
666 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
667 	test_listen(s_sock);
668 
669 	test_connect(c_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
670 	test_sendto(c_sock, TEST_STR_SMALL, strlen(TEST_STR_SMALL), 0,
671 		    (struct sockaddr *)&s_saddr, sizeof(s_saddr));
672 
673 	test_accept(s_sock, &new_sock, &addr, &addrlen);
674 	zassert_equal(addrlen, sizeof(struct sockaddr_in), "wrong addrlen");
675 
676 	test_recvfrom(new_sock, 0, NULL, NULL);
677 
678 	test_close(new_sock);
679 	test_close(s_sock);
680 	test_close(c_sock);
681 
682 	k_sleep(TCP_TEARDOWN_TIMEOUT);
683 }
684 
ZTEST_USER(net_socket_tcp,test_v6_sendto_recvfrom_null_dest)685 ZTEST_USER(net_socket_tcp, test_v6_sendto_recvfrom_null_dest)
686 {
687 	/* For a stream socket, sendto() should ignore NULL dest address */
688 	int c_sock;
689 	int s_sock;
690 	int new_sock;
691 	struct sockaddr_in6 c_saddr;
692 	struct sockaddr_in6 s_saddr;
693 	struct sockaddr addr;
694 	socklen_t addrlen = sizeof(addr);
695 
696 	prepare_sock_tcp_v6(MY_IPV6_ADDR, ANY_PORT, &c_sock, &c_saddr);
697 	prepare_sock_tcp_v6(MY_IPV6_ADDR, SERVER_PORT, &s_sock, &s_saddr);
698 
699 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
700 	test_listen(s_sock);
701 
702 	test_connect(c_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
703 	test_sendto(c_sock, TEST_STR_SMALL, strlen(TEST_STR_SMALL), 0,
704 		    (struct sockaddr *)&s_saddr, sizeof(s_saddr));
705 
706 	test_accept(s_sock, &new_sock, &addr, &addrlen);
707 	zassert_equal(addrlen, sizeof(struct sockaddr_in6), "wrong addrlen");
708 
709 	test_recvfrom(new_sock, 0, NULL, NULL);
710 
711 	test_close(new_sock);
712 	test_close(s_sock);
713 	test_close(c_sock);
714 
715 	k_sleep(TCP_TEARDOWN_TIMEOUT);
716 }
717 
ZTEST_USER(net_socket_tcp,test_v4_sendto_recvmsg)718 ZTEST_USER(net_socket_tcp, test_v4_sendto_recvmsg)
719 {
720 	int c_sock;
721 	int s_sock;
722 	int new_sock;
723 	struct sockaddr_in c_saddr;
724 	struct sockaddr_in s_saddr;
725 	struct sockaddr addr;
726 	socklen_t addrlen = sizeof(addr);
727 #define MAX_BUF_LEN 64
728 #define SMALL_BUF_LEN (sizeof(TEST_STR_SMALL) - 1 - 2)
729 	char buf[MAX_BUF_LEN];
730 	char buf2[SMALL_BUF_LEN];
731 	char buf3[MAX_BUF_LEN];
732 	struct iovec io_vector[3];
733 	struct msghdr msg;
734 	int i, len;
735 
736 	prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &c_sock, &c_saddr);
737 	prepare_sock_tcp_v4(MY_IPV4_ADDR, SERVER_PORT, &s_sock, &s_saddr);
738 
739 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
740 	test_listen(s_sock);
741 
742 	test_connect(c_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
743 	test_sendto(c_sock, TEST_STR_SMALL, strlen(TEST_STR_SMALL), 0,
744 		    (struct sockaddr *)&s_saddr, sizeof(s_saddr));
745 
746 	test_accept(s_sock, &new_sock, &addr, &addrlen);
747 	zassert_equal(addrlen, sizeof(struct sockaddr_in), "wrong addrlen");
748 
749 	/* Read data first in one chunk */
750 	io_vector[0].iov_base = buf;
751 	io_vector[0].iov_len = sizeof(buf);
752 
753 	memset(&msg, 0, sizeof(msg));
754 	msg.msg_iov = io_vector;
755 	msg.msg_iovlen = 1;
756 	msg.msg_name = &addr;
757 	msg.msg_namelen = addrlen;
758 
759 	test_recvmsg(new_sock, &msg, ZSOCK_MSG_PEEK, strlen(TEST_STR_SMALL),
760 		     __LINE__);
761 	zassert_mem_equal(buf, TEST_STR_SMALL, strlen(TEST_STR_SMALL),
762 			  "wrong data (%s)", buf);
763 
764 	/* Then in two chunks */
765 	io_vector[0].iov_base = buf2;
766 	io_vector[0].iov_len = sizeof(buf2);
767 	io_vector[1].iov_base = buf;
768 	io_vector[1].iov_len = sizeof(buf);
769 
770 	memset(&msg, 0, sizeof(msg));
771 	msg.msg_iov = io_vector;
772 	msg.msg_iovlen = 2;
773 	msg.msg_name = &addr;
774 	msg.msg_namelen = addrlen;
775 
776 	test_recvmsg(new_sock, &msg, 0, strlen(TEST_STR_SMALL), __LINE__);
777 	zassert_mem_equal(msg.msg_iov[0].iov_base, TEST_STR_SMALL, msg.msg_iov[0].iov_len,
778 			  "wrong data in %s", "iov[0]");
779 	zassert_mem_equal(msg.msg_iov[1].iov_base, &TEST_STR_SMALL[msg.msg_iov[0].iov_len],
780 			  msg.msg_iov[1].iov_len,
781 			  "wrong data in %s", "iov[1]");
782 
783 	/* Send larger test buffer */
784 	test_sendto(c_sock, TEST_STR_LONG, strlen(TEST_STR_LONG), 0,
785 		    (struct sockaddr *)&s_saddr, sizeof(s_saddr));
786 
787 	/* Verify that the data is truncated */
788 	io_vector[0].iov_base = buf;
789 	io_vector[0].iov_len = sizeof(buf);
790 	io_vector[1].iov_base = buf2;
791 	io_vector[1].iov_len = sizeof(buf2);
792 	io_vector[2].iov_base = buf3;
793 	io_vector[2].iov_len = sizeof(buf3);
794 
795 	memset(&msg, 0, sizeof(msg));
796 	msg.msg_iov = io_vector;
797 	msg.msg_iovlen = 3;
798 	msg.msg_name = &addr;
799 	msg.msg_namelen = addrlen;
800 
801 	for (i = 0, len = 0; i < msg.msg_iovlen; i++) {
802 		len += msg.msg_iov[i].iov_len;
803 	}
804 
805 	test_recvmsg(new_sock, &msg, 0, len, __LINE__);
806 	zassert_mem_equal(msg.msg_iov[0].iov_base, TEST_STR_LONG, msg.msg_iov[0].iov_len,
807 			  "wrong data in %s", "iov[0]");
808 	zassert_mem_equal(msg.msg_iov[1].iov_base, &TEST_STR_LONG[msg.msg_iov[0].iov_len],
809 			  msg.msg_iov[1].iov_len,
810 			  "wrong data in %s", "iov[1]");
811 	zassert_mem_equal(msg.msg_iov[2].iov_base,
812 			  &TEST_STR_LONG[msg.msg_iov[0].iov_len + msg.msg_iov[1].iov_len],
813 			  msg.msg_iov[2].iov_len,
814 			  "wrong data in %s", "iov[2]");
815 
816 	test_close(new_sock);
817 	test_close(s_sock);
818 	test_close(c_sock);
819 
820 	k_sleep(TCP_TEARDOWN_TIMEOUT);
821 }
822 
_test_recv_enotconn(int c_sock,int s_sock)823 void _test_recv_enotconn(int c_sock, int s_sock)
824 {
825 	char rx_buf[1] = {0};
826 	int res;
827 
828 	test_listen(s_sock);
829 
830 	/* Check "client" socket, just created. */
831 	res = zsock_recv(c_sock, rx_buf, sizeof(rx_buf), 0);
832 	zassert_equal(res, -1, "recv() on not connected sock didn't fail");
833 	zassert_equal(errno, ENOTCONN, "recv() on not connected sock didn't "
834 				       "lead to ENOTCONN");
835 
836 	/* Check "server" socket, bound and listen()ed . */
837 	res = zsock_recv(s_sock, rx_buf, sizeof(rx_buf), 0);
838 	zassert_equal(res, -1, "recv() on not connected sock didn't fail");
839 	zassert_equal(errno, ENOTCONN, "recv() on not connected sock didn't "
840 				       "lead to ENOTCONN");
841 
842 	test_close(s_sock);
843 	test_close(c_sock);
844 
845 	k_sleep(TCP_TEARDOWN_TIMEOUT);
846 }
847 
ZTEST_USER(net_socket_tcp,test_v4_recv_enotconn)848 ZTEST_USER(net_socket_tcp, test_v4_recv_enotconn)
849 {
850 	/* For a stream socket, recv() without connect() or accept()
851 	 * should lead to ENOTCONN.
852 	 */
853 	int c_sock, s_sock;
854 	struct sockaddr_in c_saddr, s_saddr;
855 
856 	prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &c_sock, &c_saddr);
857 	prepare_sock_tcp_v4(MY_IPV4_ADDR, SERVER_PORT, &s_sock, &s_saddr);
858 
859 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
860 
861 	_test_recv_enotconn(c_sock, s_sock);
862 }
863 
ZTEST_USER(net_socket_tcp,test_v6_recv_enotconn)864 ZTEST_USER(net_socket_tcp, test_v6_recv_enotconn)
865 {
866 	/* For a stream socket, recv() without connect() or accept()
867 	 * should lead to ENOTCONN.
868 	 */
869 	int c_sock, s_sock;
870 	struct sockaddr_in6 c_saddr, s_saddr;
871 
872 	prepare_sock_tcp_v6(MY_IPV6_ADDR, ANY_PORT, &c_sock, &c_saddr);
873 	prepare_sock_tcp_v6(MY_IPV6_ADDR, SERVER_PORT, &s_sock, &s_saddr);
874 
875 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
876 
877 	_test_recv_enotconn(c_sock, s_sock);
878 }
879 
ZTEST_USER(net_socket_tcp,test_shutdown_rd_synchronous)880 ZTEST_USER(net_socket_tcp, test_shutdown_rd_synchronous)
881 {
882 	/* recv() after shutdown(..., ZSOCK_SHUT_RD) should return 0 (EOF).
883 	 */
884 	int c_sock;
885 	int s_sock;
886 	int new_sock;
887 	struct sockaddr_in6 c_saddr, s_saddr;
888 	struct sockaddr addr;
889 	socklen_t addrlen = sizeof(addr);
890 
891 	prepare_sock_tcp_v6(MY_IPV6_ADDR, ANY_PORT, &c_sock, &c_saddr);
892 	prepare_sock_tcp_v6(MY_IPV6_ADDR, SERVER_PORT, &s_sock, &s_saddr);
893 
894 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
895 	test_listen(s_sock);
896 
897 	/* Connect and accept that connection */
898 	test_connect(c_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
899 
900 	test_accept(s_sock, &new_sock, &addr, &addrlen);
901 
902 	/* Shutdown reception */
903 	test_shutdown(c_sock, ZSOCK_SHUT_RD);
904 
905 	/* EOF should be notified by recv() */
906 	test_eof(c_sock);
907 
908 	test_close(new_sock);
909 	test_close(s_sock);
910 	test_close(c_sock);
911 
912 	k_sleep(TCP_TEARDOWN_TIMEOUT);
913 }
914 
915 struct shutdown_data {
916 	struct k_work_delayable work;
917 	int fd;
918 	int how;
919 };
920 
shutdown_work(struct k_work * work)921 static void shutdown_work(struct k_work *work)
922 {
923 	struct k_work_delayable *dwork = k_work_delayable_from_work(work);
924 	struct shutdown_data *data = CONTAINER_OF(dwork, struct shutdown_data,
925 						  work);
926 
927 	zsock_shutdown(data->fd, data->how);
928 }
929 
ZTEST(net_socket_tcp,test_shutdown_rd_while_recv)930 ZTEST(net_socket_tcp, test_shutdown_rd_while_recv)
931 {
932 	/* Blocking recv() should return EOF after shutdown(..., ZSOCK_SHUT_RD) is
933 	 * called from another thread.
934 	 */
935 	int c_sock;
936 	int s_sock;
937 	int new_sock;
938 	struct sockaddr_in6 c_saddr, s_saddr;
939 	struct sockaddr addr;
940 	socklen_t addrlen = sizeof(addr);
941 	struct shutdown_data shutdown_work_data;
942 
943 	prepare_sock_tcp_v6(MY_IPV6_ADDR, ANY_PORT, &c_sock, &c_saddr);
944 	prepare_sock_tcp_v6(MY_IPV6_ADDR, SERVER_PORT, &s_sock, &s_saddr);
945 
946 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
947 	test_listen(s_sock);
948 
949 	/* Connect and accept that connection */
950 	test_connect(c_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
951 
952 	test_accept(s_sock, &new_sock, &addr, &addrlen);
953 
954 	/* Schedule reception shutdown from workqueue */
955 	k_work_init_delayable(&shutdown_work_data.work, shutdown_work);
956 	shutdown_work_data.fd = c_sock;
957 	shutdown_work_data.how = ZSOCK_SHUT_RD;
958 	k_work_schedule(&shutdown_work_data.work, K_MSEC(10));
959 
960 	/* Start blocking recv(), which should be unblocked by shutdown() from
961 	 * another thread and return EOF (0).
962 	 */
963 	test_eof(c_sock);
964 
965 	test_close(new_sock);
966 	test_close(s_sock);
967 	test_close(c_sock);
968 
969 	test_context_cleanup();
970 }
971 
ZTEST(net_socket_tcp,test_open_close_immediately)972 ZTEST(net_socket_tcp, test_open_close_immediately)
973 {
974 	/* Test if socket closing works if done immediately after
975 	 * receiving SYN.
976 	 */
977 	int count_before = 0, count_after = 0;
978 	struct sockaddr_in c_saddr;
979 	struct sockaddr_in s_saddr;
980 	int c_sock;
981 	int s_sock;
982 
983 	test_context_cleanup();
984 
985 	prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &c_sock, &c_saddr);
986 	prepare_sock_tcp_v4(MY_IPV4_ADDR, SERVER_PORT, &s_sock, &s_saddr);
987 
988 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
989 	test_listen(s_sock);
990 
991 	/* We should have two contexts open now */
992 	net_context_foreach(calc_net_context, &count_before);
993 
994 	/* Try to connect to a port that is not accepting connections.
995 	 * The end result should be that we do not leak net_context.
996 	 */
997 	s_saddr.sin_port = htons(SERVER_PORT + 1);
998 
999 	zassert_not_equal(zsock_connect(c_sock, (struct sockaddr *)&s_saddr,
1000 					sizeof(s_saddr)),
1001 			  0, "connect succeed");
1002 
1003 	test_close(c_sock);
1004 
1005 	/* Allow for the close communication to finish,
1006 	 * this makes the test success, no longer scheduling dependent
1007 	 */
1008 	k_sleep(K_MSEC(CONFIG_NET_TCP_INIT_RETRANSMISSION_TIMEOUT / 2));
1009 
1010 	/* After the client socket closing, the context count should be 1 */
1011 	net_context_foreach(calc_net_context, &count_after);
1012 
1013 	test_close(s_sock);
1014 
1015 	/* Although closing a server socket does not require communication,
1016 	 * wait a little to make the test robust to scheduling order
1017 	 */
1018 	k_sleep(K_MSEC(CONFIG_NET_TCP_INIT_RETRANSMISSION_TIMEOUT / 2));
1019 
1020 	zassert_equal(count_before - 1, count_after,
1021 		      "net_context still in use (before %d vs after %d)",
1022 		      count_before - 1, count_after);
1023 
1024 	/* No need to wait here, as the test success depends on the socket being closed */
1025 	test_context_cleanup();
1026 }
1027 
ZTEST(net_socket_tcp,test_connect_timeout)1028 ZTEST(net_socket_tcp, test_connect_timeout)
1029 {
1030 	/* Test if socket connect fails when there is not communication
1031 	 * possible.
1032 	 */
1033 	int count_after = 0;
1034 	struct sockaddr_in c_saddr;
1035 	struct sockaddr_in s_saddr;
1036 	int c_sock;
1037 	int rv;
1038 
1039 	restore_packet_loss_ratio();
1040 
1041 	prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &c_sock, &c_saddr);
1042 
1043 	s_saddr.sin_family = AF_INET;
1044 	s_saddr.sin_port = htons(SERVER_PORT);
1045 	rv = zsock_inet_pton(AF_INET, MY_IPV4_ADDR, &s_saddr.sin_addr);
1046 	zassert_equal(rv, 1, "inet_pton failed");
1047 
1048 	loopback_set_packet_drop_ratio(1.0f);
1049 
1050 	zassert_equal(zsock_connect(c_sock, (struct sockaddr *)&s_saddr,
1051 				    sizeof(s_saddr)),
1052 		      -1, "connect succeed");
1053 
1054 	zassert_equal(errno, ETIMEDOUT,
1055 			    "connect should be timed out, got %i", errno);
1056 
1057 	test_close(c_sock);
1058 
1059 	/* Sleep here in order to allow other part of the system to run and
1060 	 * update itself.
1061 	 */
1062 	k_sleep(K_MSEC(10));
1063 
1064 	/* After the client socket closing, the context count should be 0 */
1065 	net_context_foreach(calc_net_context, &count_after);
1066 
1067 	zassert_equal(count_after, 0,
1068 		      "net_context %d still in use", count_after);
1069 
1070 	restore_packet_loss_ratio();
1071 }
1072 
1073 #define ASYNC_POLL_TIMEOUT 2000
1074 #define POLL_FDS_NUM 1
1075 
1076 
ZTEST(net_socket_tcp,test_async_connect_timeout)1077 ZTEST(net_socket_tcp, test_async_connect_timeout)
1078 {
1079 	/* Test if asynchronous socket connect fails when there is no communication
1080 	 * possible.
1081 	 */
1082 	struct sockaddr_in c_saddr;
1083 	struct sockaddr_in s_saddr;
1084 	int c_sock;
1085 	int rv;
1086 	struct zsock_pollfd poll_fds[POLL_FDS_NUM];
1087 
1088 	loopback_set_packet_drop_ratio(1.0f);
1089 
1090 	prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &c_sock, &c_saddr);
1091 	test_fcntl(c_sock, F_SETFL, O_NONBLOCK);
1092 	s_saddr.sin_family = AF_INET;
1093 	s_saddr.sin_port = htons(SERVER_PORT);
1094 	rv = zsock_inet_pton(AF_INET, MY_IPV4_ADDR, &s_saddr.sin_addr);
1095 	zassert_equal(rv, 1, "inet_pton failed");
1096 
1097 	rv = zsock_connect(c_sock, (struct sockaddr *)&s_saddr,
1098 			   sizeof(s_saddr));
1099 	zassert_equal(rv, -1, "connect should not succeed");
1100 	zassert_equal(errno, EINPROGRESS,
1101 		      "connect should be in progress, got %i", errno);
1102 
1103 	poll_fds[0].fd = c_sock;
1104 	poll_fds[0].events = ZSOCK_POLLOUT;
1105 	int poll_rc = zsock_poll(poll_fds, POLL_FDS_NUM, ASYNC_POLL_TIMEOUT);
1106 
1107 	zassert_equal(poll_rc, 1, "poll should return 1, got %i", poll_rc);
1108 	zassert_equal(poll_fds[0].revents, ZSOCK_POLLERR,
1109 		      "poll should set error event");
1110 
1111 	test_close(c_sock);
1112 
1113 	test_context_cleanup();
1114 
1115 	restore_packet_loss_ratio();
1116 }
1117 
ZTEST(net_socket_tcp,test_async_connect)1118 ZTEST(net_socket_tcp, test_async_connect)
1119 {
1120 	int c_sock;
1121 	int s_sock;
1122 	int new_sock;
1123 	struct sockaddr_in c_saddr;
1124 	struct sockaddr_in s_saddr;
1125 	struct sockaddr addr;
1126 	socklen_t addrlen = sizeof(addr);
1127 	struct zsock_pollfd poll_fds[1];
1128 	int poll_rc;
1129 
1130 	prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &c_sock, &c_saddr);
1131 	prepare_sock_tcp_v4(MY_IPV4_ADDR, SERVER_PORT, &s_sock, &s_saddr);
1132 	test_fcntl(c_sock, F_SETFL, O_NONBLOCK);
1133 
1134 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
1135 	test_listen(s_sock);
1136 
1137 	zassert_equal(zsock_connect(c_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr)),
1138 		      -1,
1139 		      "connect shouldn't complete right away");
1140 
1141 	zassert_equal(errno, EINPROGRESS,
1142 		      "connect should be in progress, got %i", errno);
1143 
1144 	poll_fds[0].fd = c_sock;
1145 	poll_fds[0].events = ZSOCK_POLLOUT;
1146 	poll_rc = zsock_poll(poll_fds, 1, ASYNC_POLL_TIMEOUT);
1147 	zassert_equal(poll_rc, 1, "poll should return 1, got %i", poll_rc);
1148 	zassert_equal(poll_fds[0].revents, ZSOCK_POLLOUT,
1149 		      "poll should set POLLOUT");
1150 
1151 	test_accept(s_sock, &new_sock, &addr, &addrlen);
1152 	zassert_equal(addrlen, sizeof(struct sockaddr_in), "Wrong addrlen");
1153 
1154 	test_close(c_sock);
1155 	test_close(s_sock);
1156 	test_close(new_sock);
1157 
1158 	test_context_cleanup();
1159 }
1160 
1161 #define TCP_CLOSE_FAILURE_TIMEOUT 90000
1162 
ZTEST(net_socket_tcp,test_z_close_obstructed)1163 ZTEST(net_socket_tcp, test_z_close_obstructed)
1164 {
1165 	/* Test if socket closing even when there is not communication
1166 	 * possible any more
1167 	 */
1168 	int count_before = 0, count_after = 0;
1169 	struct sockaddr_in c_saddr;
1170 	struct sockaddr_in s_saddr;
1171 	struct sockaddr addr;
1172 	socklen_t addrlen = sizeof(addr);
1173 	int c_sock;
1174 	int s_sock;
1175 	int new_sock;
1176 	int dropped_packets_before = 0;
1177 	int dropped_packets_after = 0;
1178 
1179 	restore_packet_loss_ratio();
1180 
1181 	prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &c_sock, &c_saddr);
1182 	prepare_sock_tcp_v4(MY_IPV4_ADDR, SERVER_PORT, &s_sock, &s_saddr);
1183 
1184 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
1185 	test_listen(s_sock);
1186 
1187 	zassert_equal(zsock_connect(c_sock, (struct sockaddr *)&s_saddr,
1188 				    sizeof(s_saddr)),
1189 		      0, "connect not succeed");
1190 	test_accept(s_sock, &new_sock, &addr, &addrlen);
1191 
1192 	/* We should have two contexts open now */
1193 	net_context_foreach(calc_net_context, &count_before);
1194 
1195 	/* Break the communication */
1196 	loopback_set_packet_drop_ratio(1.0f);
1197 
1198 	dropped_packets_before = loopback_get_num_dropped_packets();
1199 
1200 	test_close(c_sock);
1201 
1202 	wait_for_n_tcp_contexts(count_before-1, K_MSEC(TCP_CLOSE_FAILURE_TIMEOUT));
1203 
1204 	net_context_foreach(calc_net_context, &count_after);
1205 
1206 	zassert_equal(count_before - 1, count_after,
1207 		      "net_context still in use (before %d vs after %d)",
1208 		      count_before - 1, count_after);
1209 
1210 	dropped_packets_after = loopback_get_num_dropped_packets();
1211 	int dropped_packets = dropped_packets_after - dropped_packets_before;
1212 
1213 	/* At least some packet should have been dropped */
1214 	zassert_equal(dropped_packets,
1215 			CONFIG_NET_TCP_RETRY_COUNT + 1,
1216 			"Incorrect number of FIN retries, got %i, expected %i",
1217 			dropped_packets, CONFIG_NET_TCP_RETRY_COUNT+1);
1218 
1219 	test_close(new_sock);
1220 	test_close(s_sock);
1221 
1222 	test_context_cleanup();
1223 
1224 	/* After everything is closed, we expect no more dropped packets */
1225 	dropped_packets_before = loopback_get_num_dropped_packets();
1226 	k_sleep(K_SECONDS(2));
1227 	dropped_packets_after = loopback_get_num_dropped_packets();
1228 
1229 	zassert_equal(dropped_packets_before, dropped_packets_after,
1230 		      "packets after close");
1231 
1232 	restore_packet_loss_ratio();
1233 }
1234 
ZTEST_USER(net_socket_tcp,test_v4_accept_timeout)1235 ZTEST_USER(net_socket_tcp, test_v4_accept_timeout)
1236 {
1237 	/* Test if accept() will timeout properly */
1238 	int s_sock;
1239 	int new_sock;
1240 	uint32_t tstamp;
1241 	struct sockaddr_in s_saddr;
1242 	struct sockaddr addr;
1243 	socklen_t addrlen = sizeof(addr);
1244 
1245 	prepare_sock_tcp_v4(MY_IPV4_ADDR, SERVER_PORT, &s_sock, &s_saddr);
1246 
1247 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
1248 	test_listen(s_sock);
1249 
1250 	test_fcntl(s_sock, F_SETFL, O_NONBLOCK);
1251 
1252 	tstamp = k_uptime_get_32();
1253 	test_accept_timeout(s_sock, &new_sock, &addr, &addrlen);
1254 	zassert_true(k_uptime_get_32() - tstamp <= 100, "");
1255 
1256 	test_close(s_sock);
1257 
1258 	k_sleep(TCP_TEARDOWN_TIMEOUT);
1259 }
1260 
ZTEST(net_socket_tcp,test_so_type)1261 ZTEST(net_socket_tcp, test_so_type)
1262 {
1263 	struct sockaddr_in bind_addr4;
1264 	struct sockaddr_in6 bind_addr6;
1265 	int sock1, sock2, rv;
1266 	int optval;
1267 	socklen_t optlen = sizeof(optval);
1268 
1269 	zassert_equal(wait_for_n_tcp_contexts(0, TCP_TEARDOWN_TIMEOUT),
1270 		      0,
1271 		      "Not all TCP contexts properly cleaned up");
1272 
1273 	prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &sock1, &bind_addr4);
1274 	prepare_sock_tcp_v6(MY_IPV6_ADDR, ANY_PORT, &sock2, &bind_addr6);
1275 
1276 	rv = zsock_getsockopt(sock1, SOL_SOCKET, SO_TYPE, &optval, &optlen);
1277 	zassert_equal(rv, 0, "getsockopt failed (%d)", errno);
1278 	zassert_equal(optval, SOCK_STREAM, "getsockopt got invalid type");
1279 	zassert_equal(optlen, sizeof(optval), "getsockopt got invalid size");
1280 
1281 	rv = zsock_getsockopt(sock2, SOL_SOCKET, SO_TYPE, &optval, &optlen);
1282 	zassert_equal(rv, 0, "getsockopt failed (%d)", errno);
1283 	zassert_equal(optval, SOCK_STREAM, "getsockopt got invalid type");
1284 	zassert_equal(optlen, sizeof(optval), "getsockopt got invalid size");
1285 
1286 	test_close(sock1);
1287 	test_close(sock2);
1288 
1289 	zassert_equal(wait_for_n_tcp_contexts(0, TCP_TEARDOWN_TIMEOUT),
1290 		      0,
1291 		      "Not all TCP contexts properly cleaned up");
1292 }
1293 
ZTEST(net_socket_tcp,test_so_protocol)1294 ZTEST(net_socket_tcp, test_so_protocol)
1295 {
1296 	struct sockaddr_in bind_addr4;
1297 	struct sockaddr_in6 bind_addr6;
1298 	int sock1, sock2, rv;
1299 	int optval;
1300 	socklen_t optlen = sizeof(optval);
1301 
1302 	prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &sock1, &bind_addr4);
1303 	prepare_sock_tcp_v6(MY_IPV6_ADDR, ANY_PORT, &sock2, &bind_addr6);
1304 
1305 	rv = zsock_getsockopt(sock1, SOL_SOCKET, SO_PROTOCOL, &optval, &optlen);
1306 	zassert_equal(rv, 0, "getsockopt failed (%d)", errno);
1307 	zassert_equal(optval, IPPROTO_TCP, "getsockopt got invalid protocol");
1308 	zassert_equal(optlen, sizeof(optval), "getsockopt got invalid size");
1309 
1310 	rv = zsock_getsockopt(sock2, SOL_SOCKET, SO_PROTOCOL, &optval, &optlen);
1311 	zassert_equal(rv, 0, "getsockopt failed (%d)", errno);
1312 	zassert_equal(optval, IPPROTO_TCP, "getsockopt got invalid protocol");
1313 	zassert_equal(optlen, sizeof(optval), "getsockopt got invalid size");
1314 
1315 	test_close(sock1);
1316 	test_close(sock2);
1317 
1318 	test_context_cleanup();
1319 }
1320 
ZTEST(net_socket_tcp,test_so_rcvbuf)1321 ZTEST(net_socket_tcp, test_so_rcvbuf)
1322 {
1323 	struct sockaddr_in bind_addr4;
1324 	struct sockaddr_in6 bind_addr6;
1325 	int sock1, sock2, rv;
1326 	int  retval;
1327 	int optval = UINT16_MAX;
1328 	socklen_t optlen = sizeof(optval);
1329 
1330 	prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &sock1, &bind_addr4);
1331 	prepare_sock_tcp_v6(MY_IPV6_ADDR, ANY_PORT, &sock2, &bind_addr6);
1332 
1333 	rv = zsock_setsockopt(sock1, SOL_SOCKET, SO_RCVBUF, &optval, sizeof(optval));
1334 	zassert_equal(rv, 0, "setsockopt failed (%d)", rv);
1335 	rv = zsock_getsockopt(sock1, SOL_SOCKET, SO_RCVBUF, &retval, &optlen);
1336 	zassert_equal(rv, 0, "getsockopt failed (%d)", rv);
1337 	zassert_equal(retval, optval, "getsockopt got invalid rcvbuf");
1338 	zassert_equal(optlen, sizeof(optval), "getsockopt got invalid size");
1339 
1340 	rv = zsock_setsockopt(sock2, SOL_SOCKET, SO_RCVBUF, &optval, sizeof(optval));
1341 	zassert_equal(rv, 0, "setsockopt failed (%d)", rv);
1342 	rv = zsock_getsockopt(sock2, SOL_SOCKET, SO_RCVBUF, &retval, &optlen);
1343 	zassert_equal(rv, 0, "getsockopt failed (%d)", rv);
1344 	zassert_equal(retval, optval, "getsockopt got invalid rcvbuf");
1345 	zassert_equal(optlen, sizeof(optval), "getsockopt got invalid size");
1346 
1347 	optval = -1;
1348 	rv = zsock_setsockopt(sock2, SOL_SOCKET, SO_RCVBUF, &optval, sizeof(optval));
1349 	zassert_equal(rv, -1, "setsockopt failed (%d)", rv);
1350 
1351 	optval = UINT16_MAX + 1;
1352 	rv = zsock_setsockopt(sock2, SOL_SOCKET, SO_RCVBUF, &optval, sizeof(optval));
1353 	zassert_equal(rv, -1, "setsockopt failed (%d)", rv);
1354 
1355 	test_close(sock1);
1356 	test_close(sock2);
1357 
1358 	test_context_cleanup();
1359 }
1360 
ZTEST(net_socket_tcp,test_so_rcvbuf_win_size)1361 ZTEST(net_socket_tcp, test_so_rcvbuf_win_size)
1362 {
1363 	int rv;
1364 	int c_sock;
1365 	int s_sock;
1366 	int new_sock;
1367 	struct sockaddr_in c_saddr;
1368 	struct sockaddr_in s_saddr;
1369 	struct sockaddr addr;
1370 	socklen_t addrlen = sizeof(addr);
1371 	char tx_buf[] = TEST_STR_SMALL;
1372 	int buf_optval = sizeof(TEST_STR_SMALL);
1373 
1374 	prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &c_sock, &c_saddr);
1375 	prepare_sock_tcp_v4(MY_IPV4_ADDR, SERVER_PORT, &s_sock, &s_saddr);
1376 
1377 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
1378 	test_listen(s_sock);
1379 
1380 	test_connect(c_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
1381 
1382 	test_accept(s_sock, &new_sock, &addr, &addrlen);
1383 	zassert_equal(addrlen, sizeof(struct sockaddr_in), "wrong addrlen");
1384 
1385 	/* Lower server-side RX window size. */
1386 	rv = zsock_setsockopt(new_sock, SOL_SOCKET, SO_RCVBUF, &buf_optval,
1387 			      sizeof(buf_optval));
1388 	zassert_equal(rv, 0, "setsockopt failed (%d)", errno);
1389 
1390 	rv = zsock_send(c_sock, tx_buf, sizeof(tx_buf), ZSOCK_MSG_DONTWAIT);
1391 	zassert_equal(rv, sizeof(tx_buf), "Unexpected return code %d", rv);
1392 
1393 	/* Window should've dropped to 0, so the ACK will be delayed - wait for
1394 	 * it to arrive, so that the client is aware of the new window size.
1395 	 */
1396 	k_msleep(150);
1397 
1398 	/* Client should not be able to send now (RX window full). */
1399 	rv = zsock_send(c_sock, tx_buf, 1, ZSOCK_MSG_DONTWAIT);
1400 	zassert_equal(rv, -1, "Unexpected return code %d", rv);
1401 	zassert_equal(errno, EAGAIN, "Unexpected errno value: %d", errno);
1402 
1403 	test_close(c_sock);
1404 	test_close(new_sock);
1405 	test_close(s_sock);
1406 
1407 	test_context_cleanup();
1408 }
1409 
ZTEST(net_socket_tcp,test_so_sndbuf)1410 ZTEST(net_socket_tcp, test_so_sndbuf)
1411 {
1412 	struct sockaddr_in bind_addr4;
1413 	struct sockaddr_in6 bind_addr6;
1414 	int sock1, sock2, rv;
1415 	int retval;
1416 	int optval = UINT16_MAX;
1417 	socklen_t optlen = sizeof(optval);
1418 
1419 	prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &sock1, &bind_addr4);
1420 	prepare_sock_tcp_v6(MY_IPV6_ADDR, ANY_PORT, &sock2, &bind_addr6);
1421 
1422 	rv = zsock_setsockopt(sock1, SOL_SOCKET, SO_SNDBUF, &optval, sizeof(optval));
1423 	zassert_equal(rv, 0, "setsockopt failed (%d)", rv);
1424 	rv = zsock_getsockopt(sock1, SOL_SOCKET, SO_SNDBUF, &retval, &optlen);
1425 	zassert_equal(rv, 0, "getsockopt failed (%d)", rv);
1426 	zassert_equal(retval, optval, "getsockopt got invalid rcvbuf");
1427 	zassert_equal(optlen, sizeof(optval), "getsockopt got invalid size");
1428 
1429 	rv = zsock_setsockopt(sock2, SOL_SOCKET, SO_SNDBUF, &optval, sizeof(optval));
1430 	zassert_equal(rv, 0, "setsockopt failed (%d)", rv);
1431 	rv = zsock_getsockopt(sock2, SOL_SOCKET, SO_SNDBUF, &retval, &optlen);
1432 	zassert_equal(rv, 0, "getsockopt failed (%d)", rv);
1433 	zassert_equal(retval, optval, "getsockopt got invalid rcvbuf");
1434 	zassert_equal(optlen, sizeof(optval), "getsockopt got invalid size");
1435 
1436 	optval = -1;
1437 	rv = zsock_setsockopt(sock2, SOL_SOCKET, SO_SNDBUF, &optval, sizeof(optval));
1438 	zassert_equal(rv, -1, "setsockopt failed (%d)", rv);
1439 
1440 	optval = UINT16_MAX + 1;
1441 	rv = zsock_setsockopt(sock2, SOL_SOCKET, SO_RCVBUF, &optval, sizeof(optval));
1442 	zassert_equal(rv, -1, "setsockopt failed (%d)", rv);
1443 
1444 	test_close(sock1);
1445 	test_close(sock2);
1446 
1447 	test_context_cleanup();
1448 }
1449 
ZTEST(net_socket_tcp,test_so_sndbuf_win_size)1450 ZTEST(net_socket_tcp, test_so_sndbuf_win_size)
1451 {
1452 	int rv;
1453 	int c_sock;
1454 	int s_sock;
1455 	int new_sock;
1456 	struct sockaddr_in c_saddr;
1457 	struct sockaddr_in s_saddr;
1458 	struct sockaddr addr;
1459 	socklen_t addrlen = sizeof(addr);
1460 	char tx_buf[] = TEST_STR_SMALL;
1461 	int buf_optval = sizeof(TEST_STR_SMALL);
1462 
1463 	prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &c_sock, &c_saddr);
1464 	prepare_sock_tcp_v4(MY_IPV4_ADDR, SERVER_PORT, &s_sock, &s_saddr);
1465 
1466 	/* Lower client-side TX window size. */
1467 	rv = zsock_setsockopt(c_sock, SOL_SOCKET, SO_SNDBUF, &buf_optval,
1468 			      sizeof(buf_optval));
1469 	zassert_equal(rv, 0, "setsockopt failed (%d)", errno);
1470 
1471 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
1472 	test_listen(s_sock);
1473 
1474 	test_connect(c_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
1475 
1476 	test_accept(s_sock, &new_sock, &addr, &addrlen);
1477 	zassert_equal(addrlen, sizeof(struct sockaddr_in), "wrong addrlen");
1478 
1479 	/* Make sure the ACK from the server does not arrive. */
1480 	loopback_set_packet_drop_ratio(1.0f);
1481 
1482 	rv = zsock_send(c_sock, tx_buf, sizeof(tx_buf), ZSOCK_MSG_DONTWAIT);
1483 	zassert_equal(rv, sizeof(tx_buf), "Unexpected return code %d", rv);
1484 
1485 	/* Client should not be able to send now (TX window full). */
1486 	rv = zsock_send(c_sock, tx_buf, 1, ZSOCK_MSG_DONTWAIT);
1487 	zassert_equal(rv, -1, "Unexpected return code %d", rv);
1488 	zassert_equal(errno, EAGAIN, "Unexpected errno value: %d", errno);
1489 
1490 	restore_packet_loss_ratio();
1491 
1492 	test_close(c_sock);
1493 	test_close(new_sock);
1494 	test_close(s_sock);
1495 
1496 	test_context_cleanup();
1497 }
1498 
ZTEST(net_socket_tcp,test_v4_so_rcvtimeo)1499 ZTEST(net_socket_tcp, test_v4_so_rcvtimeo)
1500 {
1501 	int c_sock;
1502 	int s_sock;
1503 	int new_sock;
1504 	struct sockaddr_in c_saddr;
1505 	struct sockaddr_in s_saddr;
1506 	struct sockaddr addr;
1507 	socklen_t addrlen = sizeof(addr);
1508 
1509 	int rv;
1510 	uint32_t start_time, time_diff;
1511 	ssize_t recved = 0;
1512 	char rx_buf[30] = {0};
1513 
1514 	struct timeval optval = {
1515 		.tv_sec = 2,
1516 		.tv_usec = 500000,
1517 	};
1518 
1519 	prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &c_sock, &c_saddr);
1520 	prepare_sock_tcp_v4(MY_IPV4_ADDR, SERVER_PORT, &s_sock, &s_saddr);
1521 
1522 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
1523 	test_listen(s_sock);
1524 
1525 	test_connect(c_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
1526 
1527 	test_accept(s_sock, &new_sock, &addr, &addrlen);
1528 	zassert_equal(addrlen, sizeof(struct sockaddr_in), "wrong addrlen");
1529 
1530 	rv = zsock_setsockopt(c_sock, SOL_SOCKET, SO_RCVTIMEO, &optval,
1531 			      sizeof(optval));
1532 	zassert_equal(rv, 0, "setsockopt failed (%d)", errno);
1533 
1534 	optval.tv_usec = 0;
1535 	rv = zsock_setsockopt(new_sock, SOL_SOCKET, SO_RCVTIMEO, &optval,
1536 			      sizeof(optval));
1537 	zassert_equal(rv, 0, "setsockopt failed (%d)", errno);
1538 
1539 	start_time = k_uptime_get_32();
1540 	recved = zsock_recv(c_sock, rx_buf, sizeof(rx_buf), 0);
1541 	time_diff = k_uptime_get_32() - start_time;
1542 
1543 	zassert_equal(recved, -1, "Unexpected return code");
1544 	zassert_equal(errno, EAGAIN, "Unexpected errno value: %d", errno);
1545 	zassert_true(time_diff >= 2500, "Expected timeout after 2500ms but "
1546 			"was %dms", time_diff);
1547 
1548 	start_time = k_uptime_get_32();
1549 	recved = zsock_recv(new_sock, rx_buf, sizeof(rx_buf), 0);
1550 	time_diff = k_uptime_get_32() - start_time;
1551 
1552 	zassert_equal(recved, -1, "Unexpected return code");
1553 	zassert_equal(errno, EAGAIN, "Unexpected errno value: %d", errno);
1554 	zassert_true(time_diff >= 2000, "Expected timeout after 2000ms but "
1555 			"was %dms", time_diff);
1556 
1557 	test_close(c_sock);
1558 	test_eof(new_sock);
1559 
1560 	test_close(new_sock);
1561 	test_close(s_sock);
1562 
1563 	test_context_cleanup();
1564 }
1565 
ZTEST(net_socket_tcp,test_v6_so_rcvtimeo)1566 ZTEST(net_socket_tcp, test_v6_so_rcvtimeo)
1567 {
1568 	int c_sock;
1569 	int s_sock;
1570 	int new_sock;
1571 	struct sockaddr_in6 c_saddr;
1572 	struct sockaddr_in6 s_saddr;
1573 	struct sockaddr addr;
1574 	socklen_t addrlen = sizeof(addr);
1575 
1576 	int rv;
1577 	uint32_t start_time, time_diff;
1578 	ssize_t recved = 0;
1579 	char rx_buf[30] = {0};
1580 
1581 	struct timeval optval = {
1582 		.tv_sec = 2,
1583 		.tv_usec = 500000,
1584 	};
1585 
1586 	prepare_sock_tcp_v6(MY_IPV6_ADDR, ANY_PORT, &c_sock, &c_saddr);
1587 	prepare_sock_tcp_v6(MY_IPV6_ADDR, SERVER_PORT, &s_sock, &s_saddr);
1588 
1589 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
1590 	test_listen(s_sock);
1591 
1592 	test_connect(c_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
1593 
1594 	test_accept(s_sock, &new_sock, &addr, &addrlen);
1595 	zassert_equal(addrlen, sizeof(struct sockaddr_in6), "wrong addrlen");
1596 
1597 	rv = zsock_setsockopt(c_sock, SOL_SOCKET, SO_RCVTIMEO, &optval,
1598 			      sizeof(optval));
1599 	zassert_equal(rv, 0, "setsockopt failed (%d)", errno);
1600 
1601 	optval.tv_usec = 0;
1602 	rv = zsock_setsockopt(new_sock, SOL_SOCKET, SO_RCVTIMEO, &optval,
1603 			      sizeof(optval));
1604 	zassert_equal(rv, 0, "setsockopt failed (%d)", errno);
1605 
1606 	start_time = k_uptime_get_32();
1607 	recved = zsock_recv(c_sock, rx_buf, sizeof(rx_buf), 0);
1608 	time_diff = k_uptime_get_32() - start_time;
1609 
1610 	zassert_equal(recved, -1, "Unexpected return code");
1611 	zassert_equal(errno, EAGAIN, "Unexpected errno value: %d", errno);
1612 	zassert_true(time_diff >= 2500, "Expected timeout after 2500ms but "
1613 			"was %dms", time_diff);
1614 
1615 	start_time = k_uptime_get_32();
1616 	recved = zsock_recv(new_sock, rx_buf, sizeof(rx_buf), 0);
1617 	time_diff = k_uptime_get_32() - start_time;
1618 
1619 	zassert_equal(recved, -1, "Unexpected return code");
1620 	zassert_equal(errno, EAGAIN, "Unexpected errno value: %d", errno);
1621 	zassert_true(time_diff >= 2000, "Expected timeout after 2000ms but "
1622 			"was %dms", time_diff);
1623 
1624 	test_close(c_sock);
1625 	test_eof(new_sock);
1626 
1627 	test_close(new_sock);
1628 	test_close(s_sock);
1629 
1630 	test_context_cleanup();
1631 }
1632 
ZTEST(net_socket_tcp,test_v4_so_sndtimeo)1633 ZTEST(net_socket_tcp, test_v4_so_sndtimeo)
1634 {
1635 	int rv;
1636 	int c_sock;
1637 	int s_sock;
1638 	int new_sock;
1639 	struct sockaddr_in c_saddr;
1640 	struct sockaddr_in s_saddr;
1641 	struct sockaddr addr;
1642 	socklen_t addrlen = sizeof(addr);
1643 	uint32_t start_time, time_diff;
1644 	char tx_buf[] = TEST_STR_SMALL;
1645 	int buf_optval = sizeof(TEST_STR_SMALL);
1646 	struct timeval timeo_optval = {
1647 		.tv_sec = 0,
1648 		.tv_usec = 200000,
1649 	};
1650 
1651 	prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &c_sock, &c_saddr);
1652 	prepare_sock_tcp_v4(MY_IPV4_ADDR, SERVER_PORT, &s_sock, &s_saddr);
1653 
1654 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
1655 	test_listen(s_sock);
1656 
1657 	test_connect(c_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
1658 
1659 	test_accept(s_sock, &new_sock, &addr, &addrlen);
1660 	zassert_equal(addrlen, sizeof(struct sockaddr_in), "wrong addrlen");
1661 
1662 	rv = zsock_setsockopt(c_sock, SOL_SOCKET, SO_SNDTIMEO, &timeo_optval,
1663 			      sizeof(timeo_optval));
1664 	zassert_equal(rv, 0, "setsockopt failed (%d)", errno);
1665 
1666 	/* Simulate window full scenario with SO_RCVBUF option. */
1667 	rv = zsock_setsockopt(new_sock, SOL_SOCKET, SO_RCVBUF, &buf_optval,
1668 			      sizeof(buf_optval));
1669 	zassert_equal(rv, 0, "setsockopt failed (%d)", errno);
1670 
1671 	rv = zsock_send(c_sock, tx_buf, sizeof(tx_buf), ZSOCK_MSG_DONTWAIT);
1672 	zassert_equal(rv, sizeof(tx_buf), "Unexpected return code %d", rv);
1673 
1674 	/* Wait for ACK (empty window). */
1675 	k_msleep(150);
1676 
1677 	/* Client should not be able to send now and time out after SO_SNDTIMEO */
1678 	start_time = k_uptime_get_32();
1679 	rv = zsock_send(c_sock, tx_buf, 1, 0);
1680 	time_diff = k_uptime_get_32() - start_time;
1681 
1682 	zassert_equal(rv, -1, "Unexpected return code %d", rv);
1683 	zassert_equal(errno, EAGAIN, "Unexpected errno value: %d", errno);
1684 	zassert_true(time_diff >= 200, "Expected timeout after 200ms but "
1685 			"was %dms", time_diff);
1686 
1687 	test_close(c_sock);
1688 	test_close(new_sock);
1689 	test_close(s_sock);
1690 
1691 	test_context_cleanup();
1692 }
1693 
ZTEST(net_socket_tcp,test_v6_so_sndtimeo)1694 ZTEST(net_socket_tcp, test_v6_so_sndtimeo)
1695 {
1696 	int rv;
1697 	int c_sock;
1698 	int s_sock;
1699 	int new_sock;
1700 	struct sockaddr_in6 c_saddr;
1701 	struct sockaddr_in6 s_saddr;
1702 	struct sockaddr addr;
1703 	socklen_t addrlen = sizeof(addr);
1704 	uint32_t start_time, time_diff;
1705 	char tx_buf[] = TEST_STR_SMALL;
1706 	int buf_optval = sizeof(TEST_STR_SMALL);
1707 	struct timeval timeo_optval = {
1708 		.tv_sec = 0,
1709 		.tv_usec = 500000,
1710 	};
1711 
1712 	prepare_sock_tcp_v6(MY_IPV6_ADDR, ANY_PORT, &c_sock, &c_saddr);
1713 	prepare_sock_tcp_v6(MY_IPV6_ADDR, SERVER_PORT, &s_sock, &s_saddr);
1714 
1715 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
1716 	test_listen(s_sock);
1717 
1718 	test_connect(c_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
1719 
1720 	test_accept(s_sock, &new_sock, &addr, &addrlen);
1721 	zassert_equal(addrlen, sizeof(struct sockaddr_in6), "wrong addrlen");
1722 
1723 	rv = zsock_setsockopt(c_sock, SOL_SOCKET, SO_SNDTIMEO, &timeo_optval,
1724 			      sizeof(timeo_optval));
1725 	zassert_equal(rv, 0, "setsockopt failed (%d)", errno);
1726 
1727 	/* Simulate window full scenario with SO_RCVBUF option. */
1728 	rv = zsock_setsockopt(new_sock, SOL_SOCKET, SO_RCVBUF, &buf_optval,
1729 			      sizeof(buf_optval));
1730 	zassert_equal(rv, 0, "setsockopt failed (%d)", errno);
1731 
1732 	rv = zsock_send(c_sock, tx_buf, sizeof(tx_buf), ZSOCK_MSG_DONTWAIT);
1733 	zassert_equal(rv, sizeof(tx_buf), "Unexpected return code %d", rv);
1734 
1735 	/* Wait for ACK (empty window). */
1736 	k_msleep(150);
1737 
1738 	/* Client should not be able to send now and time out after SO_SNDTIMEO */
1739 	start_time = k_uptime_get_32();
1740 	rv = zsock_send(c_sock, tx_buf, 1, 0);
1741 	time_diff = k_uptime_get_32() - start_time;
1742 
1743 	zassert_equal(rv, -1, "Unexpected return code %d", rv);
1744 	zassert_equal(errno, EAGAIN, "Unexpected errno value: %d", errno);
1745 	zassert_true(time_diff >= 500, "Expected timeout after 500ms but "
1746 			"was %dms", time_diff);
1747 
1748 	test_close(c_sock);
1749 	test_close(new_sock);
1750 	test_close(s_sock);
1751 
1752 	test_context_cleanup();
1753 }
1754 
1755 struct test_msg_waitall_data {
1756 	struct k_work_delayable tx_work;
1757 	int sock;
1758 	const uint8_t *data;
1759 	size_t offset;
1760 	int retries;
1761 };
1762 
test_msg_waitall_tx_work_handler(struct k_work * work)1763 static void test_msg_waitall_tx_work_handler(struct k_work *work)
1764 {
1765 	struct k_work_delayable *dwork = k_work_delayable_from_work(work);
1766 	struct test_msg_waitall_data *test_data =
1767 		CONTAINER_OF(dwork, struct test_msg_waitall_data, tx_work);
1768 
1769 	if (test_data->retries > 0) {
1770 		test_send(test_data->sock, test_data->data + test_data->offset, 1, 0);
1771 		test_data->offset++;
1772 		test_data->retries--;
1773 		k_work_reschedule(&test_data->tx_work, K_MSEC(10));
1774 	}
1775 }
1776 
ZTEST(net_socket_tcp,test_v4_msg_waitall)1777 ZTEST(net_socket_tcp, test_v4_msg_waitall)
1778 {
1779 	struct test_msg_waitall_data test_data = {
1780 		.data = TEST_STR_SMALL,
1781 	};
1782 	int c_sock;
1783 	int s_sock;
1784 	int new_sock;
1785 	struct sockaddr_in c_saddr;
1786 	struct sockaddr_in s_saddr;
1787 	struct sockaddr addr;
1788 	socklen_t addrlen = sizeof(addr);
1789 	int ret;
1790 	uint8_t rx_buf[sizeof(TEST_STR_SMALL) - 1] = { 0 };
1791 	struct timeval timeo_optval = {
1792 		.tv_sec = 0,
1793 		.tv_usec = 100000,
1794 	};
1795 
1796 	prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &c_sock, &c_saddr);
1797 	prepare_sock_tcp_v4(MY_IPV4_ADDR, SERVER_PORT, &s_sock, &s_saddr);
1798 
1799 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
1800 	test_listen(s_sock);
1801 
1802 	test_connect(c_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
1803 
1804 	test_accept(s_sock, &new_sock, &addr, &addrlen);
1805 	zassert_equal(addrlen, sizeof(struct sockaddr_in), "Wrong addrlen");
1806 
1807 
1808 	/* Regular MSG_WAITALL - make sure recv returns only after
1809 	 * requested amount is received.
1810 	 */
1811 	test_data.offset = 0;
1812 	test_data.retries = sizeof(rx_buf);
1813 	test_data.sock = c_sock;
1814 	k_work_init_delayable(&test_data.tx_work,
1815 			      test_msg_waitall_tx_work_handler);
1816 	k_work_reschedule(&test_data.tx_work, K_MSEC(10));
1817 
1818 	ret = zsock_recv(new_sock, rx_buf, sizeof(rx_buf), ZSOCK_MSG_WAITALL);
1819 	zassert_equal(ret, sizeof(rx_buf), "Invalid length received");
1820 	zassert_mem_equal(rx_buf, TEST_STR_SMALL, sizeof(rx_buf),
1821 			  "Invalid data received");
1822 	k_work_cancel_delayable(&test_data.tx_work);
1823 
1824 	/* MSG_WAITALL + SO_RCVTIMEO - make sure recv returns the amount of data
1825 	 * received so far
1826 	 */
1827 	ret = zsock_setsockopt(new_sock, SOL_SOCKET, SO_RCVTIMEO, &timeo_optval,
1828 			       sizeof(timeo_optval));
1829 	zassert_equal(ret, 0, "setsockopt failed (%d)", errno);
1830 
1831 	memset(rx_buf, 0, sizeof(rx_buf));
1832 	test_data.offset = 0;
1833 	test_data.retries = sizeof(rx_buf) - 1;
1834 	test_data.sock = c_sock;
1835 	k_work_init_delayable(&test_data.tx_work,
1836 			      test_msg_waitall_tx_work_handler);
1837 	k_work_reschedule(&test_data.tx_work, K_MSEC(10));
1838 
1839 	ret = zsock_recv(new_sock, rx_buf, sizeof(rx_buf) - 1, ZSOCK_MSG_WAITALL);
1840 	if (ret < 0) {
1841 		LOG_ERR("receive return val %i", ret);
1842 	}
1843 	zassert_equal(ret, sizeof(rx_buf) - 1, "Invalid length received");
1844 	zassert_mem_equal(rx_buf, TEST_STR_SMALL, sizeof(rx_buf) - 1,
1845 			  "Invalid data received");
1846 	k_work_cancel_delayable(&test_data.tx_work);
1847 
1848 	test_close(new_sock);
1849 	test_close(s_sock);
1850 	test_close(c_sock);
1851 
1852 	test_context_cleanup();
1853 }
1854 
ZTEST(net_socket_tcp,test_v6_msg_waitall)1855 ZTEST(net_socket_tcp, test_v6_msg_waitall)
1856 {
1857 	struct test_msg_waitall_data test_data = {
1858 		.data = TEST_STR_SMALL,
1859 	};
1860 	int c_sock;
1861 	int s_sock;
1862 	int new_sock;
1863 	struct sockaddr_in6 c_saddr;
1864 	struct sockaddr_in6 s_saddr;
1865 	struct sockaddr addr;
1866 	socklen_t addrlen = sizeof(addr);
1867 	int ret;
1868 	uint8_t rx_buf[sizeof(TEST_STR_SMALL) - 1] = { 0 };
1869 	struct timeval timeo_optval = {
1870 		.tv_sec = 0,
1871 		.tv_usec = 100000,
1872 	};
1873 
1874 	prepare_sock_tcp_v6(MY_IPV6_ADDR, ANY_PORT, &c_sock, &c_saddr);
1875 	prepare_sock_tcp_v6(MY_IPV6_ADDR, SERVER_PORT, &s_sock, &s_saddr);
1876 
1877 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
1878 	test_listen(s_sock);
1879 
1880 	test_connect(c_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
1881 
1882 	test_accept(s_sock, &new_sock, &addr, &addrlen);
1883 	zassert_equal(addrlen, sizeof(struct sockaddr_in6), "Wrong addrlen");
1884 
1885 	/* Regular MSG_WAITALL - make sure recv returns only after
1886 	 * requested amount is received.
1887 	 */
1888 	test_data.offset = 0;
1889 	test_data.retries = sizeof(rx_buf);
1890 	test_data.sock = c_sock;
1891 	k_work_init_delayable(&test_data.tx_work,
1892 			      test_msg_waitall_tx_work_handler);
1893 	k_work_reschedule(&test_data.tx_work, K_MSEC(10));
1894 
1895 	ret = zsock_recv(new_sock, rx_buf, sizeof(rx_buf), ZSOCK_MSG_WAITALL);
1896 	zassert_equal(ret, sizeof(rx_buf), "Invalid length received");
1897 	zassert_mem_equal(rx_buf, TEST_STR_SMALL, sizeof(rx_buf),
1898 			  "Invalid data received");
1899 	k_work_cancel_delayable(&test_data.tx_work);
1900 
1901 	/* MSG_WAITALL + SO_RCVTIMEO - make sure recv returns the amount of data
1902 	 * received so far
1903 	 */
1904 	ret = zsock_setsockopt(new_sock, SOL_SOCKET, SO_RCVTIMEO, &timeo_optval,
1905 			       sizeof(timeo_optval));
1906 	zassert_equal(ret, 0, "setsockopt failed (%d)", errno);
1907 
1908 	memset(rx_buf, 0, sizeof(rx_buf));
1909 	test_data.offset = 0;
1910 	test_data.retries = sizeof(rx_buf) - 1;
1911 	test_data.sock = c_sock;
1912 	k_work_init_delayable(&test_data.tx_work,
1913 			      test_msg_waitall_tx_work_handler);
1914 	k_work_reschedule(&test_data.tx_work, K_MSEC(10));
1915 
1916 	ret = zsock_recv(new_sock, rx_buf, sizeof(rx_buf) - 1, ZSOCK_MSG_WAITALL);
1917 	zassert_equal(ret, sizeof(rx_buf) - 1, "Invalid length received");
1918 	zassert_mem_equal(rx_buf, TEST_STR_SMALL, sizeof(rx_buf) - 1,
1919 			  "Invalid data received");
1920 	k_work_cancel_delayable(&test_data.tx_work);
1921 
1922 	test_close(new_sock);
1923 	test_close(s_sock);
1924 	test_close(c_sock);
1925 
1926 	test_context_cleanup();
1927 }
1928 
1929 #ifdef CONFIG_USERSPACE
1930 #define CHILD_STACK_SZ		(2048 + CONFIG_TEST_EXTRA_STACK_SIZE)
1931 struct k_thread child_thread;
1932 K_THREAD_STACK_DEFINE(child_stack, CHILD_STACK_SZ);
1933 ZTEST_BMEM volatile int result;
1934 
child_entry(void * p1,void * p2,void * p3)1935 static void child_entry(void *p1, void *p2, void *p3)
1936 {
1937 	int sock = POINTER_TO_INT(p1);
1938 
1939 	result = zsock_close(sock);
1940 }
1941 
spawn_child(int sock)1942 static void spawn_child(int sock)
1943 {
1944 	k_thread_create(&child_thread, child_stack,
1945 			K_THREAD_STACK_SIZEOF(child_stack), child_entry,
1946 			INT_TO_POINTER(sock), NULL, NULL, 0, K_USER,
1947 			K_FOREVER);
1948 }
1949 #endif
1950 
ZTEST(net_socket_tcp,test_socket_permission)1951 ZTEST(net_socket_tcp, test_socket_permission)
1952 {
1953 #ifdef CONFIG_USERSPACE
1954 	int sock;
1955 	struct sockaddr_in saddr;
1956 	struct net_context *ctx;
1957 
1958 	prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &sock, &saddr);
1959 
1960 	ctx = zsock_get_context_object(sock);
1961 	zassert_not_null(ctx, "zsock_get_context_object() failed");
1962 
1963 	/* Spawn a child thread which doesn't inherit our permissions,
1964 	 * it will try to perform a socket operation and fail due to lack
1965 	 * of permissions on it.
1966 	 */
1967 	spawn_child(sock);
1968 	k_thread_start(&child_thread);
1969 	k_thread_join(&child_thread, K_FOREVER);
1970 
1971 	zassert_not_equal(result, 0, "child succeeded with no permission");
1972 
1973 	/* Now spawn the same child thread again, but this time we grant
1974 	 * permission on the net_context before we start it, and the
1975 	 * child should now succeed.
1976 	 */
1977 	spawn_child(sock);
1978 	k_object_access_grant(ctx, &child_thread);
1979 	k_thread_start(&child_thread);
1980 	k_thread_join(&child_thread, K_FOREVER);
1981 
1982 	zassert_equal(result, 0, "child failed with permissions");
1983 #else
1984 	ztest_test_skip();
1985 #endif /* CONFIG_USERSPACE */
1986 }
1987 
setup(void)1988 static void *setup(void)
1989 {
1990 #ifdef CONFIG_USERSPACE
1991 	/* ztest thread inherit permissions from main */
1992 	k_thread_access_grant(k_current_get(), &child_thread, child_stack);
1993 #endif
1994 
1995 	if (IS_ENABLED(CONFIG_NET_TC_THREAD_COOPERATIVE)) {
1996 		k_thread_priority_set(k_current_get(),
1997 				K_PRIO_COOP(CONFIG_NUM_COOP_PRIORITIES - 1));
1998 	} else {
1999 		k_thread_priority_set(k_current_get(), K_PRIO_PREEMPT(8));
2000 	}
2001 
2002 	return NULL;
2003 }
2004 
2005 struct close_data {
2006 	struct k_work_delayable work;
2007 	int fd;
2008 };
2009 
close_work(struct k_work * work)2010 static void close_work(struct k_work *work)
2011 {
2012 	struct k_work_delayable *dwork = k_work_delayable_from_work(work);
2013 	struct close_data *data = CONTAINER_OF(dwork, struct close_data, work);
2014 
2015 	zsock_close(data->fd);
2016 }
2017 
ZTEST(net_socket_tcp,test_close_while_recv)2018 ZTEST(net_socket_tcp, test_close_while_recv)
2019 {
2020 	/* Blocking recv() should return an error after close() is
2021 	 * called from another thread.
2022 	 */
2023 	int c_sock;
2024 	int s_sock;
2025 	int new_sock;
2026 	struct sockaddr_in6 c_saddr, s_saddr;
2027 	struct sockaddr addr;
2028 	socklen_t addrlen = sizeof(addr);
2029 	struct close_data close_work_data;
2030 	char rx_buf[1];
2031 	ssize_t ret;
2032 
2033 	prepare_sock_tcp_v6(MY_IPV6_ADDR, ANY_PORT, &c_sock, &c_saddr);
2034 	prepare_sock_tcp_v6(MY_IPV6_ADDR, SERVER_PORT, &s_sock, &s_saddr);
2035 
2036 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
2037 	test_listen(s_sock);
2038 
2039 	/* Connect and accept that connection */
2040 	test_connect(c_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
2041 
2042 	test_accept(s_sock, &new_sock, &addr, &addrlen);
2043 
2044 	/* Schedule close() from workqueue */
2045 	k_work_init_delayable(&close_work_data.work, close_work);
2046 	close_work_data.fd = c_sock;
2047 	k_work_schedule(&close_work_data.work, K_MSEC(10));
2048 
2049 	/* Start blocking recv(), which should be unblocked by close() from
2050 	 * another thread and return an error.
2051 	 */
2052 	ret = zsock_recv(c_sock, rx_buf, sizeof(rx_buf), 0);
2053 	zassert_equal(ret, -1, "recv did not return error");
2054 	zassert_equal(errno, EINTR, "Unexpected errno value: %d", errno);
2055 
2056 	test_close(new_sock);
2057 	test_close(s_sock);
2058 
2059 	test_context_cleanup();
2060 }
2061 
ZTEST(net_socket_tcp,test_close_while_accept)2062 ZTEST(net_socket_tcp, test_close_while_accept)
2063 {
2064 	/* Blocking accept() should return an error after close() is
2065 	 * called from another thread.
2066 	 */
2067 	int s_sock;
2068 	int new_sock;
2069 	struct sockaddr_in6 s_saddr;
2070 	struct sockaddr addr;
2071 	socklen_t addrlen = sizeof(addr);
2072 	struct close_data close_work_data;
2073 
2074 	prepare_sock_tcp_v6(MY_IPV6_ADDR, SERVER_PORT, &s_sock, &s_saddr);
2075 
2076 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
2077 	test_listen(s_sock);
2078 
2079 	/* Schedule close() from workqueue */
2080 	k_work_init_delayable(&close_work_data.work, close_work);
2081 	close_work_data.fd = s_sock;
2082 	k_work_schedule(&close_work_data.work, K_MSEC(10));
2083 
2084 	/* Start blocking accept(), which should be unblocked by close() from
2085 	 * another thread and return an error.
2086 	 */
2087 	new_sock = zsock_accept(s_sock, &addr, &addrlen);
2088 	zassert_equal(new_sock, -1, "accept did not return error");
2089 	zassert_equal(errno, EINTR, "Unexpected errno value: %d", errno);
2090 
2091 	test_context_cleanup();
2092 }
2093 
2094 #undef read
2095 #define read(fd, buf, len) zsock_recv(fd, buf, len, 0)
2096 
2097 #undef write
2098 #define write(fd, buf, len) zsock_send(fd, buf, len, 0)
2099 
2100 enum test_ioctl_fionread_sockid {
2101 	CLIENT, SERVER, ACCEPT,
2102 };
2103 
test_ioctl_fionread_setup(int af,int fd[3])2104 static void test_ioctl_fionread_setup(int af, int fd[3])
2105 {
2106 	socklen_t addrlen;
2107 	socklen_t addrlen2;
2108 	struct sockaddr_in6 addr;
2109 	struct sockaddr_in6 c_saddr;
2110 	struct sockaddr_in6 s_saddr;
2111 
2112 	fd[0] = -1;
2113 	fd[1] = -1;
2114 	fd[2] = -1;
2115 
2116 	switch (af) {
2117 	case AF_INET: {
2118 		prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &fd[CLIENT],
2119 				    (struct sockaddr_in *)&c_saddr);
2120 		prepare_sock_tcp_v4(MY_IPV4_ADDR, SERVER_PORT, &fd[ACCEPT],
2121 				    (struct sockaddr_in *)&s_saddr);
2122 		addrlen = sizeof(struct sockaddr_in);
2123 	} break;
2124 
2125 	case AF_INET6: {
2126 		prepare_sock_tcp_v6(MY_IPV6_ADDR, ANY_PORT, &fd[CLIENT], &c_saddr);
2127 		prepare_sock_tcp_v6(MY_IPV6_ADDR, SERVER_PORT, &fd[ACCEPT], &s_saddr);
2128 		addrlen = sizeof(struct sockaddr_in6);
2129 	} break;
2130 
2131 	default:
2132 		zassert_true(false);
2133 		return;
2134 	}
2135 
2136 	addrlen2 = addrlen;
2137 
2138 	test_bind(fd[ACCEPT], (struct sockaddr *)&s_saddr, addrlen);
2139 	test_listen(fd[ACCEPT]);
2140 
2141 	test_connect(fd[CLIENT], (struct sockaddr *)&s_saddr, addrlen);
2142 	test_accept(fd[ACCEPT], &fd[SERVER], (struct sockaddr *)&addr, &addrlen2);
2143 }
2144 
2145 /* note: this is duplicated from tests/net/socket/socketpair/src/fionread.c */
test_ioctl_fionread_common(int af)2146 static void test_ioctl_fionread_common(int af)
2147 {
2148 	int avail;
2149 	uint8_t bytes[2];
2150 	/* server fd := 0, client fd := 1, accept fd := 2 */
2151 	enum fde {
2152 		SERVER,
2153 		CLIENT,
2154 		ACCEPT,
2155 	};
2156 	int fd[] = {-1, -1, -1};
2157 
2158 	test_ioctl_fionread_setup(af, fd);
2159 
2160 	/* both ends should have zero bytes available after being newly created */
2161 	for (enum fde i = SERVER; i <= CLIENT; ++i) {
2162 		avail = 42;
2163 		zassert_ok(zsock_ioctl(fd[i], ZFD_IOCTL_FIONREAD, &avail));
2164 		zassert_equal(0, avail, "exp: %d: act: %d", 0, avail);
2165 	}
2166 
2167 	/* write something to one end, check availability from the other end */
2168 	for (enum fde i = SERVER; i <= CLIENT; ++i) {
2169 		enum fde j = (i + 1) % (CLIENT + 1);
2170 
2171 		zassert_equal(1, write(fd[i], "\x42", 1));
2172 		zassert_equal(1, write(fd[i], "\x73", 1));
2173 		k_msleep(100);
2174 		zassert_ok(zsock_ioctl(fd[j], ZFD_IOCTL_FIONREAD, &avail));
2175 		zassert_equal(ARRAY_SIZE(bytes), avail, "exp: %d: act: %d", ARRAY_SIZE(bytes),
2176 			      avail);
2177 	}
2178 
2179 	/* read the other end, ensure availability is zero again */
2180 	for (enum fde i = SERVER; i <= CLIENT; ++i) {
2181 		int ex = ARRAY_SIZE(bytes);
2182 		int act = read(fd[i], bytes, ARRAY_SIZE(bytes));
2183 
2184 		zassert_equal(ex, act, "read() failed: errno: %d exp: %d act: %d", errno, ex, act);
2185 		zassert_ok(zsock_ioctl(fd[i], ZFD_IOCTL_FIONREAD, &avail));
2186 		zassert_equal(0, avail, "exp: %d: act: %d", 0, avail);
2187 	}
2188 
2189 	zsock_close(fd[SERVER]);
2190 	zsock_close(fd[CLIENT]);
2191 	zsock_close(fd[ACCEPT]);
2192 
2193 	test_context_cleanup();
2194 }
2195 
ZTEST(net_socket_tcp,test_ioctl_fionread_v4)2196 ZTEST(net_socket_tcp, test_ioctl_fionread_v4)
2197 {
2198 	test_ioctl_fionread_common(AF_INET);
2199 }
ZTEST(net_socket_tcp,test_ioctl_fionread_v6)2200 ZTEST(net_socket_tcp, test_ioctl_fionread_v6)
2201 {
2202 	test_ioctl_fionread_common(AF_INET6);
2203 }
2204 
2205 /* Connect to peer which is not listening the test port and
2206  * make sure select() returns proper error for the closed
2207  * connection.
2208  */
ZTEST(net_socket_tcp,test_connect_and_wait_for_v4_select)2209 ZTEST(net_socket_tcp, test_connect_and_wait_for_v4_select)
2210 {
2211 	struct sockaddr_in addr = { 0 };
2212 	struct in_addr v4addr;
2213 	int fd, flags, ret, optval;
2214 	socklen_t optlen = sizeof(optval);
2215 
2216 	fd = zsock_socket(AF_INET, SOCK_STREAM, 0);
2217 
2218 	flags = zsock_fcntl(fd, F_GETFL, 0);
2219 	zsock_fcntl(fd, F_SETFL, flags | O_NONBLOCK);
2220 
2221 	zsock_inet_pton(AF_INET, "127.0.0.1", (void *)&v4addr);
2222 
2223 	addr.sin_family = AF_INET;
2224 	net_ipaddr_copy(&addr.sin_addr, &v4addr);
2225 
2226 	/* There should be nobody serving this port */
2227 	addr.sin_port = htons(8088);
2228 
2229 	ret = zsock_connect(fd, (const struct sockaddr *)&addr, sizeof(addr));
2230 	zassert_equal(ret, -1, "connect succeed, %d", errno);
2231 	zassert_equal(errno, EINPROGRESS, "connect succeed, %d", errno);
2232 
2233 	/* Wait for the connection (this should fail eventually) */
2234 	while (1) {
2235 		zsock_fd_set wfds;
2236 		struct timeval tv = {
2237 			.tv_sec = 1,
2238 			.tv_usec = 0
2239 		};
2240 
2241 		ZSOCK_FD_ZERO(&wfds);
2242 		ZSOCK_FD_SET(fd, &wfds);
2243 
2244 		/* Check if the connection is there, this should timeout */
2245 		ret = zsock_select(fd + 1,  NULL, &wfds, NULL, &tv);
2246 		if (ret < 0) {
2247 			break;
2248 		}
2249 
2250 		if (ret > 0) {
2251 			if (ZSOCK_FD_ISSET(fd, &wfds)) {
2252 				break;
2253 			}
2254 		}
2255 	}
2256 
2257 	zassert_true(ret > 0, "select failed, %d", errno);
2258 
2259 	/* Get the reason for the connect */
2260 	ret = zsock_getsockopt(fd, SOL_SOCKET, SO_ERROR, &optval, &optlen);
2261 	zassert_equal(ret, 0, "getsockopt failed, %d", errno);
2262 
2263 	/* If SO_ERROR is 0, then it means that connect succeed. Any
2264 	 * other value (errno) means that it failed.
2265 	 */
2266 	zassert_equal(optval, ECONNREFUSED, "unexpected connect status, %d", optval);
2267 
2268 	ret = zsock_close(fd);
2269 	zassert_equal(ret, 0, "close failed, %d", errno);
2270 }
2271 
2272 /* Connect to peer which is not listening the test port and
2273  * make sure poll() returns proper error for the closed
2274  * connection.
2275  */
ZTEST(net_socket_tcp,test_connect_and_wait_for_v4_poll)2276 ZTEST(net_socket_tcp, test_connect_and_wait_for_v4_poll)
2277 {
2278 	struct sockaddr_in addr = { 0 };
2279 	struct zsock_pollfd fds[1];
2280 	struct in_addr v4addr;
2281 	int fd, flags, ret, optval;
2282 	bool closed = false;
2283 	socklen_t optlen = sizeof(optval);
2284 
2285 	fd = zsock_socket(AF_INET, SOCK_STREAM, 0);
2286 
2287 	flags = zsock_fcntl(fd, F_GETFL, 0);
2288 	zsock_fcntl(fd, F_SETFL, flags | O_NONBLOCK);
2289 
2290 	zsock_inet_pton(AF_INET, "127.0.0.1", (void *)&v4addr);
2291 
2292 	addr.sin_family = AF_INET;
2293 	net_ipaddr_copy(&addr.sin_addr, &v4addr);
2294 
2295 	/* There should be nobody serving this port */
2296 	addr.sin_port = htons(8088);
2297 
2298 	ret = zsock_connect(fd, (const struct sockaddr *)&addr, sizeof(addr));
2299 	zassert_equal(ret, -1, "connect succeed, %d", errno);
2300 	zassert_equal(errno, EINPROGRESS, "connect succeed, %d", errno);
2301 
2302 	/* Wait for the connection (this should fail eventually) */
2303 	while (1) {
2304 		memset(fds, 0, sizeof(fds));
2305 		fds[0].fd = fd;
2306 		fds[0].events = ZSOCK_POLLOUT;
2307 
2308 		/* Check if the connection is there, this should timeout */
2309 		ret = zsock_poll(fds, 1, 10);
2310 		if (ret < 0) {
2311 			break;
2312 		}
2313 
2314 		if (fds[0].revents > 0) {
2315 			if (fds[0].revents & ZSOCK_POLLERR) {
2316 				closed = true;
2317 				break;
2318 			}
2319 		}
2320 	}
2321 
2322 	zassert_true(closed, "poll failed, %d", errno);
2323 
2324 	/* Get the reason for the connect */
2325 	ret = zsock_getsockopt(fd, SOL_SOCKET, SO_ERROR, &optval, &optlen);
2326 	zassert_equal(ret, 0, "getsockopt failed, %d", errno);
2327 
2328 	/* If SO_ERROR is 0, then it means that connect succeed. Any
2329 	 * other value (errno) means that it failed.
2330 	 */
2331 	zassert_equal(optval, ECONNREFUSED, "unexpected connect status, %d", optval);
2332 
2333 	ret = zsock_close(fd);
2334 	zassert_equal(ret, 0, "close failed, %d", errno);
2335 }
2336 
ZTEST(net_socket_tcp,test_so_keepalive)2337 ZTEST(net_socket_tcp, test_so_keepalive)
2338 {
2339 	struct sockaddr_in bind_addr4;
2340 	int sock, ret;
2341 	int optval;
2342 	socklen_t optlen = sizeof(optval);
2343 
2344 	prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &sock, &bind_addr4);
2345 
2346 	/* Keep-alive should be disabled by default. */
2347 	ret = zsock_getsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &optval, &optlen);
2348 	zassert_equal(ret, 0, "getsockopt failed (%d)", errno);
2349 	zassert_equal(optval, 0, "getsockopt got invalid value");
2350 	zassert_equal(optlen, sizeof(optval), "getsockopt got invalid size");
2351 
2352 	/* Enable keep-alive. */
2353 	optval = 1;
2354 	ret = zsock_setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE,
2355 			       &optval, sizeof(optval));
2356 	zassert_equal(ret, 0, "setsockopt failed (%d)", errno);
2357 
2358 	ret = zsock_getsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &optval, &optlen);
2359 	zassert_equal(ret, 0, "getsockopt failed (%d)", errno);
2360 	zassert_equal(optval, 1, "getsockopt got invalid value");
2361 	zassert_equal(optlen, sizeof(optval), "getsockopt got invalid size");
2362 
2363 	/* Check keep-alive parameters defaults. */
2364 	ret = zsock_getsockopt(sock, IPPROTO_TCP, TCP_KEEPIDLE, &optval, &optlen);
2365 	zassert_equal(ret, 0, "getsockopt failed (%d)", errno);
2366 	zassert_equal(optval, CONFIG_NET_TCP_KEEPIDLE_DEFAULT,
2367 		      "getsockopt got invalid value");
2368 	zassert_equal(optlen, sizeof(optval), "getsockopt got invalid size");
2369 
2370 	ret = zsock_getsockopt(sock, IPPROTO_TCP, TCP_KEEPINTVL, &optval, &optlen);
2371 	zassert_equal(ret, 0, "getsockopt failed (%d)", errno);
2372 	zassert_equal(optval, CONFIG_NET_TCP_KEEPINTVL_DEFAULT,
2373 		      "getsockopt got invalid value");
2374 	zassert_equal(optlen, sizeof(optval), "getsockopt got invalid size");
2375 
2376 	ret = zsock_getsockopt(sock, IPPROTO_TCP, TCP_KEEPCNT, &optval, &optlen);
2377 	zassert_equal(ret, 0, "getsockopt failed (%d)", errno);
2378 	zassert_equal(optval, CONFIG_NET_TCP_KEEPCNT_DEFAULT,
2379 		      "getsockopt got invalid value");
2380 	zassert_equal(optlen, sizeof(optval), "getsockopt got invalid size");
2381 
2382 	/* Check keep-alive parameters update. */
2383 	optval = 123;
2384 	ret = zsock_setsockopt(sock, IPPROTO_TCP, TCP_KEEPIDLE,
2385 			       &optval, sizeof(optval));
2386 	zassert_equal(ret, 0, "setsockopt failed (%d)", errno);
2387 
2388 	optval = 10;
2389 	ret = zsock_setsockopt(sock, IPPROTO_TCP, TCP_KEEPINTVL,
2390 			       &optval, sizeof(optval));
2391 	zassert_equal(ret, 0, "setsockopt failed (%d)", errno);
2392 
2393 	optval = 2;
2394 	ret = zsock_setsockopt(sock, IPPROTO_TCP, TCP_KEEPCNT,
2395 			       &optval, sizeof(optval));
2396 	zassert_equal(ret, 0, "setsockopt failed (%d)", errno);
2397 
2398 	ret = zsock_getsockopt(sock, IPPROTO_TCP, TCP_KEEPIDLE, &optval, &optlen);
2399 	zassert_equal(ret, 0, "getsockopt failed (%d)", errno);
2400 	zassert_equal(optval, 123, "getsockopt got invalid value");
2401 	zassert_equal(optlen, sizeof(optval), "getsockopt got invalid size");
2402 
2403 	ret = zsock_getsockopt(sock, IPPROTO_TCP, TCP_KEEPINTVL, &optval, &optlen);
2404 	zassert_equal(ret, 0, "getsockopt failed (%d)", errno);
2405 	zassert_equal(optval, 10, "getsockopt got invalid value");
2406 	zassert_equal(optlen, sizeof(optval), "getsockopt got invalid size");
2407 
2408 	ret = zsock_getsockopt(sock, IPPROTO_TCP, TCP_KEEPCNT, &optval, &optlen);
2409 	zassert_equal(ret, 0, "getsockopt failed (%d)", errno);
2410 	zassert_equal(optval, 2, "getsockopt got invalid value");
2411 	zassert_equal(optlen, sizeof(optval), "getsockopt got invalid size");
2412 
2413 	test_close(sock);
2414 
2415 	test_context_cleanup();
2416 }
2417 
ZTEST(net_socket_tcp,test_keepalive_timeout)2418 ZTEST(net_socket_tcp, test_keepalive_timeout)
2419 {
2420 	struct sockaddr_in c_saddr, s_saddr;
2421 	int c_sock, s_sock, new_sock;
2422 	uint8_t rx_buf;
2423 	int optval;
2424 	int ret;
2425 
2426 	prepare_sock_tcp_v4(MY_IPV4_ADDR, ANY_PORT, &c_sock, &c_saddr);
2427 	prepare_sock_tcp_v4(MY_IPV4_ADDR, SERVER_PORT, &s_sock, &s_saddr);
2428 
2429 	/* Enable keep-alive on both ends and set timeouts/retries to minimum */
2430 	optval = 1;
2431 	ret = zsock_setsockopt(c_sock, SOL_SOCKET, SO_KEEPALIVE,
2432 			       &optval, sizeof(optval));
2433 	zassert_equal(ret, 0, "setsockopt failed (%d)", errno);
2434 	ret = zsock_setsockopt(s_sock, SOL_SOCKET, SO_KEEPALIVE,
2435 			       &optval, sizeof(optval));
2436 	zassert_equal(ret, 0, "setsockopt failed (%d)", errno);
2437 
2438 	optval = 1;
2439 	ret = zsock_setsockopt(c_sock, IPPROTO_TCP, TCP_KEEPIDLE,
2440 			       &optval, sizeof(optval));
2441 	zassert_equal(ret, 0, "setsockopt failed (%d)", errno);
2442 	ret = zsock_setsockopt(s_sock, IPPROTO_TCP, TCP_KEEPIDLE,
2443 			       &optval, sizeof(optval));
2444 	zassert_equal(ret, 0, "setsockopt failed (%d)", errno);
2445 
2446 	optval = 1;
2447 	ret = zsock_setsockopt(c_sock, IPPROTO_TCP, TCP_KEEPINTVL,
2448 			       &optval, sizeof(optval));
2449 	zassert_equal(ret, 0, "setsockopt failed (%d)", errno);
2450 	ret = zsock_setsockopt(s_sock, IPPROTO_TCP, TCP_KEEPINTVL,
2451 			       &optval, sizeof(optval));
2452 	zassert_equal(ret, 0, "setsockopt failed (%d)", errno);
2453 
2454 	optval = 1;
2455 	ret = zsock_setsockopt(c_sock, IPPROTO_TCP, TCP_KEEPCNT,
2456 			       &optval, sizeof(optval));
2457 	zassert_equal(ret, 0, "setsockopt failed (%d)", errno);
2458 	ret = zsock_setsockopt(s_sock, IPPROTO_TCP, TCP_KEEPCNT,
2459 			       &optval, sizeof(optval));
2460 	zassert_equal(ret, 0, "setsockopt failed (%d)", errno);
2461 
2462 	/* Establish connection */
2463 	test_bind(s_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
2464 	test_listen(s_sock);
2465 	test_connect(c_sock, (struct sockaddr *)&s_saddr, sizeof(s_saddr));
2466 	test_accept(s_sock, &new_sock, NULL, NULL);
2467 
2468 	/* Kill communication - expect that connection will be closed after
2469 	 * a timeout period.
2470 	 */
2471 	loopback_set_packet_drop_ratio(1.0f);
2472 
2473 	ret = zsock_recv(c_sock, &rx_buf, sizeof(rx_buf), 0);
2474 	zassert_equal(ret, -1, "recv() should've failed");
2475 	zassert_equal(errno, ETIMEDOUT, "wrong errno value, %d", errno);
2476 
2477 	/* Same on the other end. */
2478 	ret = zsock_recv(new_sock, &rx_buf, sizeof(rx_buf), 0);
2479 	zassert_equal(ret, -1, "recv() should've failed");
2480 	zassert_equal(errno, ETIMEDOUT, "wrong errno value, %d", errno);
2481 
2482 	test_close(c_sock);
2483 	test_close(new_sock);
2484 	test_close(s_sock);
2485 
2486 	loopback_set_packet_drop_ratio(0.0f);
2487 	test_context_cleanup();
2488 }
2489 
after(void * arg)2490 static void after(void *arg)
2491 {
2492 	ARG_UNUSED(arg);
2493 
2494 	for (int i = 0; i < CONFIG_ZVFS_OPEN_MAX; ++i) {
2495 		(void)zsock_close(i);
2496 	}
2497 }
2498 
2499 ZTEST_SUITE(net_socket_tcp, NULL, setup, NULL, after, NULL);
2500