pc-bios/s390-ccw: enable virtio-scsi
[qemu.git] / net / socket.c
blob9826efb46f02c165d78179b2550bdc225db3ddd9
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 "qemu-common.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 int state; /* 0 = getting length, 1 = getting data */
41 unsigned int index;
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? */
49 } NetSocketState;
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,
59 s);
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[] = {
89 .iov_base = &len,
90 .iov_len = sizeof(len),
91 }, {
92 .iov_base = (void *)buf,
93 .iov_len = size,
96 size_t remaining;
97 ssize_t ret;
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 */
105 if (ret == -1) {
106 s->send_index = 0;
107 return -errno;
109 if (ret < (ssize_t)remaining) {
110 s->send_index += ret;
111 net_socket_write_poll(s, true);
112 return 0;
114 s->send_index = 0;
115 return size;
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);
121 ssize_t ret;
123 do {
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);
131 return 0;
133 return ret;
136 static void net_socket_send_completed(NetClientState *nc, ssize_t len)
138 NetSocketState *s = DO_UPCAST(NetSocketState, nc, nc);
140 if (!s->read_poll) {
141 net_socket_read_poll(s, true);
145 static void net_socket_send(void *opaque)
147 NetSocketState *s = opaque;
148 int size;
149 unsigned l;
150 uint8_t buf1[NET_BUFSIZE];
151 const uint8_t *buf;
153 size = qemu_recv(s->fd, buf1, sizeof(buf1), 0);
154 if (size < 0) {
155 if (errno != EWOULDBLOCK)
156 goto eoc;
157 } else if (size == 0) {
158 /* end of connection */
159 eoc:
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);
165 closesocket(s->fd);
167 s->fd = -1;
168 s->state = 0;
169 s->index = 0;
170 s->packet_len = 0;
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));
175 return;
177 buf = buf1;
178 while (size > 0) {
179 /* reassemble a packet from the network */
180 switch(s->state) {
181 case 0:
182 l = 4 - s->index;
183 if (l > size)
184 l = size;
185 memcpy(s->buf + s->index, buf, l);
186 buf += l;
187 size -= l;
188 s->index += l;
189 if (s->index == 4) {
190 /* got length */
191 s->packet_len = ntohl(*(uint32_t *)s->buf);
192 s->index = 0;
193 s->state = 1;
195 break;
196 case 1:
197 l = s->packet_len - s->index;
198 if (l > size)
199 l = size;
200 if (s->index + l <= sizeof(s->buf)) {
201 memcpy(s->buf + s->index, buf, l);
202 } else {
203 fprintf(stderr, "serious error: oversized packet received,"
204 "connection terminated.\n");
205 s->state = 0;
206 goto eoc;
209 s->index += l;
210 buf += l;
211 size -= l;
212 if (s->index >= s->packet_len) {
213 s->index = 0;
214 s->state = 0;
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);
218 break;
221 break;
226 static void net_socket_send_dgram(void *opaque)
228 NetSocketState *s = opaque;
229 int size;
231 size = qemu_recv(s->fd, s->buf, sizeof(s->buf), 0);
232 if (size < 0)
233 return;
234 if (size == 0) {
235 /* end of connection */
236 net_socket_read_poll(s, false);
237 net_socket_write_poll(s, false);
238 return;
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)
248 struct ip_mreq imr;
249 int fd;
250 int val, ret;
251 #ifdef __OpenBSD__
252 unsigned char loop;
253 #else
254 int loop;
255 #endif
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));
262 return -1;
265 fd = qemu_socket(PF_INET, SOCK_DGRAM, 0);
266 if (fd < 0) {
267 perror("socket(PF_INET, SOCK_DGRAM)");
268 return -1;
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.
276 val = 1;
277 ret = qemu_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
278 if (ret < 0) {
279 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
280 goto fail;
283 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
284 if (ret < 0) {
285 perror("bind");
286 goto fail;
289 /* Add host to multicast group */
290 imr.imr_multiaddr = mcastaddr->sin_addr;
291 if (localaddr) {
292 imr.imr_interface = *localaddr;
293 } else {
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));
299 if (ret < 0) {
300 perror("setsockopt(IP_ADD_MEMBERSHIP)");
301 goto fail;
304 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
305 loop = 1;
306 ret = qemu_setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
307 &loop, sizeof(loop));
308 if (ret < 0) {
309 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
310 goto fail;
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));
317 if (ret < 0) {
318 perror("setsockopt(IP_MULTICAST_IF)");
319 goto fail;
323 qemu_set_nonblock(fd);
324 return fd;
325 fail:
326 if (fd >= 0)
327 closesocket(fd);
328 return -1;
331 static void net_socket_cleanup(NetClientState *nc)
333 NetSocketState *s = DO_UPCAST(NetSocketState, nc, nc);
334 if (s->fd != -1) {
335 net_socket_read_poll(s, false);
336 net_socket_write_poll(s, false);
337 close(s->fd);
338 s->fd = -1;
340 if (s->listen_fd != -1) {
341 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
342 closesocket(s->listen_fd);
343 s->listen_fd = -1;
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,
355 const char *model,
356 const char *name,
357 int fd, int is_connected)
359 struct sockaddr_in saddr;
360 int newfd;
361 socklen_t saddr_len = sizeof(saddr);
362 NetClientState *nc;
363 NetSocketState *s;
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
370 if (is_connected) {
371 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
372 /* must be bound */
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);
376 goto err;
378 /* clone dgram socket */
379 newfd = net_socket_mcast_create(&saddr, NULL);
380 if (newfd < 0) {
381 /* error already reported by net_socket_mcast_create() */
382 goto err;
384 /* clone newfd to fd, close newfd */
385 dup2(newfd, fd);
386 close(newfd);
388 } else {
389 fprintf(stderr,
390 "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
391 fd, strerror(errno));
392 goto err;
396 nc = qemu_new_net_client(&net_dgram_socket_info, peer, model, name);
398 s = DO_UPCAST(NetSocketState, nc, nc);
400 s->fd = fd;
401 s->listen_fd = -1;
402 s->send_fn = net_socket_send_dgram;
403 net_socket_read_poll(s, true);
405 /* mcast: save bound address as dst */
406 if (is_connected) {
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));
411 } else {
412 snprintf(nc->info_str, sizeof(nc->info_str),
413 "socket: fd=%d", fd);
416 return s;
418 err:
419 closesocket(fd);
420 return NULL;
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,
438 const char *model,
439 const char *name,
440 int fd, int is_connected)
442 NetClientState *nc;
443 NetSocketState *s;
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);
451 s->fd = fd;
452 s->listen_fd = -1;
454 /* Disable Nagle algorithm on TCP sockets to reduce latency */
455 socket_set_nodelay(fd);
457 if (is_connected) {
458 net_socket_connect(s);
459 } else {
460 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
462 return 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",
474 fd);
475 closesocket(fd);
476 return NULL;
478 switch(so_type) {
479 case SOCK_DGRAM:
480 return net_socket_fd_init_dgram(peer, model, name, fd, is_connected);
481 case SOCK_STREAM:
482 return net_socket_fd_init_stream(peer, model, name, fd, is_connected);
483 default:
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);
488 return NULL;
491 static void net_socket_accept(void *opaque)
493 NetSocketState *s = opaque;
494 struct sockaddr_in saddr;
495 socklen_t len;
496 int fd;
498 for(;;) {
499 len = sizeof(saddr);
500 fd = qemu_accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
501 if (fd < 0 && errno != EINTR) {
502 return;
503 } else if (fd >= 0) {
504 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
505 break;
509 s->fd = fd;
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,
518 const char *model,
519 const char *name,
520 const char *host_str)
522 NetClientState *nc;
523 NetSocketState *s;
524 struct sockaddr_in saddr;
525 int fd, ret;
527 if (parse_host_port(&saddr, host_str) < 0)
528 return -1;
530 fd = qemu_socket(PF_INET, SOCK_STREAM, 0);
531 if (fd < 0) {
532 perror("socket");
533 return -1;
535 qemu_set_nonblock(fd);
537 socket_set_fast_reuse(fd);
539 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
540 if (ret < 0) {
541 perror("bind");
542 closesocket(fd);
543 return -1;
545 ret = listen(fd, 0);
546 if (ret < 0) {
547 perror("listen");
548 closesocket(fd);
549 return -1;
552 nc = qemu_new_net_client(&net_socket_info, peer, model, name);
553 s = DO_UPCAST(NetSocketState, nc, nc);
554 s->fd = -1;
555 s->listen_fd = fd;
556 s->nc.link_down = true;
558 qemu_set_fd_handler(s->listen_fd, net_socket_accept, NULL, s);
559 return 0;
562 static int net_socket_connect_init(NetClientState *peer,
563 const char *model,
564 const char *name,
565 const char *host_str)
567 NetSocketState *s;
568 int fd, connected, ret;
569 struct sockaddr_in saddr;
571 if (parse_host_port(&saddr, host_str) < 0)
572 return -1;
574 fd = qemu_socket(PF_INET, SOCK_STREAM, 0);
575 if (fd < 0) {
576 perror("socket");
577 return -1;
579 qemu_set_nonblock(fd);
581 connected = 0;
582 for(;;) {
583 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
584 if (ret < 0) {
585 if (errno == EINTR || errno == EWOULDBLOCK) {
586 /* continue */
587 } else if (errno == EINPROGRESS ||
588 errno == EALREADY ||
589 errno == EINVAL) {
590 break;
591 } else {
592 perror("connect");
593 closesocket(fd);
594 return -1;
596 } else {
597 connected = 1;
598 break;
601 s = net_socket_fd_init(peer, model, name, fd, connected);
602 if (!s)
603 return -1;
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));
607 return 0;
610 static int net_socket_mcast_init(NetClientState *peer,
611 const char *model,
612 const char *name,
613 const char *host_str,
614 const char *localaddr_str)
616 NetSocketState *s;
617 int fd;
618 struct sockaddr_in saddr;
619 struct in_addr localaddr, *param_localaddr;
621 if (parse_host_port(&saddr, host_str) < 0)
622 return -1;
624 if (localaddr_str != NULL) {
625 if (inet_aton(localaddr_str, &localaddr) == 0)
626 return -1;
627 param_localaddr = &localaddr;
628 } else {
629 param_localaddr = NULL;
632 fd = net_socket_mcast_create(&saddr, param_localaddr);
633 if (fd < 0)
634 return -1;
636 s = net_socket_fd_init(peer, model, name, fd, 0);
637 if (!s)
638 return -1;
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));
645 return 0;
649 static int net_socket_udp_init(NetClientState *peer,
650 const char *model,
651 const char *name,
652 const char *rhost,
653 const char *lhost)
655 NetSocketState *s;
656 int fd, ret;
657 struct sockaddr_in laddr, raddr;
659 if (parse_host_port(&laddr, lhost) < 0) {
660 return -1;
663 if (parse_host_port(&raddr, rhost) < 0) {
664 return -1;
667 fd = qemu_socket(PF_INET, SOCK_DGRAM, 0);
668 if (fd < 0) {
669 perror("socket(PF_INET, SOCK_DGRAM)");
670 return -1;
673 ret = socket_set_fast_reuse(fd);
674 if (ret < 0) {
675 closesocket(fd);
676 return -1;
678 ret = bind(fd, (struct sockaddr *)&laddr, sizeof(laddr));
679 if (ret < 0) {
680 perror("bind");
681 closesocket(fd);
682 return -1;
684 qemu_set_nonblock(fd);
686 s = net_socket_fd_init(peer, model, name, fd, 0);
687 if (!s) {
688 return -1;
691 s->dgram_dst = raddr;
693 snprintf(s->nc.info_str, sizeof(s->nc.info_str),
694 "socket: udp=%s:%d",
695 inet_ntoa(raddr.sin_addr), ntohs(raddr.sin_port));
696 return 0;
699 int net_init_socket(const NetClientOptions *opts, const char *name,
700 NetClientState *peer, Error **errp)
702 /* FIXME error_setg(errp, ...) on failure */
703 Error *err = NULL;
704 const NetdevSocketOptions *sock;
706 assert(opts->type == NET_CLIENT_OPTIONS_KIND_SOCKET);
707 sock = opts->u.socket.data;
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="
712 " is required");
713 return -1;
716 if (sock->has_localaddr && !sock->has_mcast && !sock->has_udp) {
717 error_report("localaddr= is only valid with mcast= or udp=");
718 return -1;
721 if (sock->has_fd) {
722 int fd;
724 fd = monitor_fd_param(cur_mon, sock->fd, &err);
725 if (fd == -1) {
726 error_report_err(err);
727 return -1;
729 qemu_set_nonblock(fd);
730 if (!net_socket_fd_init(peer, "socket", name, fd, 1)) {
731 return -1;
733 return 0;
736 if (sock->has_listen) {
737 if (net_socket_listen_init(peer, "socket", name, sock->listen) == -1) {
738 return -1;
740 return 0;
743 if (sock->has_connect) {
744 if (net_socket_connect_init(peer, "socket", name, sock->connect) ==
745 -1) {
746 return -1;
748 return 0;
751 if (sock->has_mcast) {
752 /* if sock->localaddr is missing, it has been initialized to "all bits
753 * zero" */
754 if (net_socket_mcast_init(peer, "socket", name, sock->mcast,
755 sock->localaddr) == -1) {
756 return -1;
758 return 0;
761 assert(sock->has_udp);
762 if (!sock->has_localaddr) {
763 error_report("localaddr= is mandatory with udp=");
764 return -1;
766 if (net_socket_udp_init(peer, "socket", name, sock->udp, sock->localaddr) ==
767 -1) {
768 return -1;
770 return 0;