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 "config-host.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"
35 typedef struct NetSocketState {
39 int state; /* 0 = getting length, 1 = getting data */
41 unsigned int packet_len;
42 unsigned int send_index; /* number of bytes sent (only SOCK_STREAM) */
43 uint8_t buf[NET_BUFSIZE];
44 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
45 IOHandler *send_fn; /* differs between SOCK_STREAM/SOCK_DGRAM */
46 bool read_poll; /* waiting to receive data? */
47 bool write_poll; /* waiting to transmit data? */
50 static void net_socket_accept(void *opaque);
51 static void net_socket_writable(void *opaque);
53 /* Only read packets from socket when peer can receive them */
54 static int net_socket_can_send(void *opaque)
56 NetSocketState *s = opaque;
58 return qemu_can_send_packet(&s->nc);
61 static void net_socket_update_fd_handler(NetSocketState *s)
63 qemu_set_fd_handler2(s->fd,
64 s->read_poll ? net_socket_can_send : NULL,
65 s->read_poll ? s->send_fn : NULL,
66 s->write_poll ? net_socket_writable : NULL,
70 static void net_socket_read_poll(NetSocketState *s, bool enable)
72 s->read_poll = enable;
73 net_socket_update_fd_handler(s);
76 static void net_socket_write_poll(NetSocketState *s, bool enable)
78 s->write_poll = enable;
79 net_socket_update_fd_handler(s);
82 static void net_socket_writable(void *opaque)
84 NetSocketState *s = opaque;
86 net_socket_write_poll(s, false);
88 qemu_flush_queued_packets(&s->nc);
91 static ssize_t net_socket_receive(NetClientState *nc, const uint8_t *buf, size_t size)
93 NetSocketState *s = DO_UPCAST(NetSocketState, nc, nc);
94 uint32_t len = htonl(size);
95 struct iovec iov[] = {
98 .iov_len = sizeof(len),
100 .iov_base = (void *)buf,
107 remaining = iov_size(iov, 2) - s->send_index;
108 ret = iov_send(s->fd, iov, 2, s->send_index, remaining);
110 if (ret == -1 && errno == EAGAIN) {
111 ret = 0; /* handled further down */
117 if (ret < (ssize_t)remaining) {
118 s->send_index += ret;
119 net_socket_write_poll(s, true);
126 static ssize_t net_socket_receive_dgram(NetClientState *nc, const uint8_t *buf, size_t size)
128 NetSocketState *s = DO_UPCAST(NetSocketState, nc, nc);
132 ret = qemu_sendto(s->fd, buf, size, 0,
133 (struct sockaddr *)&s->dgram_dst,
134 sizeof(s->dgram_dst));
135 } while (ret == -1 && errno == EINTR);
137 if (ret == -1 && errno == EAGAIN) {
138 net_socket_write_poll(s, true);
144 static void net_socket_send(void *opaque)
146 NetSocketState *s = opaque;
149 uint8_t buf1[NET_BUFSIZE];
152 size = qemu_recv(s->fd, buf1, sizeof(buf1), 0);
154 err = socket_error();
155 if (err != 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) {
213 qemu_send_packet(&s->nc, s->buf, s->packet_len);
222 static void net_socket_send_dgram(void *opaque)
224 NetSocketState *s = opaque;
227 size = qemu_recv(s->fd, s->buf, sizeof(s->buf), 0);
231 /* end of connection */
232 net_socket_read_poll(s, false);
233 net_socket_write_poll(s, false);
236 qemu_send_packet(&s->nc, s->buf, size);
239 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr, struct in_addr *localaddr)
250 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
251 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) "
252 "does not contain a multicast address\n",
253 inet_ntoa(mcastaddr->sin_addr),
254 (int)ntohl(mcastaddr->sin_addr.s_addr));
258 fd = qemu_socket(PF_INET, SOCK_DGRAM, 0);
260 perror("socket(PF_INET, SOCK_DGRAM)");
265 ret = qemu_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
267 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
271 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
277 /* Add host to multicast group */
278 imr.imr_multiaddr = mcastaddr->sin_addr;
280 imr.imr_interface = *localaddr;
282 imr.imr_interface.s_addr = htonl(INADDR_ANY);
285 ret = qemu_setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
286 &imr, sizeof(struct ip_mreq));
288 perror("setsockopt(IP_ADD_MEMBERSHIP)");
292 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
294 ret = qemu_setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
295 &loop, sizeof(loop));
297 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
301 /* If a bind address is given, only send packets from that address */
302 if (localaddr != NULL) {
303 ret = qemu_setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF,
304 localaddr, sizeof(*localaddr));
306 perror("setsockopt(IP_MULTICAST_IF)");
311 qemu_set_nonblock(fd);
319 static void net_socket_cleanup(NetClientState *nc)
321 NetSocketState *s = DO_UPCAST(NetSocketState, nc, nc);
323 net_socket_read_poll(s, false);
324 net_socket_write_poll(s, false);
328 if (s->listen_fd != -1) {
329 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
330 closesocket(s->listen_fd);
335 static NetClientInfo net_dgram_socket_info = {
336 .type = NET_CLIENT_OPTIONS_KIND_SOCKET,
337 .size = sizeof(NetSocketState),
338 .receive = net_socket_receive_dgram,
339 .cleanup = net_socket_cleanup,
342 static NetSocketState *net_socket_fd_init_dgram(NetClientState *peer,
345 int fd, int is_connected)
347 struct sockaddr_in saddr;
353 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
354 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
355 * by ONLY ONE process: we must "clone" this dgram socket --jjo
359 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
361 if (saddr.sin_addr.s_addr == 0) {
362 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, "
363 "cannot setup multicast dst addr\n", fd);
366 /* clone dgram socket */
367 newfd = net_socket_mcast_create(&saddr, NULL);
369 /* error already reported by net_socket_mcast_create() */
372 /* clone newfd to fd, close newfd */
378 "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
379 fd, strerror(errno));
384 nc = qemu_new_net_client(&net_dgram_socket_info, peer, model, name);
386 snprintf(nc->info_str, sizeof(nc->info_str),
387 "socket: fd=%d (%s mcast=%s:%d)",
388 fd, is_connected ? "cloned" : "",
389 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
391 s = DO_UPCAST(NetSocketState, nc, nc);
395 s->send_fn = net_socket_send_dgram;
396 net_socket_read_poll(s, true);
398 /* mcast: save bound address as dst */
400 s->dgram_dst = saddr;
410 static void net_socket_connect(void *opaque)
412 NetSocketState *s = opaque;
413 s->send_fn = net_socket_send;
414 net_socket_read_poll(s, true);
417 static NetClientInfo net_socket_info = {
418 .type = NET_CLIENT_OPTIONS_KIND_SOCKET,
419 .size = sizeof(NetSocketState),
420 .receive = net_socket_receive,
421 .cleanup = net_socket_cleanup,
424 static NetSocketState *net_socket_fd_init_stream(NetClientState *peer,
427 int fd, int is_connected)
432 nc = qemu_new_net_client(&net_socket_info, peer, model, name);
434 snprintf(nc->info_str, sizeof(nc->info_str), "socket: fd=%d", fd);
436 s = DO_UPCAST(NetSocketState, nc, nc);
441 /* Disable Nagle algorithm on TCP sockets to reduce latency */
442 socket_set_nodelay(fd);
445 net_socket_connect(s);
447 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
452 static NetSocketState *net_socket_fd_init(NetClientState *peer,
453 const char *model, const char *name,
454 int fd, int is_connected)
456 int so_type = -1, optlen=sizeof(so_type);
458 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
459 (socklen_t *)&optlen)< 0) {
460 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n",
467 return net_socket_fd_init_dgram(peer, model, name, fd, is_connected);
469 return net_socket_fd_init_stream(peer, model, name, fd, is_connected);
471 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
472 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
473 return net_socket_fd_init_stream(peer, model, name, fd, is_connected);
478 static void net_socket_accept(void *opaque)
480 NetSocketState *s = opaque;
481 struct sockaddr_in saddr;
487 fd = qemu_accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
488 if (fd < 0 && errno != EINTR) {
490 } else if (fd >= 0) {
491 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
497 s->nc.link_down = false;
498 net_socket_connect(s);
499 snprintf(s->nc.info_str, sizeof(s->nc.info_str),
500 "socket: connection from %s:%d",
501 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
504 static int net_socket_listen_init(NetClientState *peer,
507 const char *host_str)
511 struct sockaddr_in saddr;
514 if (parse_host_port(&saddr, host_str) < 0)
517 fd = qemu_socket(PF_INET, SOCK_STREAM, 0);
522 qemu_set_nonblock(fd);
524 /* allow fast reuse */
526 qemu_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
528 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
541 nc = qemu_new_net_client(&net_socket_info, peer, model, name);
542 s = DO_UPCAST(NetSocketState, nc, nc);
545 s->nc.link_down = true;
547 qemu_set_fd_handler(s->listen_fd, net_socket_accept, NULL, s);
551 static int net_socket_connect_init(NetClientState *peer,
554 const char *host_str)
557 int fd, connected, ret, err;
558 struct sockaddr_in saddr;
560 if (parse_host_port(&saddr, host_str) < 0)
563 fd = qemu_socket(PF_INET, SOCK_STREAM, 0);
568 qemu_set_nonblock(fd);
572 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
574 err = socket_error();
575 if (err == EINTR || err == EWOULDBLOCK) {
576 } else if (err == EINPROGRESS) {
579 } else if (err == WSAEALREADY || err == WSAEINVAL) {
592 s = net_socket_fd_init(peer, model, name, fd, connected);
595 snprintf(s->nc.info_str, sizeof(s->nc.info_str),
596 "socket: connect to %s:%d",
597 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
601 static int net_socket_mcast_init(NetClientState *peer,
604 const char *host_str,
605 const char *localaddr_str)
609 struct sockaddr_in saddr;
610 struct in_addr localaddr, *param_localaddr;
612 if (parse_host_port(&saddr, host_str) < 0)
615 if (localaddr_str != NULL) {
616 if (inet_aton(localaddr_str, &localaddr) == 0)
618 param_localaddr = &localaddr;
620 param_localaddr = NULL;
623 fd = net_socket_mcast_create(&saddr, param_localaddr);
627 s = net_socket_fd_init(peer, model, name, fd, 0);
631 s->dgram_dst = saddr;
633 snprintf(s->nc.info_str, sizeof(s->nc.info_str),
634 "socket: mcast=%s:%d",
635 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
640 static int net_socket_udp_init(NetClientState *peer,
648 struct sockaddr_in laddr, raddr;
650 if (parse_host_port(&laddr, lhost) < 0) {
654 if (parse_host_port(&raddr, rhost) < 0) {
658 fd = qemu_socket(PF_INET, SOCK_DGRAM, 0);
660 perror("socket(PF_INET, SOCK_DGRAM)");
664 ret = qemu_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
667 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
671 ret = bind(fd, (struct sockaddr *)&laddr, sizeof(laddr));
677 qemu_set_nonblock(fd);
679 s = net_socket_fd_init(peer, model, name, fd, 0);
684 s->dgram_dst = raddr;
686 snprintf(s->nc.info_str, sizeof(s->nc.info_str),
688 inet_ntoa(raddr.sin_addr), ntohs(raddr.sin_port));
692 int net_init_socket(const NetClientOptions *opts, const char *name,
693 NetClientState *peer)
695 const NetdevSocketOptions *sock;
697 assert(opts->kind == NET_CLIENT_OPTIONS_KIND_SOCKET);
700 if (sock->has_fd + sock->has_listen + sock->has_connect + sock->has_mcast +
701 sock->has_udp != 1) {
702 error_report("exactly one of fd=, listen=, connect=, mcast= or udp="
707 if (sock->has_localaddr && !sock->has_mcast && !sock->has_udp) {
708 error_report("localaddr= is only valid with mcast= or udp=");
715 fd = monitor_handle_fd_param(cur_mon, sock->fd);
719 qemu_set_nonblock(fd);
720 if (!net_socket_fd_init(peer, "socket", name, fd, 1)) {
726 if (sock->has_listen) {
727 if (net_socket_listen_init(peer, "socket", name, sock->listen) == -1) {
733 if (sock->has_connect) {
734 if (net_socket_connect_init(peer, "socket", name, sock->connect) ==
741 if (sock->has_mcast) {
742 /* if sock->localaddr is missing, it has been initialized to "all bits
744 if (net_socket_mcast_init(peer, "socket", name, sock->mcast,
745 sock->localaddr) == -1) {
751 assert(sock->has_udp);
752 if (!sock->has_localaddr) {
753 error_report("localaddr= is mandatory with udp=");
756 if (net_socket_udp_init(peer, "socket", name, sock->udp, sock->localaddr) ==