Merge tag 'pull-aspeed-20220714' of https://github.com/legoater/qemu into staging
[qemu/ar7.git] / net / socket.c
blobbfd8596250c4ed317a5f9f4cff42313b870aa1de
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "qemu/osdep.h"
26 #include "net/net.h"
27 #include "clients.h"
28 #include "monitor/monitor.h"
29 #include "qapi/error.h"
30 #include "qemu/error-report.h"
31 #include "qemu/option.h"
32 #include "qemu/sockets.h"
33 #include "qemu/iov.h"
34 #include "qemu/main-loop.h"
36 typedef struct NetSocketState {
37 NetClientState nc;
38 int listen_fd;
39 int fd;
40 SocketReadState rs;
41 unsigned int send_index; /* number of bytes sent (only SOCK_STREAM) */
42 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
43 IOHandler *send_fn; /* differs between SOCK_STREAM/SOCK_DGRAM */
44 bool read_poll; /* waiting to receive data? */
45 bool write_poll; /* waiting to transmit data? */
46 } NetSocketState;
48 static void net_socket_accept(void *opaque);
49 static void net_socket_writable(void *opaque);
51 static void net_socket_update_fd_handler(NetSocketState *s)
53 qemu_set_fd_handler(s->fd,
54 s->read_poll ? s->send_fn : NULL,
55 s->write_poll ? net_socket_writable : NULL,
56 s);
59 static void net_socket_read_poll(NetSocketState *s, bool enable)
61 s->read_poll = enable;
62 net_socket_update_fd_handler(s);
65 static void net_socket_write_poll(NetSocketState *s, bool enable)
67 s->write_poll = enable;
68 net_socket_update_fd_handler(s);
71 static void net_socket_writable(void *opaque)
73 NetSocketState *s = opaque;
75 net_socket_write_poll(s, false);
77 qemu_flush_queued_packets(&s->nc);
80 static ssize_t net_socket_receive(NetClientState *nc, const uint8_t *buf, size_t size)
82 NetSocketState *s = DO_UPCAST(NetSocketState, nc, nc);
83 uint32_t len = htonl(size);
84 struct iovec iov[] = {
86 .iov_base = &len,
87 .iov_len = sizeof(len),
88 }, {
89 .iov_base = (void *)buf,
90 .iov_len = size,
93 size_t remaining;
94 ssize_t ret;
96 remaining = iov_size(iov, 2) - s->send_index;
97 ret = iov_send(s->fd, iov, 2, s->send_index, remaining);
99 if (ret == -1 && errno == EAGAIN) {
100 ret = 0; /* handled further down */
102 if (ret == -1) {
103 s->send_index = 0;
104 return -errno;
106 if (ret < (ssize_t)remaining) {
107 s->send_index += ret;
108 net_socket_write_poll(s, true);
109 return 0;
111 s->send_index = 0;
112 return size;
115 static ssize_t net_socket_receive_dgram(NetClientState *nc, const uint8_t *buf, size_t size)
117 NetSocketState *s = DO_UPCAST(NetSocketState, nc, nc);
118 ssize_t ret;
120 do {
121 if (s->dgram_dst.sin_family != AF_UNIX) {
122 ret = sendto(s->fd, buf, size, 0,
123 (struct sockaddr *)&s->dgram_dst,
124 sizeof(s->dgram_dst));
125 } else {
126 ret = send(s->fd, buf, size, 0);
128 } while (ret == -1 && errno == EINTR);
130 if (ret == -1 && errno == EAGAIN) {
131 net_socket_write_poll(s, true);
132 return 0;
134 return ret;
137 static void net_socket_send_completed(NetClientState *nc, ssize_t len)
139 NetSocketState *s = DO_UPCAST(NetSocketState, nc, nc);
141 if (!s->read_poll) {
142 net_socket_read_poll(s, true);
146 static void net_socket_rs_finalize(SocketReadState *rs)
148 NetSocketState *s = container_of(rs, NetSocketState, rs);
150 if (qemu_send_packet_async(&s->nc, rs->buf,
151 rs->packet_len,
152 net_socket_send_completed) == 0) {
153 net_socket_read_poll(s, false);
157 static void net_socket_send(void *opaque)
159 NetSocketState *s = opaque;
160 int size;
161 int ret;
162 uint8_t buf1[NET_BUFSIZE];
163 const uint8_t *buf;
165 size = recv(s->fd, buf1, sizeof(buf1), 0);
166 if (size < 0) {
167 if (errno != EWOULDBLOCK)
168 goto eoc;
169 } else if (size == 0) {
170 /* end of connection */
171 eoc:
172 net_socket_read_poll(s, false);
173 net_socket_write_poll(s, false);
174 if (s->listen_fd != -1) {
175 qemu_set_fd_handler(s->listen_fd, net_socket_accept, NULL, s);
177 closesocket(s->fd);
179 s->fd = -1;
180 net_socket_rs_init(&s->rs, net_socket_rs_finalize, false);
181 s->nc.link_down = true;
182 memset(s->nc.info_str, 0, sizeof(s->nc.info_str));
184 return;
186 buf = buf1;
188 ret = net_fill_rstate(&s->rs, buf, size);
190 if (ret == -1) {
191 goto eoc;
195 static void net_socket_send_dgram(void *opaque)
197 NetSocketState *s = opaque;
198 int size;
200 size = recv(s->fd, s->rs.buf, sizeof(s->rs.buf), 0);
201 if (size < 0)
202 return;
203 if (size == 0) {
204 /* end of connection */
205 net_socket_read_poll(s, false);
206 net_socket_write_poll(s, false);
207 return;
209 if (qemu_send_packet_async(&s->nc, s->rs.buf, size,
210 net_socket_send_completed) == 0) {
211 net_socket_read_poll(s, false);
215 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr,
216 struct in_addr *localaddr,
217 Error **errp)
219 struct ip_mreq imr;
220 int fd;
221 int val, ret;
222 #ifdef __OpenBSD__
223 unsigned char loop;
224 #else
225 int loop;
226 #endif
228 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
229 error_setg(errp, "specified mcastaddr %s (0x%08x) "
230 "does not contain a multicast address",
231 inet_ntoa(mcastaddr->sin_addr),
232 (int)ntohl(mcastaddr->sin_addr.s_addr));
233 return -1;
236 fd = qemu_socket(PF_INET, SOCK_DGRAM, 0);
237 if (fd < 0) {
238 error_setg_errno(errp, errno, "can't create datagram socket");
239 return -1;
242 /* Allow multiple sockets to bind the same multicast ip and port by setting
243 * SO_REUSEADDR. This is the only situation where SO_REUSEADDR should be set
244 * on windows. Use socket_set_fast_reuse otherwise as it sets SO_REUSEADDR
245 * only on posix systems.
247 val = 1;
248 ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
249 if (ret < 0) {
250 error_setg_errno(errp, errno,
251 "can't set socket option SO_REUSEADDR");
252 goto fail;
255 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
256 if (ret < 0) {
257 error_setg_errno(errp, errno, "can't bind ip=%s to socket",
258 inet_ntoa(mcastaddr->sin_addr));
259 goto fail;
262 /* Add host to multicast group */
263 imr.imr_multiaddr = mcastaddr->sin_addr;
264 if (localaddr) {
265 imr.imr_interface = *localaddr;
266 } else {
267 imr.imr_interface.s_addr = htonl(INADDR_ANY);
270 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
271 &imr, sizeof(struct ip_mreq));
272 if (ret < 0) {
273 error_setg_errno(errp, errno,
274 "can't add socket to multicast group %s",
275 inet_ntoa(imr.imr_multiaddr));
276 goto fail;
279 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
280 loop = 1;
281 ret = setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
282 &loop, sizeof(loop));
283 if (ret < 0) {
284 error_setg_errno(errp, errno,
285 "can't force multicast message to loopback");
286 goto fail;
289 /* If a bind address is given, only send packets from that address */
290 if (localaddr != NULL) {
291 ret = setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF,
292 localaddr, sizeof(*localaddr));
293 if (ret < 0) {
294 error_setg_errno(errp, errno,
295 "can't set the default network send interface");
296 goto fail;
300 qemu_socket_set_nonblock(fd);
301 return fd;
302 fail:
303 if (fd >= 0)
304 closesocket(fd);
305 return -1;
308 static void net_socket_cleanup(NetClientState *nc)
310 NetSocketState *s = DO_UPCAST(NetSocketState, nc, nc);
311 if (s->fd != -1) {
312 net_socket_read_poll(s, false);
313 net_socket_write_poll(s, false);
314 close(s->fd);
315 s->fd = -1;
317 if (s->listen_fd != -1) {
318 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
319 closesocket(s->listen_fd);
320 s->listen_fd = -1;
324 static NetClientInfo net_dgram_socket_info = {
325 .type = NET_CLIENT_DRIVER_SOCKET,
326 .size = sizeof(NetSocketState),
327 .receive = net_socket_receive_dgram,
328 .cleanup = net_socket_cleanup,
331 static NetSocketState *net_socket_fd_init_dgram(NetClientState *peer,
332 const char *model,
333 const char *name,
334 int fd, int is_connected,
335 const char *mcast,
336 Error **errp)
338 struct sockaddr_in saddr;
339 int newfd;
340 NetClientState *nc;
341 NetSocketState *s;
342 SocketAddress *sa;
343 SocketAddressType sa_type;
345 sa = socket_local_address(fd, errp);
346 if (!sa) {
347 return NULL;
349 sa_type = sa->type;
350 qapi_free_SocketAddress(sa);
352 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
353 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
354 * by ONLY ONE process: we must "clone" this dgram socket --jjo
357 if (is_connected && mcast != NULL) {
358 if (parse_host_port(&saddr, mcast, errp) < 0) {
359 goto err;
361 /* must be bound */
362 if (saddr.sin_addr.s_addr == 0) {
363 error_setg(errp, "can't setup multicast destination address");
364 goto err;
366 /* clone dgram socket */
367 newfd = net_socket_mcast_create(&saddr, NULL, errp);
368 if (newfd < 0) {
369 goto err;
371 /* clone newfd to fd, close newfd */
372 dup2(newfd, fd);
373 close(newfd);
377 nc = qemu_new_net_client(&net_dgram_socket_info, peer, model, name);
379 s = DO_UPCAST(NetSocketState, nc, nc);
381 s->fd = fd;
382 s->listen_fd = -1;
383 s->send_fn = net_socket_send_dgram;
384 net_socket_rs_init(&s->rs, net_socket_rs_finalize, false);
385 net_socket_read_poll(s, true);
387 /* mcast: save bound address as dst */
388 if (is_connected && mcast != NULL) {
389 s->dgram_dst = saddr;
390 snprintf(nc->info_str, sizeof(nc->info_str),
391 "socket: fd=%d (cloned mcast=%s:%d)",
392 fd, inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
393 } else {
394 if (sa_type == SOCKET_ADDRESS_TYPE_UNIX) {
395 s->dgram_dst.sin_family = AF_UNIX;
398 snprintf(nc->info_str, sizeof(nc->info_str),
399 "socket: fd=%d %s", fd, SocketAddressType_str(sa_type));
402 return s;
404 err:
405 closesocket(fd);
406 return NULL;
409 static void net_socket_connect(void *opaque)
411 NetSocketState *s = opaque;
412 s->send_fn = net_socket_send;
413 net_socket_read_poll(s, true);
416 static NetClientInfo net_socket_info = {
417 .type = NET_CLIENT_DRIVER_SOCKET,
418 .size = sizeof(NetSocketState),
419 .receive = net_socket_receive,
420 .cleanup = net_socket_cleanup,
423 static NetSocketState *net_socket_fd_init_stream(NetClientState *peer,
424 const char *model,
425 const char *name,
426 int fd, int is_connected)
428 NetClientState *nc;
429 NetSocketState *s;
431 nc = qemu_new_net_client(&net_socket_info, peer, model, name);
433 snprintf(nc->info_str, sizeof(nc->info_str), "socket: fd=%d", fd);
435 s = DO_UPCAST(NetSocketState, nc, nc);
437 s->fd = fd;
438 s->listen_fd = -1;
439 net_socket_rs_init(&s->rs, net_socket_rs_finalize, false);
441 /* Disable Nagle algorithm on TCP sockets to reduce latency */
442 socket_set_nodelay(fd);
444 if (is_connected) {
445 net_socket_connect(s);
446 } else {
447 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
449 return s;
452 static NetSocketState *net_socket_fd_init(NetClientState *peer,
453 const char *model, const char *name,
454 int fd, int is_connected,
455 const char *mc, Error **errp)
457 int so_type = -1, optlen=sizeof(so_type);
459 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
460 (socklen_t *)&optlen)< 0) {
461 error_setg(errp, "can't get socket option SO_TYPE");
462 closesocket(fd);
463 return NULL;
465 switch(so_type) {
466 case SOCK_DGRAM:
467 return net_socket_fd_init_dgram(peer, model, name, fd, is_connected,
468 mc, errp);
469 case SOCK_STREAM:
470 return net_socket_fd_init_stream(peer, model, name, fd, is_connected);
471 default:
472 error_setg(errp, "socket type=%d for fd=%d must be either"
473 " SOCK_DGRAM or SOCK_STREAM", so_type, fd);
474 closesocket(fd);
476 return NULL;
479 static void net_socket_accept(void *opaque)
481 NetSocketState *s = opaque;
482 struct sockaddr_in saddr;
483 socklen_t len;
484 int fd;
486 for(;;) {
487 len = sizeof(saddr);
488 fd = qemu_accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
489 if (fd < 0 && errno != EINTR) {
490 return;
491 } else if (fd >= 0) {
492 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
493 break;
497 s->fd = fd;
498 s->nc.link_down = false;
499 net_socket_connect(s);
500 snprintf(s->nc.info_str, sizeof(s->nc.info_str),
501 "socket: connection from %s:%d",
502 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
505 static int net_socket_listen_init(NetClientState *peer,
506 const char *model,
507 const char *name,
508 const char *host_str,
509 Error **errp)
511 NetClientState *nc;
512 NetSocketState *s;
513 struct sockaddr_in saddr;
514 int fd, ret;
516 if (parse_host_port(&saddr, host_str, errp) < 0) {
517 return -1;
520 fd = qemu_socket(PF_INET, SOCK_STREAM, 0);
521 if (fd < 0) {
522 error_setg_errno(errp, errno, "can't create stream socket");
523 return -1;
525 qemu_socket_set_nonblock(fd);
527 socket_set_fast_reuse(fd);
529 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
530 if (ret < 0) {
531 error_setg_errno(errp, errno, "can't bind ip=%s to socket",
532 inet_ntoa(saddr.sin_addr));
533 closesocket(fd);
534 return -1;
536 ret = listen(fd, 0);
537 if (ret < 0) {
538 error_setg_errno(errp, errno, "can't listen on socket");
539 closesocket(fd);
540 return -1;
543 nc = qemu_new_net_client(&net_socket_info, peer, model, name);
544 s = DO_UPCAST(NetSocketState, nc, nc);
545 s->fd = -1;
546 s->listen_fd = fd;
547 s->nc.link_down = true;
548 net_socket_rs_init(&s->rs, net_socket_rs_finalize, false);
550 qemu_set_fd_handler(s->listen_fd, net_socket_accept, NULL, s);
551 return 0;
554 static int net_socket_connect_init(NetClientState *peer,
555 const char *model,
556 const char *name,
557 const char *host_str,
558 Error **errp)
560 NetSocketState *s;
561 int fd, connected, ret;
562 struct sockaddr_in saddr;
564 if (parse_host_port(&saddr, host_str, errp) < 0) {
565 return -1;
568 fd = qemu_socket(PF_INET, SOCK_STREAM, 0);
569 if (fd < 0) {
570 error_setg_errno(errp, errno, "can't create stream socket");
571 return -1;
573 qemu_socket_set_nonblock(fd);
575 connected = 0;
576 for(;;) {
577 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
578 if (ret < 0) {
579 if (errno == EINTR || errno == EWOULDBLOCK) {
580 /* continue */
581 } else if (errno == EINPROGRESS ||
582 errno == EALREADY ||
583 errno == EINVAL) {
584 break;
585 } else {
586 error_setg_errno(errp, errno, "can't connect socket");
587 closesocket(fd);
588 return -1;
590 } else {
591 connected = 1;
592 break;
595 s = net_socket_fd_init(peer, model, name, fd, connected, NULL, errp);
596 if (!s) {
597 return -1;
600 snprintf(s->nc.info_str, sizeof(s->nc.info_str),
601 "socket: connect to %s:%d",
602 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
603 return 0;
606 static int net_socket_mcast_init(NetClientState *peer,
607 const char *model,
608 const char *name,
609 const char *host_str,
610 const char *localaddr_str,
611 Error **errp)
613 NetSocketState *s;
614 int fd;
615 struct sockaddr_in saddr;
616 struct in_addr localaddr, *param_localaddr;
618 if (parse_host_port(&saddr, host_str, errp) < 0) {
619 return -1;
622 if (localaddr_str != NULL) {
623 if (inet_aton(localaddr_str, &localaddr) == 0) {
624 error_setg(errp, "localaddr '%s' is not a valid IPv4 address",
625 localaddr_str);
626 return -1;
628 param_localaddr = &localaddr;
629 } else {
630 param_localaddr = NULL;
633 fd = net_socket_mcast_create(&saddr, param_localaddr, errp);
634 if (fd < 0) {
635 return -1;
638 s = net_socket_fd_init(peer, model, name, fd, 0, NULL, errp);
639 if (!s) {
640 return -1;
643 s->dgram_dst = saddr;
645 snprintf(s->nc.info_str, sizeof(s->nc.info_str),
646 "socket: mcast=%s:%d",
647 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
648 return 0;
652 static int net_socket_udp_init(NetClientState *peer,
653 const char *model,
654 const char *name,
655 const char *rhost,
656 const char *lhost,
657 Error **errp)
659 NetSocketState *s;
660 int fd, ret;
661 struct sockaddr_in laddr, raddr;
663 if (parse_host_port(&laddr, lhost, errp) < 0) {
664 return -1;
667 if (parse_host_port(&raddr, rhost, errp) < 0) {
668 return -1;
671 fd = qemu_socket(PF_INET, SOCK_DGRAM, 0);
672 if (fd < 0) {
673 error_setg_errno(errp, errno, "can't create datagram socket");
674 return -1;
677 ret = socket_set_fast_reuse(fd);
678 if (ret < 0) {
679 error_setg_errno(errp, errno,
680 "can't set socket option SO_REUSEADDR");
681 closesocket(fd);
682 return -1;
684 ret = bind(fd, (struct sockaddr *)&laddr, sizeof(laddr));
685 if (ret < 0) {
686 error_setg_errno(errp, errno, "can't bind ip=%s to socket",
687 inet_ntoa(laddr.sin_addr));
688 closesocket(fd);
689 return -1;
691 qemu_socket_set_nonblock(fd);
693 s = net_socket_fd_init(peer, model, name, fd, 0, NULL, errp);
694 if (!s) {
695 return -1;
698 s->dgram_dst = raddr;
700 snprintf(s->nc.info_str, sizeof(s->nc.info_str),
701 "socket: udp=%s:%d",
702 inet_ntoa(raddr.sin_addr), ntohs(raddr.sin_port));
703 return 0;
706 int net_init_socket(const Netdev *netdev, const char *name,
707 NetClientState *peer, Error **errp)
709 const NetdevSocketOptions *sock;
711 assert(netdev->type == NET_CLIENT_DRIVER_SOCKET);
712 sock = &netdev->u.socket;
714 if (sock->has_fd + sock->has_listen + sock->has_connect + sock->has_mcast +
715 sock->has_udp != 1) {
716 error_setg(errp, "exactly one of listen=, connect=, mcast= or udp="
717 " is required");
718 return -1;
721 if (sock->has_localaddr && !sock->has_mcast && !sock->has_udp) {
722 error_setg(errp, "localaddr= is only valid with mcast= or udp=");
723 return -1;
726 if (sock->has_fd) {
727 int fd, ret;
729 fd = monitor_fd_param(monitor_cur(), sock->fd, errp);
730 if (fd == -1) {
731 return -1;
733 ret = qemu_socket_try_set_nonblock(fd);
734 if (ret < 0) {
735 error_setg_errno(errp, -ret, "%s: Can't use file descriptor %d",
736 name, fd);
737 return -1;
739 if (!net_socket_fd_init(peer, "socket", name, fd, 1, sock->mcast,
740 errp)) {
741 return -1;
743 return 0;
746 if (sock->has_listen) {
747 if (net_socket_listen_init(peer, "socket", name, sock->listen, errp)
748 < 0) {
749 return -1;
751 return 0;
754 if (sock->has_connect) {
755 if (net_socket_connect_init(peer, "socket", name, sock->connect, errp)
756 < 0) {
757 return -1;
759 return 0;
762 if (sock->has_mcast) {
763 /* if sock->localaddr is missing, it has been initialized to "all bits
764 * zero" */
765 if (net_socket_mcast_init(peer, "socket", name, sock->mcast,
766 sock->localaddr, errp) < 0) {
767 return -1;
769 return 0;
772 assert(sock->has_udp);
773 if (!sock->has_localaddr) {
774 error_setg(errp, "localaddr= is mandatory with udp=");
775 return -1;
777 if (net_socket_udp_init(peer, "socket", name, sock->udp, sock->localaddr,
778 errp) < 0) {
779 return -1;
781 return 0;