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"
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 err
= socket_error();
156 if (err
!= EWOULDBLOCK
)
158 } else if (size
== 0) {
159 /* end of connection */
161 net_socket_read_poll(s
, false);
162 net_socket_write_poll(s
, false);
163 if (s
->listen_fd
!= -1) {
164 qemu_set_fd_handler(s
->listen_fd
, net_socket_accept
, NULL
, s
);
172 s
->nc
.link_down
= true;
173 memset(s
->buf
, 0, sizeof(s
->buf
));
174 memset(s
->nc
.info_str
, 0, sizeof(s
->nc
.info_str
));
180 /* reassemble a packet from the network */
186 memcpy(s
->buf
+ s
->index
, buf
, l
);
192 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
198 l
= s
->packet_len
- s
->index
;
201 if (s
->index
+ l
<= sizeof(s
->buf
)) {
202 memcpy(s
->buf
+ s
->index
, buf
, l
);
204 fprintf(stderr
, "serious error: oversized packet received,"
205 "connection terminated.\n");
213 if (s
->index
>= s
->packet_len
) {
216 if (qemu_send_packet_async(&s
->nc
, s
->buf
, size
,
217 net_socket_send_completed
) == 0) {
218 net_socket_read_poll(s
, false);
227 static void net_socket_send_dgram(void *opaque
)
229 NetSocketState
*s
= opaque
;
232 size
= qemu_recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
236 /* end of connection */
237 net_socket_read_poll(s
, false);
238 net_socket_write_poll(s
, false);
241 if (qemu_send_packet_async(&s
->nc
, s
->buf
, size
,
242 net_socket_send_completed
) == 0) {
243 net_socket_read_poll(s
, false);
247 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
, struct in_addr
*localaddr
)
258 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
259 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) "
260 "does not contain a multicast address\n",
261 inet_ntoa(mcastaddr
->sin_addr
),
262 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
266 fd
= qemu_socket(PF_INET
, SOCK_DGRAM
, 0);
268 perror("socket(PF_INET, SOCK_DGRAM)");
272 /* Allow multiple sockets to bind the same multicast ip and port by setting
273 * SO_REUSEADDR. This is the only situation where SO_REUSEADDR should be set
274 * on windows. Use socket_set_fast_reuse otherwise as it sets SO_REUSEADDR
275 * only on posix systems.
278 ret
= qemu_setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
, sizeof(val
));
280 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
284 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
290 /* Add host to multicast group */
291 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
293 imr
.imr_interface
= *localaddr
;
295 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
298 ret
= qemu_setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
299 &imr
, sizeof(struct ip_mreq
));
301 perror("setsockopt(IP_ADD_MEMBERSHIP)");
305 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
307 ret
= qemu_setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
308 &loop
, sizeof(loop
));
310 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
314 /* If a bind address is given, only send packets from that address */
315 if (localaddr
!= NULL
) {
316 ret
= qemu_setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_IF
,
317 localaddr
, sizeof(*localaddr
));
319 perror("setsockopt(IP_MULTICAST_IF)");
324 qemu_set_nonblock(fd
);
332 static void net_socket_cleanup(NetClientState
*nc
)
334 NetSocketState
*s
= DO_UPCAST(NetSocketState
, nc
, nc
);
336 net_socket_read_poll(s
, false);
337 net_socket_write_poll(s
, false);
341 if (s
->listen_fd
!= -1) {
342 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
343 closesocket(s
->listen_fd
);
348 static NetClientInfo net_dgram_socket_info
= {
349 .type
= NET_CLIENT_OPTIONS_KIND_SOCKET
,
350 .size
= sizeof(NetSocketState
),
351 .receive
= net_socket_receive_dgram
,
352 .cleanup
= net_socket_cleanup
,
355 static NetSocketState
*net_socket_fd_init_dgram(NetClientState
*peer
,
358 int fd
, int is_connected
)
360 struct sockaddr_in saddr
;
362 socklen_t saddr_len
= sizeof(saddr
);
366 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
367 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
368 * by ONLY ONE process: we must "clone" this dgram socket --jjo
372 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
374 if (saddr
.sin_addr
.s_addr
== 0) {
375 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, "
376 "cannot setup multicast dst addr\n", fd
);
379 /* clone dgram socket */
380 newfd
= net_socket_mcast_create(&saddr
, NULL
);
382 /* error already reported by net_socket_mcast_create() */
385 /* clone newfd to fd, close newfd */
391 "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
392 fd
, strerror(errno
));
397 nc
= qemu_new_net_client(&net_dgram_socket_info
, peer
, model
, name
);
399 s
= DO_UPCAST(NetSocketState
, nc
, nc
);
403 s
->send_fn
= net_socket_send_dgram
;
404 net_socket_read_poll(s
, true);
406 /* mcast: save bound address as dst */
408 s
->dgram_dst
= saddr
;
409 snprintf(nc
->info_str
, sizeof(nc
->info_str
),
410 "socket: fd=%d (cloned mcast=%s:%d)",
411 fd
, inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
413 snprintf(nc
->info_str
, sizeof(nc
->info_str
),
414 "socket: fd=%d", fd
);
424 static void net_socket_connect(void *opaque
)
426 NetSocketState
*s
= opaque
;
427 s
->send_fn
= net_socket_send
;
428 net_socket_read_poll(s
, true);
431 static NetClientInfo net_socket_info
= {
432 .type
= NET_CLIENT_OPTIONS_KIND_SOCKET
,
433 .size
= sizeof(NetSocketState
),
434 .receive
= net_socket_receive
,
435 .cleanup
= net_socket_cleanup
,
438 static NetSocketState
*net_socket_fd_init_stream(NetClientState
*peer
,
441 int fd
, int is_connected
)
446 nc
= qemu_new_net_client(&net_socket_info
, peer
, model
, name
);
448 snprintf(nc
->info_str
, sizeof(nc
->info_str
), "socket: fd=%d", fd
);
450 s
= DO_UPCAST(NetSocketState
, nc
, nc
);
455 /* Disable Nagle algorithm on TCP sockets to reduce latency */
456 socket_set_nodelay(fd
);
459 net_socket_connect(s
);
461 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
466 static NetSocketState
*net_socket_fd_init(NetClientState
*peer
,
467 const char *model
, const char *name
,
468 int fd
, int is_connected
)
470 int so_type
= -1, optlen
=sizeof(so_type
);
472 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
,
473 (socklen_t
*)&optlen
)< 0) {
474 fprintf(stderr
, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n",
481 return net_socket_fd_init_dgram(peer
, model
, name
, fd
, is_connected
);
483 return net_socket_fd_init_stream(peer
, model
, name
, fd
, is_connected
);
485 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
486 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
487 return net_socket_fd_init_stream(peer
, model
, name
, fd
, is_connected
);
492 static void net_socket_accept(void *opaque
)
494 NetSocketState
*s
= opaque
;
495 struct sockaddr_in saddr
;
501 fd
= qemu_accept(s
->listen_fd
, (struct sockaddr
*)&saddr
, &len
);
502 if (fd
< 0 && errno
!= EINTR
) {
504 } else if (fd
>= 0) {
505 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
511 s
->nc
.link_down
= false;
512 net_socket_connect(s
);
513 snprintf(s
->nc
.info_str
, sizeof(s
->nc
.info_str
),
514 "socket: connection from %s:%d",
515 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
518 static int net_socket_listen_init(NetClientState
*peer
,
521 const char *host_str
)
525 struct sockaddr_in saddr
;
528 if (parse_host_port(&saddr
, host_str
) < 0)
531 fd
= qemu_socket(PF_INET
, SOCK_STREAM
, 0);
536 qemu_set_nonblock(fd
);
538 socket_set_fast_reuse(fd
);
540 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
553 nc
= qemu_new_net_client(&net_socket_info
, peer
, model
, name
);
554 s
= DO_UPCAST(NetSocketState
, nc
, nc
);
557 s
->nc
.link_down
= true;
559 qemu_set_fd_handler(s
->listen_fd
, net_socket_accept
, NULL
, s
);
563 static int net_socket_connect_init(NetClientState
*peer
,
566 const char *host_str
)
569 int fd
, connected
, ret
, err
;
570 struct sockaddr_in saddr
;
572 if (parse_host_port(&saddr
, host_str
) < 0)
575 fd
= qemu_socket(PF_INET
, SOCK_STREAM
, 0);
580 qemu_set_nonblock(fd
);
584 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
586 err
= socket_error();
587 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
588 } else if (err
== EINPROGRESS
) {
591 } else if (err
== WSAEALREADY
|| err
== WSAEINVAL
) {
604 s
= net_socket_fd_init(peer
, model
, name
, fd
, connected
);
607 snprintf(s
->nc
.info_str
, sizeof(s
->nc
.info_str
),
608 "socket: connect to %s:%d",
609 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
613 static int net_socket_mcast_init(NetClientState
*peer
,
616 const char *host_str
,
617 const char *localaddr_str
)
621 struct sockaddr_in saddr
;
622 struct in_addr localaddr
, *param_localaddr
;
624 if (parse_host_port(&saddr
, host_str
) < 0)
627 if (localaddr_str
!= NULL
) {
628 if (inet_aton(localaddr_str
, &localaddr
) == 0)
630 param_localaddr
= &localaddr
;
632 param_localaddr
= NULL
;
635 fd
= net_socket_mcast_create(&saddr
, param_localaddr
);
639 s
= net_socket_fd_init(peer
, model
, name
, fd
, 0);
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
));
652 static int net_socket_udp_init(NetClientState
*peer
,
660 struct sockaddr_in laddr
, raddr
;
662 if (parse_host_port(&laddr
, lhost
) < 0) {
666 if (parse_host_port(&raddr
, rhost
) < 0) {
670 fd
= qemu_socket(PF_INET
, SOCK_DGRAM
, 0);
672 perror("socket(PF_INET, SOCK_DGRAM)");
676 ret
= socket_set_fast_reuse(fd
);
681 ret
= bind(fd
, (struct sockaddr
*)&laddr
, sizeof(laddr
));
687 qemu_set_nonblock(fd
);
689 s
= net_socket_fd_init(peer
, model
, name
, fd
, 0);
694 s
->dgram_dst
= raddr
;
696 snprintf(s
->nc
.info_str
, sizeof(s
->nc
.info_str
),
698 inet_ntoa(raddr
.sin_addr
), ntohs(raddr
.sin_port
));
702 int net_init_socket(const NetClientOptions
*opts
, const char *name
,
703 NetClientState
*peer
, Error
**errp
)
705 /* FIXME error_setg(errp, ...) on failure */
707 const NetdevSocketOptions
*sock
;
709 assert(opts
->kind
== NET_CLIENT_OPTIONS_KIND_SOCKET
);
712 if (sock
->has_fd
+ sock
->has_listen
+ sock
->has_connect
+ sock
->has_mcast
+
713 sock
->has_udp
!= 1) {
714 error_report("exactly one of fd=, listen=, connect=, mcast= or udp="
719 if (sock
->has_localaddr
&& !sock
->has_mcast
&& !sock
->has_udp
) {
720 error_report("localaddr= is only valid with mcast= or udp=");
727 fd
= monitor_fd_param(cur_mon
, sock
->fd
, &err
);
729 error_report_err(err
);
732 qemu_set_nonblock(fd
);
733 if (!net_socket_fd_init(peer
, "socket", name
, fd
, 1)) {
739 if (sock
->has_listen
) {
740 if (net_socket_listen_init(peer
, "socket", name
, sock
->listen
) == -1) {
746 if (sock
->has_connect
) {
747 if (net_socket_connect_init(peer
, "socket", name
, sock
->connect
) ==
754 if (sock
->has_mcast
) {
755 /* if sock->localaddr is missing, it has been initialized to "all bits
757 if (net_socket_mcast_init(peer
, "socket", name
, sock
->mcast
,
758 sock
->localaddr
) == -1) {
764 assert(sock
->has_udp
);
765 if (!sock
->has_localaddr
) {
766 error_report("localaddr= is mandatory with udp=");
769 if (net_socket_udp_init(peer
, "socket", name
, sock
->udp
, sock
->localaddr
) ==