]> git.proxmox.com Git - qemu.git/blob - net/socket.c
aabf0a48c5a4fa3645c11e4b5b5c9aa292fecd66
[qemu.git] / net / socket.c
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2008 Fabrice Bellard
5 *
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:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
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.
23 */
24 #include "net/socket.h"
25
26 #include "config-host.h"
27
28 #include "net.h"
29 #include "monitor.h"
30 #include "qemu-char.h"
31 #include "qemu-common.h"
32 #include "qemu-error.h"
33 #include "qemu-option.h"
34 #include "qemu_socket.h"
35
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 uint8_t buf[4096];
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? */
48 } NetSocketState;
49
50 static void net_socket_accept(void *opaque);
51 static void net_socket_writable(void *opaque);
52
53 /* Only read packets from socket when peer can receive them */
54 static int net_socket_can_send(void *opaque)
55 {
56 NetSocketState *s = opaque;
57
58 return qemu_can_send_packet(&s->nc);
59 }
60
61 static void net_socket_update_fd_handler(NetSocketState *s)
62 {
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,
67 s);
68 }
69
70 static void net_socket_read_poll(NetSocketState *s, bool enable)
71 {
72 s->read_poll = enable;
73 net_socket_update_fd_handler(s);
74 }
75
76 static void net_socket_write_poll(NetSocketState *s, bool enable)
77 {
78 s->write_poll = enable;
79 net_socket_update_fd_handler(s);
80 }
81
82 static void net_socket_writable(void *opaque)
83 {
84 NetSocketState *s = opaque;
85
86 net_socket_write_poll(s, false);
87
88 qemu_flush_queued_packets(&s->nc);
89 }
90
91 /* XXX: we consider we can send the whole packet without blocking */
92 static ssize_t net_socket_receive(NetClientState *nc, const uint8_t *buf, size_t size)
93 {
94 NetSocketState *s = DO_UPCAST(NetSocketState, nc, nc);
95 uint32_t len;
96 len = htonl(size);
97
98 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
99 return send_all(s->fd, buf, size);
100 }
101
102 static ssize_t net_socket_receive_dgram(NetClientState *nc, const uint8_t *buf, size_t size)
103 {
104 NetSocketState *s = DO_UPCAST(NetSocketState, nc, nc);
105 ssize_t ret;
106
107 do {
108 ret = sendto(s->fd, buf, size, 0,
109 (struct sockaddr *)&s->dgram_dst,
110 sizeof(s->dgram_dst));
111 } while (ret == -1 && errno == EINTR);
112
113 if (ret == -1 && errno == EAGAIN) {
114 net_socket_write_poll(s, true);
115 return 0;
116 }
117 return ret;
118 }
119
120 static void net_socket_send(void *opaque)
121 {
122 NetSocketState *s = opaque;
123 int size, err;
124 unsigned l;
125 uint8_t buf1[4096];
126 const uint8_t *buf;
127
128 size = qemu_recv(s->fd, buf1, sizeof(buf1), 0);
129 if (size < 0) {
130 err = socket_error();
131 if (err != EWOULDBLOCK)
132 goto eoc;
133 } else if (size == 0) {
134 /* end of connection */
135 eoc:
136 net_socket_read_poll(s, false);
137 net_socket_write_poll(s, false);
138 if (s->listen_fd != -1) {
139 qemu_set_fd_handler(s->listen_fd, net_socket_accept, NULL, s);
140 }
141 closesocket(s->fd);
142
143 s->fd = -1;
144 s->state = 0;
145 s->index = 0;
146 s->packet_len = 0;
147 s->nc.link_down = true;
148 memset(s->buf, 0, sizeof(s->buf));
149 memset(s->nc.info_str, 0, sizeof(s->nc.info_str));
150
151 return;
152 }
153 buf = buf1;
154 while (size > 0) {
155 /* reassemble a packet from the network */
156 switch(s->state) {
157 case 0:
158 l = 4 - s->index;
159 if (l > size)
160 l = size;
161 memcpy(s->buf + s->index, buf, l);
162 buf += l;
163 size -= l;
164 s->index += l;
165 if (s->index == 4) {
166 /* got length */
167 s->packet_len = ntohl(*(uint32_t *)s->buf);
168 s->index = 0;
169 s->state = 1;
170 }
171 break;
172 case 1:
173 l = s->packet_len - s->index;
174 if (l > size)
175 l = size;
176 if (s->index + l <= sizeof(s->buf)) {
177 memcpy(s->buf + s->index, buf, l);
178 } else {
179 fprintf(stderr, "serious error: oversized packet received,"
180 "connection terminated.\n");
181 s->state = 0;
182 goto eoc;
183 }
184
185 s->index += l;
186 buf += l;
187 size -= l;
188 if (s->index >= s->packet_len) {
189 qemu_send_packet(&s->nc, s->buf, s->packet_len);
190 s->index = 0;
191 s->state = 0;
192 }
193 break;
194 }
195 }
196 }
197
198 static void net_socket_send_dgram(void *opaque)
199 {
200 NetSocketState *s = opaque;
201 int size;
202
203 size = qemu_recv(s->fd, s->buf, sizeof(s->buf), 0);
204 if (size < 0)
205 return;
206 if (size == 0) {
207 /* end of connection */
208 net_socket_read_poll(s, false);
209 net_socket_write_poll(s, false);
210 return;
211 }
212 qemu_send_packet(&s->nc, s->buf, size);
213 }
214
215 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr, struct in_addr *localaddr)
216 {
217 struct ip_mreq imr;
218 int fd;
219 int val, ret;
220 #ifdef __OpenBSD__
221 unsigned char loop;
222 #else
223 int loop;
224 #endif
225
226 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
227 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) "
228 "does not contain a multicast address\n",
229 inet_ntoa(mcastaddr->sin_addr),
230 (int)ntohl(mcastaddr->sin_addr.s_addr));
231 return -1;
232
233 }
234 fd = qemu_socket(PF_INET, SOCK_DGRAM, 0);
235 if (fd < 0) {
236 perror("socket(PF_INET, SOCK_DGRAM)");
237 return -1;
238 }
239
240 val = 1;
241 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
242 (const char *)&val, sizeof(val));
243 if (ret < 0) {
244 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
245 goto fail;
246 }
247
248 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
249 if (ret < 0) {
250 perror("bind");
251 goto fail;
252 }
253
254 /* Add host to multicast group */
255 imr.imr_multiaddr = mcastaddr->sin_addr;
256 if (localaddr) {
257 imr.imr_interface = *localaddr;
258 } else {
259 imr.imr_interface.s_addr = htonl(INADDR_ANY);
260 }
261
262 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
263 (const char *)&imr, sizeof(struct ip_mreq));
264 if (ret < 0) {
265 perror("setsockopt(IP_ADD_MEMBERSHIP)");
266 goto fail;
267 }
268
269 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
270 loop = 1;
271 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
272 (const char *)&loop, sizeof(loop));
273 if (ret < 0) {
274 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
275 goto fail;
276 }
277
278 /* If a bind address is given, only send packets from that address */
279 if (localaddr != NULL) {
280 ret = setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF,
281 (const char *)localaddr, sizeof(*localaddr));
282 if (ret < 0) {
283 perror("setsockopt(IP_MULTICAST_IF)");
284 goto fail;
285 }
286 }
287
288 socket_set_nonblock(fd);
289 return fd;
290 fail:
291 if (fd >= 0)
292 closesocket(fd);
293 return -1;
294 }
295
296 static void net_socket_cleanup(NetClientState *nc)
297 {
298 NetSocketState *s = DO_UPCAST(NetSocketState, nc, nc);
299 if (s->fd != -1) {
300 net_socket_read_poll(s, false);
301 net_socket_write_poll(s, false);
302 close(s->fd);
303 s->fd = -1;
304 }
305 if (s->listen_fd != -1) {
306 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
307 closesocket(s->listen_fd);
308 s->listen_fd = -1;
309 }
310 }
311
312 static NetClientInfo net_dgram_socket_info = {
313 .type = NET_CLIENT_OPTIONS_KIND_SOCKET,
314 .size = sizeof(NetSocketState),
315 .receive = net_socket_receive_dgram,
316 .cleanup = net_socket_cleanup,
317 };
318
319 static NetSocketState *net_socket_fd_init_dgram(NetClientState *peer,
320 const char *model,
321 const char *name,
322 int fd, int is_connected)
323 {
324 struct sockaddr_in saddr;
325 int newfd;
326 socklen_t saddr_len;
327 NetClientState *nc;
328 NetSocketState *s;
329
330 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
331 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
332 * by ONLY ONE process: we must "clone" this dgram socket --jjo
333 */
334
335 if (is_connected) {
336 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
337 /* must be bound */
338 if (saddr.sin_addr.s_addr == 0) {
339 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, "
340 "cannot setup multicast dst addr\n", fd);
341 goto err;
342 }
343 /* clone dgram socket */
344 newfd = net_socket_mcast_create(&saddr, NULL);
345 if (newfd < 0) {
346 /* error already reported by net_socket_mcast_create() */
347 goto err;
348 }
349 /* clone newfd to fd, close newfd */
350 dup2(newfd, fd);
351 close(newfd);
352
353 } else {
354 fprintf(stderr,
355 "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
356 fd, strerror(errno));
357 goto err;
358 }
359 }
360
361 nc = qemu_new_net_client(&net_dgram_socket_info, peer, model, name);
362
363 snprintf(nc->info_str, sizeof(nc->info_str),
364 "socket: fd=%d (%s mcast=%s:%d)",
365 fd, is_connected ? "cloned" : "",
366 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
367
368 s = DO_UPCAST(NetSocketState, nc, nc);
369
370 s->fd = fd;
371 s->listen_fd = -1;
372 s->send_fn = net_socket_send_dgram;
373 net_socket_read_poll(s, true);
374
375 /* mcast: save bound address as dst */
376 if (is_connected) {
377 s->dgram_dst = saddr;
378 }
379
380 return s;
381
382 err:
383 closesocket(fd);
384 return NULL;
385 }
386
387 static void net_socket_connect(void *opaque)
388 {
389 NetSocketState *s = opaque;
390 s->send_fn = net_socket_send;
391 net_socket_read_poll(s, true);
392 }
393
394 static NetClientInfo net_socket_info = {
395 .type = NET_CLIENT_OPTIONS_KIND_SOCKET,
396 .size = sizeof(NetSocketState),
397 .receive = net_socket_receive,
398 .cleanup = net_socket_cleanup,
399 };
400
401 static NetSocketState *net_socket_fd_init_stream(NetClientState *peer,
402 const char *model,
403 const char *name,
404 int fd, int is_connected)
405 {
406 NetClientState *nc;
407 NetSocketState *s;
408
409 nc = qemu_new_net_client(&net_socket_info, peer, model, name);
410
411 snprintf(nc->info_str, sizeof(nc->info_str), "socket: fd=%d", fd);
412
413 s = DO_UPCAST(NetSocketState, nc, nc);
414
415 s->fd = fd;
416 s->listen_fd = -1;
417
418 if (is_connected) {
419 net_socket_connect(s);
420 } else {
421 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
422 }
423 return s;
424 }
425
426 static NetSocketState *net_socket_fd_init(NetClientState *peer,
427 const char *model, const char *name,
428 int fd, int is_connected)
429 {
430 int so_type = -1, optlen=sizeof(so_type);
431
432 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
433 (socklen_t *)&optlen)< 0) {
434 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n",
435 fd);
436 closesocket(fd);
437 return NULL;
438 }
439 switch(so_type) {
440 case SOCK_DGRAM:
441 return net_socket_fd_init_dgram(peer, model, name, fd, is_connected);
442 case SOCK_STREAM:
443 return net_socket_fd_init_stream(peer, model, name, fd, is_connected);
444 default:
445 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
446 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
447 return net_socket_fd_init_stream(peer, model, name, fd, is_connected);
448 }
449 return NULL;
450 }
451
452 static void net_socket_accept(void *opaque)
453 {
454 NetSocketState *s = opaque;
455 struct sockaddr_in saddr;
456 socklen_t len;
457 int fd;
458
459 for(;;) {
460 len = sizeof(saddr);
461 fd = qemu_accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
462 if (fd < 0 && errno != EINTR) {
463 return;
464 } else if (fd >= 0) {
465 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
466 break;
467 }
468 }
469
470 s->fd = fd;
471 s->nc.link_down = false;
472 net_socket_connect(s);
473 snprintf(s->nc.info_str, sizeof(s->nc.info_str),
474 "socket: connection from %s:%d",
475 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
476 }
477
478 static int net_socket_listen_init(NetClientState *peer,
479 const char *model,
480 const char *name,
481 const char *host_str)
482 {
483 NetClientState *nc;
484 NetSocketState *s;
485 struct sockaddr_in saddr;
486 int fd, val, ret;
487
488 if (parse_host_port(&saddr, host_str) < 0)
489 return -1;
490
491 fd = qemu_socket(PF_INET, SOCK_STREAM, 0);
492 if (fd < 0) {
493 perror("socket");
494 return -1;
495 }
496 socket_set_nonblock(fd);
497
498 /* allow fast reuse */
499 val = 1;
500 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
501
502 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
503 if (ret < 0) {
504 perror("bind");
505 closesocket(fd);
506 return -1;
507 }
508 ret = listen(fd, 0);
509 if (ret < 0) {
510 perror("listen");
511 closesocket(fd);
512 return -1;
513 }
514
515 nc = qemu_new_net_client(&net_socket_info, peer, model, name);
516 s = DO_UPCAST(NetSocketState, nc, nc);
517 s->fd = -1;
518 s->listen_fd = fd;
519 s->nc.link_down = true;
520
521 qemu_set_fd_handler(s->listen_fd, net_socket_accept, NULL, s);
522 return 0;
523 }
524
525 static int net_socket_connect_init(NetClientState *peer,
526 const char *model,
527 const char *name,
528 const char *host_str)
529 {
530 NetSocketState *s;
531 int fd, connected, ret, err;
532 struct sockaddr_in saddr;
533
534 if (parse_host_port(&saddr, host_str) < 0)
535 return -1;
536
537 fd = qemu_socket(PF_INET, SOCK_STREAM, 0);
538 if (fd < 0) {
539 perror("socket");
540 return -1;
541 }
542 socket_set_nonblock(fd);
543
544 connected = 0;
545 for(;;) {
546 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
547 if (ret < 0) {
548 err = socket_error();
549 if (err == EINTR || err == EWOULDBLOCK) {
550 } else if (err == EINPROGRESS) {
551 break;
552 #ifdef _WIN32
553 } else if (err == WSAEALREADY || err == WSAEINVAL) {
554 break;
555 #endif
556 } else {
557 perror("connect");
558 closesocket(fd);
559 return -1;
560 }
561 } else {
562 connected = 1;
563 break;
564 }
565 }
566 s = net_socket_fd_init(peer, model, name, fd, connected);
567 if (!s)
568 return -1;
569 snprintf(s->nc.info_str, sizeof(s->nc.info_str),
570 "socket: connect to %s:%d",
571 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
572 return 0;
573 }
574
575 static int net_socket_mcast_init(NetClientState *peer,
576 const char *model,
577 const char *name,
578 const char *host_str,
579 const char *localaddr_str)
580 {
581 NetSocketState *s;
582 int fd;
583 struct sockaddr_in saddr;
584 struct in_addr localaddr, *param_localaddr;
585
586 if (parse_host_port(&saddr, host_str) < 0)
587 return -1;
588
589 if (localaddr_str != NULL) {
590 if (inet_aton(localaddr_str, &localaddr) == 0)
591 return -1;
592 param_localaddr = &localaddr;
593 } else {
594 param_localaddr = NULL;
595 }
596
597 fd = net_socket_mcast_create(&saddr, param_localaddr);
598 if (fd < 0)
599 return -1;
600
601 s = net_socket_fd_init(peer, model, name, fd, 0);
602 if (!s)
603 return -1;
604
605 s->dgram_dst = saddr;
606
607 snprintf(s->nc.info_str, sizeof(s->nc.info_str),
608 "socket: mcast=%s:%d",
609 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
610 return 0;
611
612 }
613
614 static int net_socket_udp_init(NetClientState *peer,
615 const char *model,
616 const char *name,
617 const char *rhost,
618 const char *lhost)
619 {
620 NetSocketState *s;
621 int fd, val, ret;
622 struct sockaddr_in laddr, raddr;
623
624 if (parse_host_port(&laddr, lhost) < 0) {
625 return -1;
626 }
627
628 if (parse_host_port(&raddr, rhost) < 0) {
629 return -1;
630 }
631
632 fd = qemu_socket(PF_INET, SOCK_DGRAM, 0);
633 if (fd < 0) {
634 perror("socket(PF_INET, SOCK_DGRAM)");
635 return -1;
636 }
637 val = 1;
638 ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
639 (const char *)&val, sizeof(val));
640 if (ret < 0) {
641 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
642 closesocket(fd);
643 return -1;
644 }
645 ret = bind(fd, (struct sockaddr *)&laddr, sizeof(laddr));
646 if (ret < 0) {
647 perror("bind");
648 closesocket(fd);
649 return -1;
650 }
651
652 s = net_socket_fd_init(peer, model, name, fd, 0);
653 if (!s) {
654 return -1;
655 }
656
657 s->dgram_dst = raddr;
658
659 snprintf(s->nc.info_str, sizeof(s->nc.info_str),
660 "socket: udp=%s:%d",
661 inet_ntoa(raddr.sin_addr), ntohs(raddr.sin_port));
662 return 0;
663 }
664
665 int net_init_socket(const NetClientOptions *opts, const char *name,
666 NetClientState *peer)
667 {
668 const NetdevSocketOptions *sock;
669
670 assert(opts->kind == NET_CLIENT_OPTIONS_KIND_SOCKET);
671 sock = opts->socket;
672
673 if (sock->has_fd + sock->has_listen + sock->has_connect + sock->has_mcast +
674 sock->has_udp != 1) {
675 error_report("exactly one of fd=, listen=, connect=, mcast= or udp="
676 " is required");
677 return -1;
678 }
679
680 if (sock->has_localaddr && !sock->has_mcast && !sock->has_udp) {
681 error_report("localaddr= is only valid with mcast= or udp=");
682 return -1;
683 }
684
685 if (sock->has_fd) {
686 int fd;
687
688 fd = monitor_handle_fd_param(cur_mon, sock->fd);
689 if (fd == -1 || !net_socket_fd_init(peer, "socket", name, fd, 1)) {
690 return -1;
691 }
692 return 0;
693 }
694
695 if (sock->has_listen) {
696 if (net_socket_listen_init(peer, "socket", name, sock->listen) == -1) {
697 return -1;
698 }
699 return 0;
700 }
701
702 if (sock->has_connect) {
703 if (net_socket_connect_init(peer, "socket", name, sock->connect) ==
704 -1) {
705 return -1;
706 }
707 return 0;
708 }
709
710 if (sock->has_mcast) {
711 /* if sock->localaddr is missing, it has been initialized to "all bits
712 * zero" */
713 if (net_socket_mcast_init(peer, "socket", name, sock->mcast,
714 sock->localaddr) == -1) {
715 return -1;
716 }
717 return 0;
718 }
719
720 assert(sock->has_udp);
721 if (!sock->has_localaddr) {
722 error_report("localaddr= is mandatory with udp=");
723 return -1;
724 }
725 if (net_socket_udp_init(peer, "udp", name, sock->udp, sock->localaddr) ==
726 -1) {
727 return -1;
728 }
729 return 0;
730 }