• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) 2014-2016 Oracle and/or its affiliates. All Rights Reserved.
4  * Author: Alexey Kodanev <alexey.kodanev@oracle.com>
5  */
6 
7 #include <pthread.h>
8 #include <stdlib.h>
9 #include <limits.h>
10 #include <linux/dccp.h>
11 #include <sys/types.h>
12 #include <sys/socket.h>
13 #include <netdb.h>
14 #include <netinet/in.h>
15 #include <netinet/tcp.h>
16 #include <arpa/inet.h>
17 #include <poll.h>
18 #include <time.h>
19 #include <string.h>
20 #include <unistd.h>
21 #include <errno.h>
22 
23 #include "lapi/udp.h"
24 #include "lapi/dccp.h"
25 #include "lapi/netinet_in.h"
26 #include "lapi/posix_clocks.h"
27 #include "lapi/socket.h"
28 #include "lapi/tcp.h"
29 #include "tst_safe_stdio.h"
30 #include "tst_safe_pthread.h"
31 #include "tst_test.h"
32 
33 static const int max_msg_len = (1 << 16) - 1;
34 static const int min_msg_len = 5;
35 
36 enum {
37 	SERVER_HOST = 0,
38 	CLIENT_HOST,
39 };
40 static char *client_mode;
41 
42 enum {
43 	TFO_DISABLED = 0,
44 	TFO_ENABLED,
45 };
46 static int tfo_value = -1;
47 static char *fastopen_api, *fastopen_sapi;
48 
49 static const char tfo_cfg[]		= "/proc/sys/net/ipv4/tcp_fastopen";
50 static const char tcp_tw_reuse[]	= "/proc/sys/net/ipv4/tcp_tw_reuse";
51 static int tw_reuse_changed;
52 static int tfo_cfg_value;
53 static int tfo_cfg_changed;
54 static int tfo_queue_size	= 100;
55 static int max_queue_len	= 100;
56 static const int client_byte	= 0x43;
57 static const int server_byte	= 0x53;
58 static const int start_byte	= 0x24;
59 static const int start_fin_byte	= 0x25;
60 static const int end_byte	= 0x0a;
61 static int init_cln_msg_len	= 32;
62 static int init_srv_msg_len	= 128;
63 static int max_rand_msg_len;
64 
65 /*
66  * The number of requests from client after
67  * which server has to close the connection.
68  */
69 static int server_max_requests	= 3;
70 static int client_max_requests	= 10;
71 static int clients_num;
72 static char *tcp_port;
73 static char *server_addr;
74 static char *source_addr;
75 static char *server_bg;
76 static int busy_poll		= -1;
77 static int max_etime_cnt = 21; /* ~60 sec max timeout if no connection */
78 static int max_eshutdown_cnt = 10;
79 static int max_pmtu_err = 10;
80 
81 enum {
82 	TYPE_TCP = 0,
83 	TYPE_UDP,
84 	TYPE_UDP_LITE,
85 	TYPE_DCCP,
86 	TYPE_SCTP
87 };
88 static uint proto_type;
89 static char *type;
90 static char *dev;
91 static int sock_type = SOCK_STREAM;
92 static int protocol;
93 static int family = AF_INET6;
94 
95 static uint32_t service_code = 0xffff;
96 
97 /* server socket */
98 static int sfd;
99 
100 /* how long a client must wait for the server's reply */
101 static int wait_timeout = 60000;
102 
103 /* in the end test will save time result in this file */
104 static char *rpath;
105 static char *port_path = "netstress_port";
106 static char *log_path = "netstress.log";
107 
108 static char *narg, *Narg, *qarg, *rarg, *Rarg, *aarg, *Targ, *barg, *targ,
109 	    *Aarg;
110 
111 /* common structure for TCP/UDP server and TCP/UDP client */
112 struct net_func {
113 	void (*init)(void);
114 	void (*run)(void);
115 	void (*cleanup)(void);
116 };
117 static struct net_func net;
118 
119 #define MAX_THREADS	10000
120 static pthread_attr_t attr;
121 static pthread_t *thread_ids;
122 
123 static struct addrinfo *remote_addrinfo;
124 static struct addrinfo *local_addrinfo;
125 
126 struct sock_info {
127 	int fd;
128 	struct sockaddr_storage raddr;
129 	socklen_t raddr_len;
130 	int etime_cnt;
131 	int pmtu_err_cnt;
132 	int eshutdown_cnt;
133 	int timeout;
134 };
135 
136 static char *zcopy;
137 static int send_flags = MSG_NOSIGNAL;
138 static char *reuse_port;
139 
init_socket_opts(int sd)140 static void init_socket_opts(int sd)
141 {
142 	if (busy_poll >= 0)
143 		SAFE_SETSOCKOPT_INT(sd, SOL_SOCKET, SO_BUSY_POLL, busy_poll);
144 
145 	if (dev)
146 		SAFE_SETSOCKOPT(sd, SOL_SOCKET, SO_BINDTODEVICE, dev,
147 				strlen(dev) + 1);
148 
149 	switch (proto_type) {
150 	case TYPE_TCP:
151 		if (client_mode && fastopen_sapi) {
152 			SAFE_SETSOCKOPT_INT(sd, IPPROTO_TCP,
153 					    TCP_FASTOPEN_CONNECT, 1);
154 		}
155 		if (client_mode && zcopy)
156 			SAFE_SETSOCKOPT_INT(sd, SOL_SOCKET, SO_ZEROCOPY, 1);
157 	break;
158 	case TYPE_DCCP:
159 		SAFE_SETSOCKOPT_INT(sd, SOL_DCCP, DCCP_SOCKOPT_SERVICE,
160 				    service_code);
161 	break;
162 	case TYPE_UDP_LITE: {
163 		int cscov = init_srv_msg_len >> 1;
164 
165 		if (cscov < 8)
166 			cscov = 8;
167 		tst_res(TINFO, "UDP-Lite send cscov is %d", cscov);
168 		/* set checksum for header and partially for payload */
169 		SAFE_SETSOCKOPT_INT(sd, SOL_UDPLITE, UDPLITE_SEND_CSCOV, cscov);
170 		SAFE_SETSOCKOPT_INT(sd, SOL_UDPLITE, UDPLITE_RECV_CSCOV, 8);
171 	} break;
172 	}
173 }
174 
do_cleanup(void)175 static void do_cleanup(void)
176 {
177 	if (net.cleanup)
178 		net.cleanup();
179 
180 	if (tfo_cfg_changed) {
181 		tst_res(TINFO, "unset '%s' back to '%d'",
182 			tfo_cfg, tfo_cfg_value);
183 		SAFE_FILE_PRINTF(tfo_cfg, "%d", tfo_cfg_value);
184 	}
185 
186 	if (tw_reuse_changed) {
187 		SAFE_FILE_PRINTF(tcp_tw_reuse, "0");
188 		tst_res(TINFO, "unset '%s' back to '0'", tcp_tw_reuse);
189 	}
190 }
TST_DECLARE_ONCE_FN(cleanup,do_cleanup)191 TST_DECLARE_ONCE_FN(cleanup, do_cleanup)
192 
193 static int sock_recv_poll(char *buf, int size, struct sock_info *i)
194 {
195 	struct pollfd pfd;
196 	pfd.fd = i->fd;
197 	pfd.events = POLLIN;
198 	int len = -1;
199 
200 	while (1) {
201 		errno = 0;
202 		int ret = poll(&pfd, 1, i->timeout);
203 		if (ret == -1) {
204 			if (errno == EINTR)
205 				continue;
206 			break;
207 		}
208 
209 		if (ret != 1) {
210 			if (!errno)
211 				errno = ETIME;
212 			break;
213 		}
214 
215 		if (!(pfd.revents & POLLIN)) {
216 			if (pfd.revents & POLLERR) {
217 				int err = 0;
218 				socklen_t err_len = sizeof(err);
219 
220 				getsockopt(i->fd, SOL_SOCKET, SO_ERROR,
221 					   &err, &err_len);
222 				if (!err)
223 					continue;
224 				errno = err;
225 			}
226 			break;
227 		}
228 
229 		errno = 0;
230 		len = recvfrom(i->fd, buf, size, MSG_DONTWAIT,
231 			       (struct sockaddr *)&i->raddr,
232 			       &i->raddr_len);
233 
234 		if (len == -1 && errno == EINTR)
235 			continue;
236 
237 		if (len == 0)
238 			errno = ESHUTDOWN;
239 
240 		break;
241 	}
242 
243 	return len;
244 }
245 
client_recv(char * buf,int srv_msg_len,struct sock_info * i)246 static int client_recv(char *buf, int srv_msg_len, struct sock_info *i)
247 {
248 	int len, offset = 0;
249 
250 	while (1) {
251 		errno = 0;
252 		len = sock_recv_poll(buf + offset, srv_msg_len - offset, i);
253 
254 		/* socket closed or msg is not valid */
255 		if (len < 1 || (offset + len) > srv_msg_len ||
256 		   (buf[0] != start_byte && buf[0] != start_fin_byte)) {
257 			/* packet too big message, resend with new pmtu */
258 			if (errno == EMSGSIZE) {
259 				if (++(i->pmtu_err_cnt) < max_pmtu_err)
260 					return 0;
261 				tst_brk(TFAIL, "too many pmtu errors %d",
262 					i->pmtu_err_cnt);
263 			} else if (!errno) {
264 				errno = ENOMSG;
265 			}
266 			break;
267 		}
268 		offset += len;
269 		if (buf[offset - 1] != end_byte)
270 			continue;
271 
272 		/* recv last msg, close socket */
273 		if (buf[0] == start_fin_byte)
274 			break;
275 		return 0;
276 	}
277 
278 	if (sock_type != SOCK_STREAM) {
279 		if (errno == ETIME) {
280 			if (++(i->etime_cnt) > max_etime_cnt)
281 				tst_brk(TFAIL, "client requests timeout %d times, last timeout %dms",
282 					i->etime_cnt, i->timeout);
283 			/* Increase timeout in poll up to 3.2 sec */
284 			if (i->timeout < 3000)
285 				i->timeout <<= 1;
286 			return 0;
287 		}
288 		if (errno == ESHUTDOWN) {
289 			if (++(i->eshutdown_cnt) > max_eshutdown_cnt)
290 				tst_brk(TFAIL, "too many zero-length msgs");
291 			tst_res(TINFO, "%d-length msg on sock %d", len, i->fd);
292 			return 0;
293 		}
294 	}
295 
296 	SAFE_CLOSE(i->fd);
297 	return (errno) ? -1 : 0;
298 }
299 
300 static int bind_no_port;
bind_before_connect(int sd)301 static void bind_before_connect(int sd)
302 {
303 	if (!local_addrinfo)
304 		return;
305 
306 	if (bind_no_port)
307 		SAFE_SETSOCKOPT_INT(sd, SOL_IP, IP_BIND_ADDRESS_NO_PORT, 1);
308 	if (reuse_port)
309 		SAFE_SETSOCKOPT_INT(sd, SOL_SOCKET, SO_REUSEPORT, 1);
310 
311 	SAFE_BIND(sd, local_addrinfo->ai_addr, local_addrinfo->ai_addrlen);
312 
313 	if (bind_no_port && proto_type != TYPE_SCTP) {
314 		int port = TST_GETSOCKPORT(sd);
315 
316 		if (port)
317 			tst_brk(TFAIL, "port not zero after bind(): %d", port);
318 	}
319 }
320 
client_connect_send(const char * msg,int size)321 static int client_connect_send(const char *msg, int size)
322 {
323 	int cfd = SAFE_SOCKET(family, sock_type, protocol);
324 
325 	init_socket_opts(cfd);
326 
327 	if (fastopen_api) {
328 		/* Replaces connect() + send()/write() */
329 		SAFE_SENDTO(1, cfd, msg, size, send_flags | MSG_FASTOPEN,
330 			remote_addrinfo->ai_addr, remote_addrinfo->ai_addrlen);
331 	} else {
332 		bind_before_connect(cfd);
333 		/* old TCP API */
334 		SAFE_CONNECT(cfd, remote_addrinfo->ai_addr,
335 			     remote_addrinfo->ai_addrlen);
336 		SAFE_SEND(1, cfd, msg, size, send_flags);
337 	}
338 	return cfd;
339 }
340 
341 union net_size_field {
342 	char bytes[2];
343 	uint16_t value;
344 };
345 
make_client_request(char client_msg[],int * cln_len,int * srv_len)346 static void make_client_request(char client_msg[], int *cln_len, int *srv_len)
347 {
348 	if (max_rand_msg_len)
349 		*cln_len = *srv_len = min_msg_len + rand() % max_rand_msg_len;
350 
351 	memset(client_msg, client_byte, *cln_len);
352 	client_msg[0] = start_byte;
353 
354 	/* set size for reply */
355 	union net_size_field net_size;
356 
357 	net_size.value = htons(*srv_len);
358 	client_msg[1] = net_size.bytes[0];
359 	client_msg[2] = net_size.bytes[1];
360 
361 	client_msg[*cln_len - 1] = end_byte;
362 }
363 
client_fn(LTP_ATTRIBUTE_UNUSED void * arg)364 void *client_fn(LTP_ATTRIBUTE_UNUSED void *arg)
365 {
366 	int cln_len = init_cln_msg_len,
367 	    srv_len = init_srv_msg_len;
368 	struct sock_info inf;
369 	char buf[max_msg_len];
370 	char client_msg[max_msg_len];
371 	int i = 0;
372 	intptr_t err = 0;
373 
374 	inf.raddr_len = sizeof(inf.raddr);
375 	inf.etime_cnt = 0;
376 	inf.timeout = wait_timeout;
377 	inf.pmtu_err_cnt = 0;
378 
379 	make_client_request(client_msg, &cln_len, &srv_len);
380 
381 	/* connect & send requests */
382 	inf.fd = client_connect_send(client_msg, cln_len);
383 	if (inf.fd == -1) {
384 		err = errno;
385 		goto out;
386 	}
387 
388 	if (client_recv(buf, srv_len, &inf)) {
389 		err = errno;
390 		goto out;
391 	}
392 
393 	for (i = 1; i < client_max_requests; ++i) {
394 		if (inf.fd == -1) {
395 			inf.fd = client_connect_send(client_msg, cln_len);
396 			if (inf.fd == -1) {
397 				err = errno;
398 				goto out;
399 			}
400 
401 			if (client_recv(buf, srv_len, &inf)) {
402 				err = errno;
403 				break;
404 			}
405 			continue;
406 		}
407 
408 		if (max_rand_msg_len)
409 			make_client_request(client_msg, &cln_len, &srv_len);
410 
411 		SAFE_SEND(1, inf.fd, client_msg, cln_len, send_flags);
412 
413 		if (client_recv(buf, srv_len, &inf)) {
414 			err = errno;
415 			break;
416 		}
417 	}
418 
419 	if (inf.fd != -1)
420 		SAFE_CLOSE(inf.fd);
421 
422 out:
423 	if (i != client_max_requests)
424 		tst_res(TWARN, "client exit on '%d' request", i);
425 
426 	return (void *) err;
427 }
428 
parse_client_request(const char * msg)429 static int parse_client_request(const char *msg)
430 {
431 	union net_size_field net_size;
432 	net_size.bytes[0] = msg[1];
433 	net_size.bytes[1] = msg[2];
434 	int size = ntohs(net_size.value);
435 	if (size < 2 || size > max_msg_len)
436 		return -1;
437 
438 	return size;
439 }
440 
441 static struct timespec tv_client_start;
442 static struct timespec tv_client_end;
443 
setup_addrinfo(const char * src_addr,const char * port,const struct addrinfo * hints,struct addrinfo ** addr_info)444 static void setup_addrinfo(const char *src_addr, const char *port,
445 			   const struct addrinfo *hints,
446 			   struct addrinfo **addr_info)
447 {
448 	int err = getaddrinfo(src_addr, port, hints, addr_info);
449 
450 	if (err)
451 		tst_brk(TBROK, "getaddrinfo failed, %s", gai_strerror(err));
452 
453 	if (!*addr_info)
454 		tst_brk(TBROK, "failed to get the address");
455 }
456 
client_init(void)457 static void client_init(void)
458 {
459 	if (clients_num >= MAX_THREADS) {
460 		tst_brk(TBROK, "Unexpected num of clients '%d'",
461 			clients_num);
462 	}
463 
464 	thread_ids = SAFE_MALLOC(sizeof(pthread_t) * clients_num);
465 
466 	struct addrinfo hints;
467 	memset(&hints, 0, sizeof(struct addrinfo));
468 	hints.ai_family = AF_UNSPEC;
469 	hints.ai_socktype = sock_type;
470 	hints.ai_flags = 0;
471 	hints.ai_protocol = 0;
472 
473 	if (source_addr)
474 		setup_addrinfo(source_addr, NULL, &hints, &local_addrinfo);
475 	setup_addrinfo(server_addr, tcp_port, &hints, &remote_addrinfo);
476 
477 	tst_res(TINFO, "Running the test over IPv%s",
478 		(remote_addrinfo->ai_family == AF_INET6) ? "6" : "4");
479 
480 	family = remote_addrinfo->ai_family;
481 
482 	clock_gettime(CLOCK_MONOTONIC_RAW, &tv_client_start);
483 	int i;
484 	for (i = 0; i < clients_num; ++i)
485 		SAFE_PTHREAD_CREATE(&thread_ids[i], 0, client_fn, NULL);
486 }
487 
client_run(void)488 static void client_run(void)
489 {
490 	void *res = NULL;
491 	long clnt_time = 0;
492 	int i;
493 	for (i = 0; i < clients_num; ++i) {
494 		pthread_join(thread_ids[i], &res);
495 		if (res) {
496 			tst_brk(TBROK, "client[%d] failed: %s",
497 				i, strerror((intptr_t)res));
498 		}
499 	}
500 
501 	clock_gettime(CLOCK_MONOTONIC_RAW, &tv_client_end);
502 	clnt_time = (tv_client_end.tv_sec - tv_client_start.tv_sec) * 1000 +
503 		(tv_client_end.tv_nsec - tv_client_start.tv_nsec) / 1000000;
504 
505 	tst_res(TINFO, "total time '%ld' ms", clnt_time);
506 
507 	char client_msg[min_msg_len];
508 	int msg_len = min_msg_len;
509 
510 	max_rand_msg_len = 0;
511 	make_client_request(client_msg, &msg_len, &msg_len);
512 	/* ask server to terminate */
513 	client_msg[0] = start_fin_byte;
514 	int cfd = client_connect_send(client_msg, msg_len);
515 	if (cfd != -1) {
516 		shutdown(cfd, SHUT_WR);
517 		SAFE_CLOSE(cfd);
518 	}
519 	/* the script tcp_fastopen_run.sh will remove it */
520 	if (rpath)
521 		SAFE_FILE_PRINTF(rpath, "%ld", clnt_time);
522 
523 	tst_res(TPASS, "test completed");
524 }
525 
client_cleanup(void)526 static void client_cleanup(void)
527 {
528 	free(thread_ids);
529 
530 	if (remote_addrinfo)
531 		freeaddrinfo(remote_addrinfo);
532 }
533 
make_server_reply(char * send_msg,int size)534 static void make_server_reply(char *send_msg, int size)
535 {
536 	memset(send_msg, server_byte, size - 1);
537 	send_msg[0] = start_byte;
538 	send_msg[size - 1] = end_byte;
539 }
540 
server_fn(void * cfd)541 void *server_fn(void *cfd)
542 {
543 	int num_requests = 0, offset = 0;
544 	char send_msg[max_msg_len], end[] = { end_byte };
545 	int start_send_type = (sock_type == SOCK_DGRAM) ? 1 : 0;
546 	int send_msg_len, send_type = start_send_type;
547 	char recv_msg[max_msg_len];
548 	struct sock_info inf;
549 	ssize_t recv_len;
550 	struct iovec iov[2];
551 	struct msghdr msg;
552 
553 	inf.fd = (intptr_t) cfd;
554 	inf.raddr_len = sizeof(inf.raddr);
555 	inf.timeout = wait_timeout;
556 
557 	iov[0].iov_base = send_msg;
558 	iov[1].iov_base = end;
559 	iov[1].iov_len = 1;
560 	memset(&msg, 0, sizeof(msg));
561 	msg.msg_name = &inf.raddr;
562 	msg.msg_iov = iov;
563 	msg.msg_iovlen = 2;
564 
565 	init_socket_opts(inf.fd);
566 
567 	while (1) {
568 		recv_len = sock_recv_poll(recv_msg + offset,
569 					  max_msg_len - offset, &inf);
570 
571 		if (recv_len == 0)
572 			break;
573 
574 		if (recv_len < 0 || (offset + recv_len) > max_msg_len ||
575 		   (recv_msg[0] != start_byte &&
576 		    recv_msg[0] != start_fin_byte)) {
577 			tst_res(TFAIL, "recv failed, sock '%d'", inf.fd);
578 			goto out;
579 		}
580 
581 		offset += recv_len;
582 
583 		if (recv_msg[offset - 1] != end_byte) {
584 			/* msg is not complete, continue recv */
585 			continue;
586 		}
587 
588 		/* client asks to terminate */
589 		if (recv_msg[0] == start_fin_byte)
590 			goto out;
591 
592 		send_msg_len = parse_client_request(recv_msg);
593 		if (send_msg_len < 0) {
594 			tst_res(TFAIL, "wrong msg size '%d'",
595 				send_msg_len);
596 			goto out;
597 		}
598 		make_server_reply(send_msg, send_msg_len);
599 
600 		offset = 0;
601 
602 		/*
603 		 * It will tell client that server is going
604 		 * to close this connection.
605 		 */
606 		if (sock_type == SOCK_STREAM &&
607 		    ++num_requests >= server_max_requests)
608 			send_msg[0] = start_fin_byte;
609 
610 		switch (send_type) {
611 		case 0:
612 			SAFE_SEND(1, inf.fd, send_msg, send_msg_len,
613 				  send_flags);
614 			if (proto_type != TYPE_SCTP)
615 				++send_type;
616 			break;
617 		case 1:
618 			SAFE_SENDTO(1, inf.fd, send_msg, send_msg_len,
619 				    send_flags, (struct sockaddr *)&inf.raddr,
620 				    inf.raddr_len);
621 			++send_type;
622 			break;
623 		default:
624 			iov[0].iov_len = send_msg_len - 1;
625 			msg.msg_namelen = inf.raddr_len;
626 			SAFE_SENDMSG(send_msg_len, inf.fd, &msg, send_flags);
627 			send_type = start_send_type;
628 			break;
629 		}
630 
631 		if (sock_type == SOCK_STREAM &&
632 		    num_requests >= server_max_requests) {
633 			/* max reqs, close socket */
634 			shutdown(inf.fd, SHUT_WR);
635 			break;
636 		}
637 	}
638 
639 	SAFE_CLOSE(inf.fd);
640 	return NULL;
641 
642 out:
643 	SAFE_CLOSE(inf.fd);
644 	tst_brk(TBROK, "Server closed");
645 	return NULL;
646 }
647 
server_thread_add(intptr_t client_fd)648 static pthread_t server_thread_add(intptr_t client_fd)
649 {
650 	pthread_t id;
651 	SAFE_PTHREAD_CREATE(&id, &attr, server_fn, (void *) client_fd);
652 	return id;
653 }
654 
server_init(void)655 static void server_init(void)
656 {
657 	char *src_addr = NULL;
658 	struct addrinfo hints;
659 
660 	memset(&hints, 0, sizeof(struct addrinfo));
661 	hints.ai_family = AF_INET6;
662 	hints.ai_socktype = sock_type;
663 	hints.ai_flags = AI_PASSIVE;
664 
665 	if (!source_addr && !tcp_port)
666 		tcp_port = "0";
667 
668 	if (source_addr && !strchr(source_addr, ':'))
669 		SAFE_ASPRINTF(&src_addr, "::ffff:%s", source_addr);
670 	setup_addrinfo(src_addr ? src_addr : source_addr, tcp_port,
671 		       &hints, &local_addrinfo);
672 	free(src_addr);
673 
674 	/* IPv6 socket is also able to access IPv4 protocol stack */
675 	sfd = SAFE_SOCKET(family, sock_type, protocol);
676 	SAFE_SETSOCKOPT_INT(sfd, SOL_SOCKET, SO_REUSEADDR, 1);
677 	if (reuse_port)
678 		SAFE_SETSOCKOPT_INT(sfd, SOL_SOCKET, SO_REUSEPORT, 1);
679 
680 	tst_res(TINFO, "assigning a name to the server socket...");
681 	SAFE_BIND(sfd, local_addrinfo->ai_addr, local_addrinfo->ai_addrlen);
682 
683 	freeaddrinfo(local_addrinfo);
684 
685 	int port = TST_GETSOCKPORT(sfd);
686 
687 	tst_res(TINFO, "bind to port %d", port);
688 	if (server_bg) {
689 		SAFE_CHDIR(server_bg);
690 		SAFE_FILE_PRINTF(port_path, "%d", port);
691 	}
692 
693 	if (sock_type == SOCK_DGRAM)
694 		return;
695 
696 	init_socket_opts(sfd);
697 
698 	if (fastopen_api || fastopen_sapi) {
699 		SAFE_SETSOCKOPT_INT(sfd, IPPROTO_TCP, TCP_FASTOPEN,
700 			tfo_queue_size);
701 	}
702 
703 	if (zcopy)
704 		SAFE_SETSOCKOPT_INT(sfd, SOL_SOCKET, SO_ZEROCOPY, 1);
705 
706 	SAFE_LISTEN(sfd, max_queue_len);
707 
708 	tst_res(TINFO, "Listen on the socket '%d'", sfd);
709 }
710 
server_cleanup(void)711 static void server_cleanup(void)
712 {
713 	SAFE_CLOSE(sfd);
714 }
715 
move_to_background(void)716 static void move_to_background(void)
717 {
718 	if (SAFE_FORK())
719 		exit(0);
720 
721 	SAFE_SETSID();
722 
723 	close(STDIN_FILENO);
724 	SAFE_OPEN("/dev/null", O_RDONLY);
725 	close(STDOUT_FILENO);
726 	close(STDERR_FILENO);
727 
728 	int fd = SAFE_OPEN(log_path, O_CREAT | O_TRUNC | O_RDONLY, 00444);
729 
730 	SAFE_DUP(fd);
731 }
732 
server_run_udp(void)733 static void server_run_udp(void)
734 {
735 	if (server_bg)
736 		move_to_background();
737 
738 	pthread_t p_id = server_thread_add(sfd);
739 
740 	SAFE_PTHREAD_JOIN(p_id, NULL);
741 }
742 
server_run(void)743 static void server_run(void)
744 {
745 	if (server_bg)
746 		move_to_background();
747 
748 	/* IPv4 source address will be mapped to IPv6 address */
749 	struct sockaddr_in6 addr6;
750 	socklen_t addr_size = sizeof(addr6);
751 
752 	pthread_attr_init(&attr);
753 
754 	/*
755 	 * detaching threads allow to reclaim thread's resources
756 	 * once a thread finishes its work.
757 	 */
758 	if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0)
759 		tst_brk(TBROK | TERRNO, "setdetachstate failed");
760 
761 	while (1) {
762 		int client_fd = accept(sfd, (struct sockaddr *)&addr6,
763 			&addr_size);
764 
765 		if (client_fd == -1)
766 			tst_brk(TBROK, "Can't create client socket");
767 
768 		server_thread_add(client_fd);
769 	}
770 }
771 
require_root(const char * file)772 static void require_root(const char *file)
773 {
774 	if (!geteuid())
775 		return;
776 	tst_brk(TCONF, "Test needs to be run as root to change %s", file);
777 }
778 
check_tfo_value(void)779 static void check_tfo_value(void)
780 {
781 	/* Check if we can write to tcp_fastopen knob. We might be
782 	 * inside netns and either have read-only permission or
783 	 * doesn't have the knob at all.
784 	 */
785 	if (access(tfo_cfg, W_OK) < 0) {
786 		/* TODO check /proc/self/ns/ or TST_USE_NETNS env var */
787 		tst_res(TINFO, "can't read %s, assume server runs in netns",
788 			tfo_cfg);
789 		return;
790 	}
791 
792 	SAFE_FILE_SCANF(tfo_cfg, "%d", &tfo_cfg_value);
793 	tst_res(TINFO, "'%s' is %d", tfo_cfg, tfo_cfg_value);
794 
795 	/* The check can be the first in this function but set here
796 	 * to allow to print information about the currently set config
797 	 */
798 	if (tfo_value < 0)
799 		return;
800 
801 	if (tfo_cfg_value == tfo_value)
802 		return;
803 
804 	require_root(tfo_cfg);
805 
806 	tst_res(TINFO, "set '%s' to '%d'", tfo_cfg, tfo_value);
807 
808 	SAFE_FILE_PRINTF(tfo_cfg, "%d", tfo_value);
809 	tfo_cfg_changed = 1;
810 }
811 
check_tw_reuse(void)812 static void check_tw_reuse(void)
813 {
814 	if (access(tcp_tw_reuse, W_OK) < 0)
815 		return;
816 
817 	int reuse_value = 0;
818 
819 	SAFE_FILE_SCANF(tcp_tw_reuse, "%d", &reuse_value);
820 	if (reuse_value) {
821 		tst_res(TINFO, "tcp_tw_reuse is already set");
822 		return;
823 	}
824 
825 	require_root(tfo_cfg);
826 
827 	SAFE_FILE_PRINTF(tcp_tw_reuse, "1");
828 	tw_reuse_changed = 1;
829 	tst_res(TINFO, "set '%s' to '1'", tcp_tw_reuse);
830 }
831 
set_protocol_type(void)832 static void set_protocol_type(void)
833 {
834 	if (!type || !strcmp(type, "tcp"))
835 		proto_type = TYPE_TCP;
836 	else if (!strcmp(type, "udp"))
837 		proto_type = TYPE_UDP;
838 	else if (!strcmp(type, "udp_lite"))
839 		proto_type = TYPE_UDP_LITE;
840 	else if (!strcmp(type, "dccp"))
841 		proto_type = TYPE_DCCP;
842 	else if (!strcmp(type, "sctp"))
843 		proto_type = TYPE_SCTP;
844 	else
845 		tst_brk(TBROK, "Invalid proto_type: '%s'", type);
846 }
847 
setup(void)848 static void setup(void)
849 {
850 	if (tst_parse_int(aarg, &clients_num, 1, INT_MAX))
851 		tst_brk(TBROK, "Invalid client number '%s'", aarg);
852 	if (tst_parse_int(rarg, &client_max_requests, 1, INT_MAX))
853 		tst_brk(TBROK, "Invalid client max requests '%s'", rarg);
854 	if (tst_parse_int(Rarg, &server_max_requests, 1, INT_MAX))
855 		tst_brk(TBROK, "Invalid server max requests '%s'", Rarg);
856 	if (tst_parse_int(narg, &init_cln_msg_len, min_msg_len, max_msg_len))
857 		tst_brk(TBROK, "Invalid client msg size '%s'", narg);
858 	if (tst_parse_int(Narg, &init_srv_msg_len, min_msg_len, max_msg_len))
859 		tst_brk(TBROK, "Invalid server msg size '%s'", Narg);
860 	if (tst_parse_int(qarg, &tfo_queue_size, 1, INT_MAX))
861 		tst_brk(TBROK, "Invalid TFO queue size '%s'", qarg);
862 	if (tst_parse_int(Targ, &wait_timeout, 0, INT_MAX))
863 		tst_brk(TBROK, "Invalid wait timeout '%s'", Targ);
864 	if (tst_parse_int(barg, &busy_poll, 0, INT_MAX))
865 		tst_brk(TBROK, "Invalid busy poll timeout'%s'", barg);
866 	if (tst_parse_int(targ, &tfo_value, 0, INT_MAX))
867 		tst_brk(TBROK, "Invalid net.ipv4.tcp_fastopen '%s'", targ);
868 	if (tst_parse_int(Aarg, &max_rand_msg_len, 10, max_msg_len))
869 		tst_brk(TBROK, "Invalid max random payload size '%s'", Aarg);
870 
871 	if (!server_addr)
872 		server_addr = "localhost";
873 
874 	if (max_rand_msg_len) {
875 		max_rand_msg_len -= min_msg_len;
876 		unsigned int seed = max_rand_msg_len ^ client_max_requests;
877 
878 		srand(seed);
879 		tst_res(TINFO, "srand() seed 0x%x", seed);
880 	}
881 
882 	/* if client_num is not set, use num of processors */
883 	if (!clients_num)
884 		clients_num = sysconf(_SC_NPROCESSORS_ONLN);
885 
886 	if (tfo_value > 0 && tst_kvercmp(3, 7, 0) < 0)
887 		tst_brk(TCONF, "Test must be run with kernel 3.7 or newer");
888 
889 	if (busy_poll >= 0 && tst_kvercmp(3, 11, 0) < 0)
890 		tst_brk(TCONF, "Test must be run with kernel 3.11 or newer");
891 
892 	set_protocol_type();
893 
894 	if (client_mode) {
895 		if (source_addr && tst_kvercmp(4, 2, 0) >= 0) {
896 			bind_no_port = 1;
897 			tst_res(TINFO, "IP_BIND_ADDRESS_NO_PORT is used");
898 		}
899 		tst_res(TINFO, "connection: addr '%s', port '%s'",
900 			server_addr, tcp_port);
901 		tst_res(TINFO, "client max req: %d", client_max_requests);
902 		tst_res(TINFO, "clients num: %d", clients_num);
903 		if (max_rand_msg_len) {
904 			tst_res(TINFO, "random msg size [%d %d]",
905 				min_msg_len, max_rand_msg_len);
906 		} else {
907 			tst_res(TINFO, "client msg size: %d", init_cln_msg_len);
908 			tst_res(TINFO, "server msg size: %d", init_srv_msg_len);
909 		}
910 		net.init	= client_init;
911 		net.run		= client_run;
912 		net.cleanup	= client_cleanup;
913 
914 		switch (proto_type) {
915 		case TYPE_TCP:
916 			check_tw_reuse();
917 			break;
918 		case TYPE_DCCP:
919 		case TYPE_UDP:
920 		case TYPE_UDP_LITE:
921 			if (max_etime_cnt >= client_max_requests)
922 				max_etime_cnt = client_max_requests - 1;
923 			tst_res(TINFO, "maximum allowed timeout errors %d", max_etime_cnt);
924 			wait_timeout = 100;
925 		}
926 	} else {
927 		tst_res(TINFO, "max requests '%d'",
928 			server_max_requests);
929 		net.init	= server_init;
930 		switch (proto_type) {
931 		case TYPE_TCP:
932 		case TYPE_DCCP:
933 		case TYPE_SCTP:
934 			net.run		= server_run;
935 			net.cleanup	= server_cleanup;
936 		break;
937 		case TYPE_UDP:
938 		case TYPE_UDP_LITE:
939 			net.run		= server_run_udp;
940 			net.cleanup	= NULL;
941 		break;
942 		}
943 	}
944 
945 	if (zcopy)
946 		send_flags |= MSG_ZEROCOPY;
947 
948 	switch (proto_type) {
949 	case TYPE_TCP:
950 		tst_res(TINFO, "TCP %s is using %s TCP API.",
951 			(client_mode) ? "client" : "server",
952 			(fastopen_api) ? "Fastopen" : "old");
953 		check_tfo_value();
954 	break;
955 	case TYPE_UDP:
956 		tst_res(TINFO, "using UDP");
957 		fastopen_api = fastopen_sapi = NULL;
958 		sock_type = SOCK_DGRAM;
959 	break;
960 	case TYPE_UDP_LITE:
961 		tst_res(TINFO, "using UDP Lite");
962 		fastopen_api = fastopen_sapi = NULL;
963 		sock_type = SOCK_DGRAM;
964 		protocol = IPPROTO_UDPLITE;
965 	break;
966 	case TYPE_DCCP: {
967 		/* dccp* modules can be blacklisted, load them manually */
968 		const char * const argv[] = {"modprobe", "dccp_ipv6", NULL};
969 
970 		if (tst_run_cmd(argv, NULL, NULL, 1))
971 			tst_brk(TCONF, "Failed to load dccp_ipv6 module");
972 
973 		tst_res(TINFO, "DCCP %s", (client_mode) ? "client" : "server");
974 		fastopen_api = fastopen_sapi = NULL;
975 		sock_type = SOCK_DCCP;
976 		protocol = IPPROTO_DCCP;
977 		service_code = htonl(service_code);
978 	} break;
979 	case TYPE_SCTP:
980 		tst_res(TINFO, "SCTP %s", (client_mode) ? "client" : "server");
981 		fastopen_api = fastopen_sapi = NULL;
982 		protocol = IPPROTO_SCTP;
983 	break;
984 	}
985 
986 	net.init();
987 }
988 
do_test(void)989 static void do_test(void)
990 {
991 	net.run();
992 }
993 
994 static struct tst_option options[] = {
995 	{"f", &fastopen_api, "-f       Use TFO API, default is old API"},
996 	{"F", &fastopen_sapi,
997 		"-F       TCP_FASTOPEN_CONNECT socket option and standard API"},
998 	{"t:", &targ, "-t x     Set tcp_fastopen value"},
999 
1000 	{"S:", &source_addr, "-S x     Source address to bind"},
1001 	{"g:", &tcp_port, "-g x     x - server port"},
1002 	{"b:", &barg, "-b x     x - low latency busy poll timeout"},
1003 	{"T:", &type, "-T x     tcp (default), udp, udp_lite, dccp, sctp"},
1004 	{"z", &zcopy, "-z       enable SO_ZEROCOPY"},
1005 	{"P:", &reuse_port, "-P       enable SO_REUSEPORT"},
1006 	{"D:", &dev, "-D x     bind to device x\n"},
1007 
1008 	{"H:", &server_addr, "Client:\n-H x     Server name or IP address"},
1009 	{"l", &client_mode, "-l       Become client, default is server"},
1010 	{"a:", &aarg, "-a x     Number of clients running in parallel"},
1011 	{"r:", &rarg, "-r x     Number of client requests"},
1012 	{"n:", &narg, "-n x     Client message size"},
1013 	{"N:", &Narg, "-N x     Server message size"},
1014 	{"m:", &Targ, "-m x     Receive timeout in milliseconds (not used by UDP/DCCP client)"},
1015 	{"d:", &rpath, "-d x     x is a path to file where result is saved"},
1016 	{"A:", &Aarg, "-A x     x max payload length (generated randomly)\n"},
1017 
1018 	{"R:", &Rarg, "Server:\n-R x     x requests after which conn.closed"},
1019 	{"q:", &qarg, "-q x     x - TFO queue"},
1020 	{"B:", &server_bg, "-B x     run in background, x - process directory"},
1021 	{NULL, NULL, NULL}
1022 };
1023 
1024 static struct tst_test test = {
1025 	.test_all = do_test,
1026 	.forks_child = 1,
1027 	.setup = setup,
1028 	.cleanup = cleanup,
1029 	.options = options
1030 };
1031