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
24 #include "qemu/osdep.h"
28 #include "monitor/monitor.h"
29 #include "qemu-common.h"
30 #include "qemu/error-report.h"
31 #include "qemu/option.h"
32 #include "qemu/sockets.h"
34 #include "qemu/main-loop.h"
36 typedef struct NetSocketState {
40 int state; /* 0 = getting length, 1 = getting data */
42 unsigned int packet_len;
43 unsigned int send_index; /* number of bytes sent (only SOCK_STREAM) */
44 uint8_t buf[NET_BUFSIZE];
45 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
46 IOHandler *send_fn; /* differs between SOCK_STREAM/SOCK_DGRAM */
47 bool read_poll; /* waiting to receive data? */
48 bool write_poll; /* waiting to transmit data? */
51 static void net_socket_accept(void *opaque);
52 static void net_socket_writable(void *opaque);
54 static void net_socket_update_fd_handler(NetSocketState *s)
56 qemu_set_fd_handler(s->fd,
57 s->read_poll ? s->send_fn : NULL,
58 s->write_poll ? net_socket_writable : NULL,
62 static void net_socket_read_poll(NetSocketState *s, bool enable)
64 s->read_poll = enable;
65 net_socket_update_fd_handler(s);
68 static void net_socket_write_poll(NetSocketState *s, bool enable)
70 s->write_poll = enable;
71 net_socket_update_fd_handler(s);
74 static void net_socket_writable(void *opaque)
76 NetSocketState *s = opaque;
78 net_socket_write_poll(s, false);
80 qemu_flush_queued_packets(&s->nc);
83 static ssize_t net_socket_receive(NetClientState *nc, const uint8_t *buf, size_t size)
85 NetSocketState *s = DO_UPCAST(NetSocketState, nc, nc);
86 uint32_t len = htonl(size);
87 struct iovec iov[] = {
90 .iov_len = sizeof(len),
92 .iov_base = (void *)buf,
99 remaining = iov_size(iov, 2) - s->send_index;
100 ret = iov_send(s->fd, iov, 2, s->send_index, remaining);
102 if (ret == -1 && errno == EAGAIN) {
103 ret = 0; /* handled further down */
109 if (ret < (ssize_t)remaining) {
110 s->send_index += ret;
111 net_socket_write_poll(s, true);
118 static ssize_t net_socket_receive_dgram(NetClientState *nc, const uint8_t *buf, size_t size)
120 NetSocketState *s = DO_UPCAST(NetSocketState, nc, nc);
124 ret = qemu_sendto(s->fd, buf, size, 0,
125 (struct sockaddr *)&s->dgram_dst,
126 sizeof(s->dgram_dst));
127 } while (ret == -1 && errno == EINTR);
129 if (ret == -1 && errno == EAGAIN) {
130 net_socket_write_poll(s, true);
136 static void net_socket_send_completed(NetClientState *nc, ssize_t len)
138 NetSocketState *s = DO_UPCAST(NetSocketState, nc, nc);
141 net_socket_read_poll(s, true);
145 static void net_socket_send(void *opaque)
147 NetSocketState *s = opaque;
150 uint8_t buf1[NET_BUFSIZE];
153 size = qemu_recv(s->fd, buf1, sizeof(buf1), 0);
155 if (errno != EWOULDBLOCK)
157 } else if (size == 0) {
158 /* end of connection */
160 net_socket_read_poll(s, false);
161 net_socket_write_poll(s, false);
162 if (s->listen_fd != -1) {
163 qemu_set_fd_handler(s->listen_fd, net_socket_accept, NULL, s);
171 s->nc.link_down = true;
172 memset(s->buf, 0, sizeof(s->buf));
173 memset(s->nc.info_str, 0, sizeof(s->nc.info_str));
179 /* reassemble a packet from the network */
185 memcpy(s->buf + s->index, buf, l);
191 s->packet_len = ntohl(*(uint32_t *)s->buf);
197 l = s->packet_len - s->index;
200 if (s->index + l <= sizeof(s->buf)) {
201 memcpy(s->buf + s->index, buf, l);
203 fprintf(stderr, "serious error: oversized packet received,"
204 "connection terminated.\n");
212 if (s->index >= s->packet_len) {
215 if (qemu_send_packet_async(&s->nc, s->buf, s->packet_len,
216 net_socket_send_completed) == 0) {
217 net_socket_read_poll(s, false);
226 static void net_socket_send_dgram(void *opaque)
228 NetSocketState *s = opaque;
231 size = qemu_recv(s->fd, s->buf, sizeof(s->buf), 0);
235 /* end of connection */
236 net_socket_read_poll(s, false);
237 net_socket_write_poll(s, false);
240 if (qemu_send_packet_async(&s->nc, s->buf, size,
241 net_socket_send_completed) == 0) {
242 net_socket_read_poll(s, false);
246 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr, struct in_addr *localaddr)
257 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
258 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) "
259 "does not contain a multicast address\n",
260 inet_ntoa(mcastaddr->sin_addr),
261 (int)ntohl(mcastaddr->sin_addr.s_addr));
265 fd = qemu_socket(PF_INET, SOCK_DGRAM, 0);
267 perror("socket(PF_INET, SOCK_DGRAM)");
271 /* Allow multiple sockets to bind the same multicast ip and port by setting
272 * SO_REUSEADDR. This is the only situation where SO_REUSEADDR should be set
273 * on windows. Use socket_set_fast_reuse otherwise as it sets SO_REUSEADDR
274 * only on posix systems.
277 ret = qemu_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
279 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
283 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
289 /* Add host to multicast group */
290 imr.imr_multiaddr = mcastaddr->sin_addr;
292 imr.imr_interface = *localaddr;
294 imr.imr_interface.s_addr = htonl(INADDR_ANY);
297 ret = qemu_setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
298 &imr, sizeof(struct ip_mreq));
300 perror("setsockopt(IP_ADD_MEMBERSHIP)");
304 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
306 ret = qemu_setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
307 &loop, sizeof(loop));
309 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
313 /* If a bind address is given, only send packets from that address */
314 if (localaddr != NULL) {
315 ret = qemu_setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF,
316 localaddr, sizeof(*localaddr));
318 perror("setsockopt(IP_MULTICAST_IF)");
323 qemu_set_nonblock(fd);
331 static void net_socket_cleanup(NetClientState *nc)
333 NetSocketState *s = DO_UPCAST(NetSocketState, nc, nc);
335 net_socket_read_poll(s, false);
336 net_socket_write_poll(s, false);
340 if (s->listen_fd != -1) {
341 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
342 closesocket(s->listen_fd);
347 static NetClientInfo net_dgram_socket_info = {
348 .type = NET_CLIENT_OPTIONS_KIND_SOCKET,
349 .size = sizeof(NetSocketState),
350 .receive = net_socket_receive_dgram,
351 .cleanup = net_socket_cleanup,
354 static NetSocketState *net_socket_fd_init_dgram(NetClientState *peer,
357 int fd, int is_connected)
359 struct sockaddr_in saddr;
361 socklen_t saddr_len = sizeof(saddr);
365 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
366 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
367 * by ONLY ONE process: we must "clone" this dgram socket --jjo
371 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
373 if (saddr.sin_addr.s_addr == 0) {
374 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, "
375 "cannot setup multicast dst addr\n", fd);
378 /* clone dgram socket */
379 newfd = net_socket_mcast_create(&saddr, NULL);
381 /* error already reported by net_socket_mcast_create() */
384 /* clone newfd to fd, close newfd */
390 "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
391 fd, strerror(errno));
396 nc = qemu_new_net_client(&net_dgram_socket_info, peer, model, name);
398 s = DO_UPCAST(NetSocketState, nc, nc);
402 s->send_fn = net_socket_send_dgram;
403 net_socket_read_poll(s, true);
405 /* mcast: save bound address as dst */
407 s->dgram_dst = saddr;
408 snprintf(nc->info_str, sizeof(nc->info_str),
409 "socket: fd=%d (cloned mcast=%s:%d)",
410 fd, inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
412 snprintf(nc->info_str, sizeof(nc->info_str),
413 "socket: fd=%d", fd);
423 static void net_socket_connect(void *opaque)
425 NetSocketState *s = opaque;
426 s->send_fn = net_socket_send;
427 net_socket_read_poll(s, true);
430 static NetClientInfo net_socket_info = {
431 .type = NET_CLIENT_OPTIONS_KIND_SOCKET,
432 .size = sizeof(NetSocketState),
433 .receive = net_socket_receive,
434 .cleanup = net_socket_cleanup,
437 static NetSocketState *net_socket_fd_init_stream(NetClientState *peer,
440 int fd, int is_connected)
445 nc = qemu_new_net_client(&net_socket_info, peer, model, name);
447 snprintf(nc->info_str, sizeof(nc->info_str), "socket: fd=%d", fd);
449 s = DO_UPCAST(NetSocketState, nc, nc);
454 /* Disable Nagle algorithm on TCP sockets to reduce latency */
455 socket_set_nodelay(fd);
458 net_socket_connect(s);
460 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
465 static NetSocketState *net_socket_fd_init(NetClientState *peer,
466 const char *model, const char *name,
467 int fd, int is_connected)
469 int so_type = -1, optlen=sizeof(so_type);
471 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
472 (socklen_t *)&optlen)< 0) {
473 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n",
480 return net_socket_fd_init_dgram(peer, model, name, fd, is_connected);
482 return net_socket_fd_init_stream(peer, model, name, fd, is_connected);
484 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
485 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
486 return net_socket_fd_init_stream(peer, model, name, fd, is_connected);
491 static void net_socket_accept(void *opaque)
493 NetSocketState *s = opaque;
494 struct sockaddr_in saddr;
500 fd = qemu_accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
501 if (fd < 0 && errno != EINTR) {
503 } else if (fd >= 0) {
504 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
510 s->nc.link_down = false;
511 net_socket_connect(s);
512 snprintf(s->nc.info_str, sizeof(s->nc.info_str),
513 "socket: connection from %s:%d",
514 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
517 static int net_socket_listen_init(NetClientState *peer,
520 const char *host_str)
524 struct sockaddr_in saddr;
527 if (parse_host_port(&saddr, host_str) < 0)
530 fd = qemu_socket(PF_INET, SOCK_STREAM, 0);
535 qemu_set_nonblock(fd);
537 socket_set_fast_reuse(fd);
539 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
552 nc = qemu_new_net_client(&net_socket_info, peer, model, name);
553 s = DO_UPCAST(NetSocketState, nc, nc);
556 s->nc.link_down = true;
558 qemu_set_fd_handler(s->listen_fd, net_socket_accept, NULL, s);
562 static int net_socket_connect_init(NetClientState *peer,
565 const char *host_str)
568 int fd, connected, ret;
569 struct sockaddr_in saddr;
571 if (parse_host_port(&saddr, host_str) < 0)
574 fd = qemu_socket(PF_INET, SOCK_STREAM, 0);
579 qemu_set_nonblock(fd);
583 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
585 if (errno == EINTR || errno == EWOULDBLOCK) {
587 } else if (errno == EINPROGRESS ||
601 s = net_socket_fd_init(peer, model, name, fd, connected);
604 snprintf(s->nc.info_str, sizeof(s->nc.info_str),
605 "socket: connect to %s:%d",
606 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
610 static int net_socket_mcast_init(NetClientState *peer,
613 const char *host_str,
614 const char *localaddr_str)
618 struct sockaddr_in saddr;
619 struct in_addr localaddr, *param_localaddr;
621 if (parse_host_port(&saddr, host_str) < 0)
624 if (localaddr_str != NULL) {
625 if (inet_aton(localaddr_str, &localaddr) == 0)
627 param_localaddr = &localaddr;
629 param_localaddr = NULL;
632 fd = net_socket_mcast_create(&saddr, param_localaddr);
636 s = net_socket_fd_init(peer, model, name, fd, 0);
640 s->dgram_dst = saddr;
642 snprintf(s->nc.info_str, sizeof(s->nc.info_str),
643 "socket: mcast=%s:%d",
644 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
649 static int net_socket_udp_init(NetClientState *peer,
657 struct sockaddr_in laddr, raddr;
659 if (parse_host_port(&laddr, lhost) < 0) {
663 if (parse_host_port(&raddr, rhost) < 0) {
667 fd = qemu_socket(PF_INET, SOCK_DGRAM, 0);
669 perror("socket(PF_INET, SOCK_DGRAM)");
673 ret = socket_set_fast_reuse(fd);
678 ret = bind(fd, (struct sockaddr *)&laddr, sizeof(laddr));
684 qemu_set_nonblock(fd);
686 s = net_socket_fd_init(peer, model, name, fd, 0);
691 s->dgram_dst = raddr;
693 snprintf(s->nc.info_str, sizeof(s->nc.info_str),
695 inet_ntoa(raddr.sin_addr), ntohs(raddr.sin_port));
699 int net_init_socket(const NetClientOptions *opts, const char *name,
700 NetClientState *peer, Error **errp)
702 /* FIXME error_setg(errp, ...) on failure */
704 const NetdevSocketOptions *sock;
706 assert(opts->type == NET_CLIENT_OPTIONS_KIND_SOCKET);
707 sock = opts->u.socket;
709 if (sock->has_fd + sock->has_listen + sock->has_connect + sock->has_mcast +
710 sock->has_udp != 1) {
711 error_report("exactly one of fd=, listen=, connect=, mcast= or udp="
716 if (sock->has_localaddr && !sock->has_mcast && !sock->has_udp) {
717 error_report("localaddr= is only valid with mcast= or udp=");
724 fd = monitor_fd_param(cur_mon, sock->fd, &err);
726 error_report_err(err);
729 qemu_set_nonblock(fd);
730 if (!net_socket_fd_init(peer, "socket", name, fd, 1)) {
736 if (sock->has_listen) {
737 if (net_socket_listen_init(peer, "socket", name, sock->listen) == -1) {
743 if (sock->has_connect) {
744 if (net_socket_connect_init(peer, "socket", name, sock->connect) ==
751 if (sock->has_mcast) {
752 /* if sock->localaddr is missing, it has been initialized to "all bits
754 if (net_socket_mcast_init(peer, "socket", name, sock->mcast,
755 sock->localaddr) == -1) {
761 assert(sock->has_udp);
762 if (!sock->has_localaddr) {
763 error_report("localaddr= is mandatory with udp=");
766 if (net_socket_udp_init(peer, "socket", name, sock->udp, sock->localaddr) ==