]> git.proxmox.com Git - qemu.git/blob - net.c
Add support for GNU/kFreeBSD
[qemu.git] / net.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 <unistd.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
31
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
34
35 #ifndef _WIN32
36 #include <sys/times.h>
37 #include <sys/wait.h>
38 #include <termios.h>
39 #include <sys/mman.h>
40 #include <sys/ioctl.h>
41 #include <sys/resource.h>
42 #include <sys/socket.h>
43 #include <netinet/in.h>
44 #include <net/if.h>
45 #include <arpa/inet.h>
46 #include <dirent.h>
47 #include <netdb.h>
48 #include <sys/select.h>
49 #ifdef CONFIG_BSD
50 #include <sys/stat.h>
51 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
52 #include <libutil.h>
53 #else
54 #include <util.h>
55 #endif
56 #ifdef __linux__
57 #include <pty.h>
58 #include <malloc.h>
59 #include <linux/rtc.h>
60
61 /* For the benefit of older linux systems which don't supply it,
62 we use a local copy of hpet.h. */
63 /* #include <linux/hpet.h> */
64 #include "hpet.h"
65
66 #include <linux/ppdev.h>
67 #include <linux/parport.h>
68 #endif
69 #ifdef __sun__
70 #include <sys/stat.h>
71 #include <sys/ethernet.h>
72 #include <sys/sockio.h>
73 #include <netinet/arp.h>
74 #include <netinet/in.h>
75 #include <netinet/in_systm.h>
76 #include <netinet/ip.h>
77 #include <netinet/ip_icmp.h> // must come after ip.h
78 #include <netinet/udp.h>
79 #include <netinet/tcp.h>
80 #include <net/if.h>
81 #include <syslog.h>
82 #include <stropts.h>
83 #endif
84 #endif
85 #endif
86
87 #if defined(__OpenBSD__)
88 #include <util.h>
89 #endif
90
91 #if defined(CONFIG_VDE)
92 #include <libvdeplug.h>
93 #endif
94
95 #include "qemu-common.h"
96 #include "net.h"
97 #include "net/tap.h"
98 #include "monitor.h"
99 #include "sysemu.h"
100 #include "qemu-timer.h"
101 #include "qemu-char.h"
102 #include "audio/audio.h"
103 #include "qemu_socket.h"
104 #include "qemu-log.h"
105 #include "qemu-config.h"
106
107 #include "slirp/libslirp.h"
108
109 static QTAILQ_HEAD(, VLANState) vlans;
110 static QTAILQ_HEAD(, VLANClientState) non_vlan_clients;
111
112 /***********************************************************/
113 /* network device redirectors */
114
115 #if defined(DEBUG_NET) || defined(DEBUG_SLIRP)
116 static void hex_dump(FILE *f, const uint8_t *buf, int size)
117 {
118 int len, i, j, c;
119
120 for(i=0;i<size;i+=16) {
121 len = size - i;
122 if (len > 16)
123 len = 16;
124 fprintf(f, "%08x ", i);
125 for(j=0;j<16;j++) {
126 if (j < len)
127 fprintf(f, " %02x", buf[i+j]);
128 else
129 fprintf(f, " ");
130 }
131 fprintf(f, " ");
132 for(j=0;j<len;j++) {
133 c = buf[i+j];
134 if (c < ' ' || c > '~')
135 c = '.';
136 fprintf(f, "%c", c);
137 }
138 fprintf(f, "\n");
139 }
140 }
141 #endif
142
143 static int parse_macaddr(uint8_t *macaddr, const char *p)
144 {
145 int i;
146 char *last_char;
147 long int offset;
148
149 errno = 0;
150 offset = strtol(p, &last_char, 0);
151 if (0 == errno && '\0' == *last_char &&
152 offset >= 0 && offset <= 0xFFFFFF) {
153 macaddr[3] = (offset & 0xFF0000) >> 16;
154 macaddr[4] = (offset & 0xFF00) >> 8;
155 macaddr[5] = offset & 0xFF;
156 return 0;
157 } else {
158 for(i = 0; i < 6; i++) {
159 macaddr[i] = strtol(p, (char **)&p, 16);
160 if (i == 5) {
161 if (*p != '\0')
162 return -1;
163 } else {
164 if (*p != ':' && *p != '-')
165 return -1;
166 p++;
167 }
168 }
169 return 0;
170 }
171
172 return -1;
173 }
174
175 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
176 {
177 const char *p, *p1;
178 int len;
179 p = *pp;
180 p1 = strchr(p, sep);
181 if (!p1)
182 return -1;
183 len = p1 - p;
184 p1++;
185 if (buf_size > 0) {
186 if (len > buf_size - 1)
187 len = buf_size - 1;
188 memcpy(buf, p, len);
189 buf[len] = '\0';
190 }
191 *pp = p1;
192 return 0;
193 }
194
195 int parse_host_src_port(struct sockaddr_in *haddr,
196 struct sockaddr_in *saddr,
197 const char *input_str)
198 {
199 char *str = strdup(input_str);
200 char *host_str = str;
201 char *src_str;
202 const char *src_str2;
203 char *ptr;
204
205 /*
206 * Chop off any extra arguments at the end of the string which
207 * would start with a comma, then fill in the src port information
208 * if it was provided else use the "any address" and "any port".
209 */
210 if ((ptr = strchr(str,',')))
211 *ptr = '\0';
212
213 if ((src_str = strchr(input_str,'@'))) {
214 *src_str = '\0';
215 src_str++;
216 }
217
218 if (parse_host_port(haddr, host_str) < 0)
219 goto fail;
220
221 src_str2 = src_str;
222 if (!src_str || *src_str == '\0')
223 src_str2 = ":0";
224
225 if (parse_host_port(saddr, src_str2) < 0)
226 goto fail;
227
228 free(str);
229 return(0);
230
231 fail:
232 free(str);
233 return -1;
234 }
235
236 int parse_host_port(struct sockaddr_in *saddr, const char *str)
237 {
238 char buf[512];
239 struct hostent *he;
240 const char *p, *r;
241 int port;
242
243 p = str;
244 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
245 return -1;
246 saddr->sin_family = AF_INET;
247 if (buf[0] == '\0') {
248 saddr->sin_addr.s_addr = 0;
249 } else {
250 if (qemu_isdigit(buf[0])) {
251 if (!inet_aton(buf, &saddr->sin_addr))
252 return -1;
253 } else {
254 if ((he = gethostbyname(buf)) == NULL)
255 return - 1;
256 saddr->sin_addr = *(struct in_addr *)he->h_addr;
257 }
258 }
259 port = strtol(p, (char **)&r, 0);
260 if (r == p)
261 return -1;
262 saddr->sin_port = htons(port);
263 return 0;
264 }
265
266 void qemu_format_nic_info_str(VLANClientState *vc, uint8_t macaddr[6])
267 {
268 snprintf(vc->info_str, sizeof(vc->info_str),
269 "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
270 vc->model,
271 macaddr[0], macaddr[1], macaddr[2],
272 macaddr[3], macaddr[4], macaddr[5]);
273 }
274
275 void qemu_macaddr_default_if_unset(MACAddr *macaddr)
276 {
277 static int index = 0;
278 static const MACAddr zero = { .a = { 0,0,0,0,0,0 } };
279
280 if (memcmp(macaddr, &zero, sizeof(zero)) != 0)
281 return;
282 macaddr->a[0] = 0x52;
283 macaddr->a[1] = 0x54;
284 macaddr->a[2] = 0x00;
285 macaddr->a[3] = 0x12;
286 macaddr->a[4] = 0x34;
287 macaddr->a[5] = 0x56 + index++;
288 }
289
290 static char *assign_name(VLANClientState *vc1, const char *model)
291 {
292 VLANState *vlan;
293 char buf[256];
294 int id = 0;
295
296 QTAILQ_FOREACH(vlan, &vlans, next) {
297 VLANClientState *vc;
298
299 QTAILQ_FOREACH(vc, &vlan->clients, next) {
300 if (vc != vc1 && strcmp(vc->model, model) == 0) {
301 id++;
302 }
303 }
304 }
305
306 snprintf(buf, sizeof(buf), "%s.%d", model, id);
307
308 return qemu_strdup(buf);
309 }
310
311 static ssize_t qemu_deliver_packet(VLANClientState *sender,
312 unsigned flags,
313 const uint8_t *data,
314 size_t size,
315 void *opaque);
316 static ssize_t qemu_deliver_packet_iov(VLANClientState *sender,
317 unsigned flags,
318 const struct iovec *iov,
319 int iovcnt,
320 void *opaque);
321
322 VLANClientState *qemu_new_vlan_client(net_client_type type,
323 VLANState *vlan,
324 VLANClientState *peer,
325 const char *model,
326 const char *name,
327 NetCanReceive *can_receive,
328 NetReceive *receive,
329 NetReceive *receive_raw,
330 NetReceiveIOV *receive_iov,
331 NetCleanup *cleanup,
332 void *opaque)
333 {
334 VLANClientState *vc;
335
336 vc = qemu_mallocz(sizeof(VLANClientState));
337
338 vc->type = type;
339 vc->model = qemu_strdup(model);
340 if (name)
341 vc->name = qemu_strdup(name);
342 else
343 vc->name = assign_name(vc, model);
344 vc->can_receive = can_receive;
345 vc->receive = receive;
346 vc->receive_raw = receive_raw;
347 vc->receive_iov = receive_iov;
348 vc->cleanup = cleanup;
349 vc->opaque = opaque;
350
351 if (vlan) {
352 assert(!peer);
353 vc->vlan = vlan;
354 QTAILQ_INSERT_TAIL(&vc->vlan->clients, vc, next);
355 } else {
356 if (peer) {
357 vc->peer = peer;
358 peer->peer = vc;
359 }
360 QTAILQ_INSERT_TAIL(&non_vlan_clients, vc, next);
361
362 vc->send_queue = qemu_new_net_queue(qemu_deliver_packet,
363 qemu_deliver_packet_iov,
364 vc);
365 }
366
367 return vc;
368 }
369
370 void qemu_del_vlan_client(VLANClientState *vc)
371 {
372 if (vc->vlan) {
373 QTAILQ_REMOVE(&vc->vlan->clients, vc, next);
374 } else {
375 if (vc->send_queue) {
376 qemu_del_net_queue(vc->send_queue);
377 }
378 QTAILQ_REMOVE(&non_vlan_clients, vc, next);
379 if (vc->peer) {
380 vc->peer->peer = NULL;
381 }
382 }
383
384 if (vc->cleanup) {
385 vc->cleanup(vc);
386 }
387
388 qemu_free(vc->name);
389 qemu_free(vc->model);
390 qemu_free(vc);
391 }
392
393 VLANClientState *qemu_find_vlan_client(VLANState *vlan, void *opaque)
394 {
395 VLANClientState *vc;
396
397 QTAILQ_FOREACH(vc, &vlan->clients, next) {
398 if (vc->opaque == opaque) {
399 return vc;
400 }
401 }
402
403 return NULL;
404 }
405
406 static VLANClientState *
407 qemu_find_vlan_client_by_name(Monitor *mon, int vlan_id,
408 const char *client_str)
409 {
410 VLANState *vlan;
411 VLANClientState *vc;
412
413 vlan = qemu_find_vlan(vlan_id, 0);
414 if (!vlan) {
415 monitor_printf(mon, "unknown VLAN %d\n", vlan_id);
416 return NULL;
417 }
418
419 QTAILQ_FOREACH(vc, &vlan->clients, next) {
420 if (!strcmp(vc->name, client_str)) {
421 break;
422 }
423 }
424 if (!vc) {
425 monitor_printf(mon, "can't find device %s on VLAN %d\n",
426 client_str, vlan_id);
427 }
428
429 return vc;
430 }
431
432 int qemu_can_send_packet(VLANClientState *sender)
433 {
434 VLANState *vlan = sender->vlan;
435 VLANClientState *vc;
436
437 if (sender->peer) {
438 if (sender->peer->receive_disabled) {
439 return 0;
440 } else if (sender->peer->can_receive &&
441 !sender->peer->can_receive(sender->peer)) {
442 return 0;
443 } else {
444 return 1;
445 }
446 }
447
448 if (!sender->vlan) {
449 return 1;
450 }
451
452 QTAILQ_FOREACH(vc, &vlan->clients, next) {
453 if (vc == sender) {
454 continue;
455 }
456
457 /* no can_receive() handler, they can always receive */
458 if (!vc->can_receive || vc->can_receive(vc)) {
459 return 1;
460 }
461 }
462 return 0;
463 }
464
465 static ssize_t qemu_deliver_packet(VLANClientState *sender,
466 unsigned flags,
467 const uint8_t *data,
468 size_t size,
469 void *opaque)
470 {
471 VLANClientState *vc = opaque;
472 ssize_t ret;
473
474 if (vc->link_down) {
475 return size;
476 }
477
478 if (vc->receive_disabled) {
479 return 0;
480 }
481
482 if (flags & QEMU_NET_PACKET_FLAG_RAW && vc->receive_raw) {
483 ret = vc->receive_raw(vc, data, size);
484 } else {
485 ret = vc->receive(vc, data, size);
486 }
487
488 if (ret == 0) {
489 vc->receive_disabled = 1;
490 };
491
492 return ret;
493 }
494
495 static ssize_t qemu_vlan_deliver_packet(VLANClientState *sender,
496 unsigned flags,
497 const uint8_t *buf,
498 size_t size,
499 void *opaque)
500 {
501 VLANState *vlan = opaque;
502 VLANClientState *vc;
503 ssize_t ret = -1;
504
505 QTAILQ_FOREACH(vc, &vlan->clients, next) {
506 ssize_t len;
507
508 if (vc == sender) {
509 continue;
510 }
511
512 if (vc->link_down) {
513 ret = size;
514 continue;
515 }
516
517 if (vc->receive_disabled) {
518 ret = 0;
519 continue;
520 }
521
522 if (flags & QEMU_NET_PACKET_FLAG_RAW && vc->receive_raw) {
523 len = vc->receive_raw(vc, buf, size);
524 } else {
525 len = vc->receive(vc, buf, size);
526 }
527
528 if (len == 0) {
529 vc->receive_disabled = 1;
530 }
531
532 ret = (ret >= 0) ? ret : len;
533
534 }
535
536 return ret;
537 }
538
539 void qemu_purge_queued_packets(VLANClientState *vc)
540 {
541 NetQueue *queue;
542
543 if (!vc->peer && !vc->vlan) {
544 return;
545 }
546
547 if (vc->peer) {
548 queue = vc->peer->send_queue;
549 } else {
550 queue = vc->vlan->send_queue;
551 }
552
553 qemu_net_queue_purge(queue, vc);
554 }
555
556 void qemu_flush_queued_packets(VLANClientState *vc)
557 {
558 NetQueue *queue;
559
560 vc->receive_disabled = 0;
561
562 if (vc->vlan) {
563 queue = vc->vlan->send_queue;
564 } else {
565 queue = vc->send_queue;
566 }
567
568 qemu_net_queue_flush(queue);
569 }
570
571 static ssize_t qemu_send_packet_async_with_flags(VLANClientState *sender,
572 unsigned flags,
573 const uint8_t *buf, int size,
574 NetPacketSent *sent_cb)
575 {
576 NetQueue *queue;
577
578 #ifdef DEBUG_NET
579 printf("qemu_send_packet_async:\n");
580 hex_dump(stdout, buf, size);
581 #endif
582
583 if (sender->link_down || (!sender->peer && !sender->vlan)) {
584 return size;
585 }
586
587 if (sender->peer) {
588 queue = sender->peer->send_queue;
589 } else {
590 queue = sender->vlan->send_queue;
591 }
592
593 return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
594 }
595
596 ssize_t qemu_send_packet_async(VLANClientState *sender,
597 const uint8_t *buf, int size,
598 NetPacketSent *sent_cb)
599 {
600 return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
601 buf, size, sent_cb);
602 }
603
604 void qemu_send_packet(VLANClientState *vc, const uint8_t *buf, int size)
605 {
606 qemu_send_packet_async(vc, buf, size, NULL);
607 }
608
609 ssize_t qemu_send_packet_raw(VLANClientState *vc, const uint8_t *buf, int size)
610 {
611 return qemu_send_packet_async_with_flags(vc, QEMU_NET_PACKET_FLAG_RAW,
612 buf, size, NULL);
613 }
614
615 static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
616 int iovcnt)
617 {
618 uint8_t buffer[4096];
619 size_t offset = 0;
620 int i;
621
622 for (i = 0; i < iovcnt; i++) {
623 size_t len;
624
625 len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
626 memcpy(buffer + offset, iov[i].iov_base, len);
627 offset += len;
628 }
629
630 return vc->receive(vc, buffer, offset);
631 }
632
633 static ssize_t calc_iov_length(const struct iovec *iov, int iovcnt)
634 {
635 size_t offset = 0;
636 int i;
637
638 for (i = 0; i < iovcnt; i++)
639 offset += iov[i].iov_len;
640 return offset;
641 }
642
643 static ssize_t qemu_deliver_packet_iov(VLANClientState *sender,
644 unsigned flags,
645 const struct iovec *iov,
646 int iovcnt,
647 void *opaque)
648 {
649 VLANClientState *vc = opaque;
650
651 if (vc->link_down) {
652 return calc_iov_length(iov, iovcnt);
653 }
654
655 if (vc->receive_iov) {
656 return vc->receive_iov(vc, iov, iovcnt);
657 } else {
658 return vc_sendv_compat(vc, iov, iovcnt);
659 }
660 }
661
662 static ssize_t qemu_vlan_deliver_packet_iov(VLANClientState *sender,
663 unsigned flags,
664 const struct iovec *iov,
665 int iovcnt,
666 void *opaque)
667 {
668 VLANState *vlan = opaque;
669 VLANClientState *vc;
670 ssize_t ret = -1;
671
672 QTAILQ_FOREACH(vc, &vlan->clients, next) {
673 ssize_t len;
674
675 if (vc == sender) {
676 continue;
677 }
678
679 if (vc->link_down) {
680 ret = calc_iov_length(iov, iovcnt);
681 continue;
682 }
683
684 assert(!(flags & QEMU_NET_PACKET_FLAG_RAW));
685
686 if (vc->receive_iov) {
687 len = vc->receive_iov(vc, iov, iovcnt);
688 } else {
689 len = vc_sendv_compat(vc, iov, iovcnt);
690 }
691
692 ret = (ret >= 0) ? ret : len;
693 }
694
695 return ret;
696 }
697
698 ssize_t qemu_sendv_packet_async(VLANClientState *sender,
699 const struct iovec *iov, int iovcnt,
700 NetPacketSent *sent_cb)
701 {
702 NetQueue *queue;
703
704 if (sender->link_down || (!sender->peer && !sender->vlan)) {
705 return calc_iov_length(iov, iovcnt);
706 }
707
708 if (sender->peer) {
709 queue = sender->peer->send_queue;
710 } else {
711 queue = sender->vlan->send_queue;
712 }
713
714 return qemu_net_queue_send_iov(queue, sender,
715 QEMU_NET_PACKET_FLAG_NONE,
716 iov, iovcnt, sent_cb);
717 }
718
719 ssize_t
720 qemu_sendv_packet(VLANClientState *vc, const struct iovec *iov, int iovcnt)
721 {
722 return qemu_sendv_packet_async(vc, iov, iovcnt, NULL);
723 }
724
725 #if defined(CONFIG_SLIRP)
726
727 /* slirp network adapter */
728
729 #define SLIRP_CFG_HOSTFWD 1
730 #define SLIRP_CFG_LEGACY 2
731
732 struct slirp_config_str {
733 struct slirp_config_str *next;
734 int flags;
735 char str[1024];
736 int legacy_format;
737 };
738
739 typedef struct SlirpState {
740 QTAILQ_ENTRY(SlirpState) entry;
741 VLANClientState *vc;
742 Slirp *slirp;
743 #ifndef _WIN32
744 char smb_dir[128];
745 #endif
746 } SlirpState;
747
748 static struct slirp_config_str *slirp_configs;
749 const char *legacy_tftp_prefix;
750 const char *legacy_bootp_filename;
751 static QTAILQ_HEAD(slirp_stacks, SlirpState) slirp_stacks =
752 QTAILQ_HEAD_INITIALIZER(slirp_stacks);
753
754 static int slirp_hostfwd(SlirpState *s, const char *redir_str,
755 int legacy_format);
756 static int slirp_guestfwd(SlirpState *s, const char *config_str,
757 int legacy_format);
758
759 #ifndef _WIN32
760 static const char *legacy_smb_export;
761
762 static int slirp_smb(SlirpState *s, const char *exported_dir,
763 struct in_addr vserver_addr);
764 static void slirp_smb_cleanup(SlirpState *s);
765 #else
766 static inline void slirp_smb_cleanup(SlirpState *s) { }
767 #endif
768
769 int slirp_can_output(void *opaque)
770 {
771 SlirpState *s = opaque;
772
773 return qemu_can_send_packet(s->vc);
774 }
775
776 void slirp_output(void *opaque, const uint8_t *pkt, int pkt_len)
777 {
778 SlirpState *s = opaque;
779
780 #ifdef DEBUG_SLIRP
781 printf("slirp output:\n");
782 hex_dump(stdout, pkt, pkt_len);
783 #endif
784 qemu_send_packet(s->vc, pkt, pkt_len);
785 }
786
787 static ssize_t slirp_receive(VLANClientState *vc, const uint8_t *buf, size_t size)
788 {
789 SlirpState *s = vc->opaque;
790
791 #ifdef DEBUG_SLIRP
792 printf("slirp input:\n");
793 hex_dump(stdout, buf, size);
794 #endif
795 slirp_input(s->slirp, buf, size);
796 return size;
797 }
798
799 static void net_slirp_cleanup(VLANClientState *vc)
800 {
801 SlirpState *s = vc->opaque;
802
803 slirp_cleanup(s->slirp);
804 slirp_smb_cleanup(s);
805 QTAILQ_REMOVE(&slirp_stacks, s, entry);
806 qemu_free(s);
807 }
808
809 static int net_slirp_init(VLANState *vlan, const char *model,
810 const char *name, int restricted,
811 const char *vnetwork, const char *vhost,
812 const char *vhostname, const char *tftp_export,
813 const char *bootfile, const char *vdhcp_start,
814 const char *vnameserver, const char *smb_export,
815 const char *vsmbserver)
816 {
817 /* default settings according to historic slirp */
818 struct in_addr net = { .s_addr = htonl(0x0a000200) }; /* 10.0.2.0 */
819 struct in_addr mask = { .s_addr = htonl(0xffffff00) }; /* 255.255.255.0 */
820 struct in_addr host = { .s_addr = htonl(0x0a000202) }; /* 10.0.2.2 */
821 struct in_addr dhcp = { .s_addr = htonl(0x0a00020f) }; /* 10.0.2.15 */
822 struct in_addr dns = { .s_addr = htonl(0x0a000203) }; /* 10.0.2.3 */
823 #ifndef _WIN32
824 struct in_addr smbsrv = { .s_addr = 0 };
825 #endif
826 SlirpState *s;
827 char buf[20];
828 uint32_t addr;
829 int shift;
830 char *end;
831 struct slirp_config_str *config;
832
833 if (!tftp_export) {
834 tftp_export = legacy_tftp_prefix;
835 }
836 if (!bootfile) {
837 bootfile = legacy_bootp_filename;
838 }
839
840 if (vnetwork) {
841 if (get_str_sep(buf, sizeof(buf), &vnetwork, '/') < 0) {
842 if (!inet_aton(vnetwork, &net)) {
843 return -1;
844 }
845 addr = ntohl(net.s_addr);
846 if (!(addr & 0x80000000)) {
847 mask.s_addr = htonl(0xff000000); /* class A */
848 } else if ((addr & 0xfff00000) == 0xac100000) {
849 mask.s_addr = htonl(0xfff00000); /* priv. 172.16.0.0/12 */
850 } else if ((addr & 0xc0000000) == 0x80000000) {
851 mask.s_addr = htonl(0xffff0000); /* class B */
852 } else if ((addr & 0xffff0000) == 0xc0a80000) {
853 mask.s_addr = htonl(0xffff0000); /* priv. 192.168.0.0/16 */
854 } else if ((addr & 0xffff0000) == 0xc6120000) {
855 mask.s_addr = htonl(0xfffe0000); /* tests 198.18.0.0/15 */
856 } else if ((addr & 0xe0000000) == 0xe0000000) {
857 mask.s_addr = htonl(0xffffff00); /* class C */
858 } else {
859 mask.s_addr = htonl(0xfffffff0); /* multicast/reserved */
860 }
861 } else {
862 if (!inet_aton(buf, &net)) {
863 return -1;
864 }
865 shift = strtol(vnetwork, &end, 10);
866 if (*end != '\0') {
867 if (!inet_aton(vnetwork, &mask)) {
868 return -1;
869 }
870 } else if (shift < 4 || shift > 32) {
871 return -1;
872 } else {
873 mask.s_addr = htonl(0xffffffff << (32 - shift));
874 }
875 }
876 net.s_addr &= mask.s_addr;
877 host.s_addr = net.s_addr | (htonl(0x0202) & ~mask.s_addr);
878 dhcp.s_addr = net.s_addr | (htonl(0x020f) & ~mask.s_addr);
879 dns.s_addr = net.s_addr | (htonl(0x0203) & ~mask.s_addr);
880 }
881
882 if (vhost && !inet_aton(vhost, &host)) {
883 return -1;
884 }
885 if ((host.s_addr & mask.s_addr) != net.s_addr) {
886 return -1;
887 }
888
889 if (vdhcp_start && !inet_aton(vdhcp_start, &dhcp)) {
890 return -1;
891 }
892 if ((dhcp.s_addr & mask.s_addr) != net.s_addr ||
893 dhcp.s_addr == host.s_addr || dhcp.s_addr == dns.s_addr) {
894 return -1;
895 }
896
897 if (vnameserver && !inet_aton(vnameserver, &dns)) {
898 return -1;
899 }
900 if ((dns.s_addr & mask.s_addr) != net.s_addr ||
901 dns.s_addr == host.s_addr) {
902 return -1;
903 }
904
905 #ifndef _WIN32
906 if (vsmbserver && !inet_aton(vsmbserver, &smbsrv)) {
907 return -1;
908 }
909 #endif
910
911 s = qemu_mallocz(sizeof(SlirpState));
912 s->slirp = slirp_init(restricted, net, mask, host, vhostname,
913 tftp_export, bootfile, dhcp, dns, s);
914 QTAILQ_INSERT_TAIL(&slirp_stacks, s, entry);
915
916 for (config = slirp_configs; config; config = config->next) {
917 if (config->flags & SLIRP_CFG_HOSTFWD) {
918 if (slirp_hostfwd(s, config->str,
919 config->flags & SLIRP_CFG_LEGACY) < 0)
920 return -1;
921 } else {
922 if (slirp_guestfwd(s, config->str,
923 config->flags & SLIRP_CFG_LEGACY) < 0)
924 return -1;
925 }
926 }
927 #ifndef _WIN32
928 if (!smb_export) {
929 smb_export = legacy_smb_export;
930 }
931 if (smb_export) {
932 if (slirp_smb(s, smb_export, smbsrv) < 0)
933 return -1;
934 }
935 #endif
936
937 s->vc = qemu_new_vlan_client(NET_CLIENT_TYPE_SLIRP,
938 vlan, NULL, model, name, NULL,
939 slirp_receive, NULL, NULL,
940 net_slirp_cleanup, s);
941 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
942 "net=%s, restricted=%c", inet_ntoa(net), restricted ? 'y' : 'n');
943 return 0;
944 }
945
946 static SlirpState *slirp_lookup(Monitor *mon, const char *vlan,
947 const char *stack)
948 {
949 VLANClientState *vc;
950
951 if (vlan) {
952 vc = qemu_find_vlan_client_by_name(mon, strtol(vlan, NULL, 0), stack);
953 if (!vc) {
954 return NULL;
955 }
956 if (strcmp(vc->model, "user")) {
957 monitor_printf(mon, "invalid device specified\n");
958 return NULL;
959 }
960 return vc->opaque;
961 } else {
962 if (QTAILQ_EMPTY(&slirp_stacks)) {
963 monitor_printf(mon, "user mode network stack not in use\n");
964 return NULL;
965 }
966 return QTAILQ_FIRST(&slirp_stacks);
967 }
968 }
969
970 void net_slirp_hostfwd_remove(Monitor *mon, const QDict *qdict)
971 {
972 struct in_addr host_addr = { .s_addr = INADDR_ANY };
973 int host_port;
974 char buf[256] = "";
975 const char *src_str, *p;
976 SlirpState *s;
977 int is_udp = 0;
978 int err;
979 const char *arg1 = qdict_get_str(qdict, "arg1");
980 const char *arg2 = qdict_get_try_str(qdict, "arg2");
981 const char *arg3 = qdict_get_try_str(qdict, "arg3");
982
983 if (arg2) {
984 s = slirp_lookup(mon, arg1, arg2);
985 src_str = arg3;
986 } else {
987 s = slirp_lookup(mon, NULL, NULL);
988 src_str = arg1;
989 }
990 if (!s) {
991 return;
992 }
993
994 if (!src_str || !src_str[0])
995 goto fail_syntax;
996
997 p = src_str;
998 get_str_sep(buf, sizeof(buf), &p, ':');
999
1000 if (!strcmp(buf, "tcp") || buf[0] == '\0') {
1001 is_udp = 0;
1002 } else if (!strcmp(buf, "udp")) {
1003 is_udp = 1;
1004 } else {
1005 goto fail_syntax;
1006 }
1007
1008 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1009 goto fail_syntax;
1010 }
1011 if (buf[0] != '\0' && !inet_aton(buf, &host_addr)) {
1012 goto fail_syntax;
1013 }
1014
1015 host_port = atoi(p);
1016
1017 err = slirp_remove_hostfwd(QTAILQ_FIRST(&slirp_stacks)->slirp, is_udp,
1018 host_addr, host_port);
1019
1020 monitor_printf(mon, "host forwarding rule for %s %s\n", src_str,
1021 err ? "removed" : "not found");
1022 return;
1023
1024 fail_syntax:
1025 monitor_printf(mon, "invalid format\n");
1026 }
1027
1028 static int slirp_hostfwd(SlirpState *s, const char *redir_str,
1029 int legacy_format)
1030 {
1031 struct in_addr host_addr = { .s_addr = INADDR_ANY };
1032 struct in_addr guest_addr = { .s_addr = 0 };
1033 int host_port, guest_port;
1034 const char *p;
1035 char buf[256];
1036 int is_udp;
1037 char *end;
1038
1039 p = redir_str;
1040 if (!p || get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1041 goto fail_syntax;
1042 }
1043 if (!strcmp(buf, "tcp") || buf[0] == '\0') {
1044 is_udp = 0;
1045 } else if (!strcmp(buf, "udp")) {
1046 is_udp = 1;
1047 } else {
1048 goto fail_syntax;
1049 }
1050
1051 if (!legacy_format) {
1052 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1053 goto fail_syntax;
1054 }
1055 if (buf[0] != '\0' && !inet_aton(buf, &host_addr)) {
1056 goto fail_syntax;
1057 }
1058 }
1059
1060 if (get_str_sep(buf, sizeof(buf), &p, legacy_format ? ':' : '-') < 0) {
1061 goto fail_syntax;
1062 }
1063 host_port = strtol(buf, &end, 0);
1064 if (*end != '\0' || host_port < 1 || host_port > 65535) {
1065 goto fail_syntax;
1066 }
1067
1068 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1069 goto fail_syntax;
1070 }
1071 if (buf[0] != '\0' && !inet_aton(buf, &guest_addr)) {
1072 goto fail_syntax;
1073 }
1074
1075 guest_port = strtol(p, &end, 0);
1076 if (*end != '\0' || guest_port < 1 || guest_port > 65535) {
1077 goto fail_syntax;
1078 }
1079
1080 if (slirp_add_hostfwd(s->slirp, is_udp, host_addr, host_port, guest_addr,
1081 guest_port) < 0) {
1082 qemu_error("could not set up host forwarding rule '%s'\n",
1083 redir_str);
1084 return -1;
1085 }
1086 return 0;
1087
1088 fail_syntax:
1089 qemu_error("invalid host forwarding rule '%s'\n", redir_str);
1090 return -1;
1091 }
1092
1093 void net_slirp_hostfwd_add(Monitor *mon, const QDict *qdict)
1094 {
1095 const char *redir_str;
1096 SlirpState *s;
1097 const char *arg1 = qdict_get_str(qdict, "arg1");
1098 const char *arg2 = qdict_get_try_str(qdict, "arg2");
1099 const char *arg3 = qdict_get_try_str(qdict, "arg3");
1100
1101 if (arg2) {
1102 s = slirp_lookup(mon, arg1, arg2);
1103 redir_str = arg3;
1104 } else {
1105 s = slirp_lookup(mon, NULL, NULL);
1106 redir_str = arg1;
1107 }
1108 if (s) {
1109 slirp_hostfwd(s, redir_str, 0);
1110 }
1111
1112 }
1113
1114 int net_slirp_redir(const char *redir_str)
1115 {
1116 struct slirp_config_str *config;
1117
1118 if (QTAILQ_EMPTY(&slirp_stacks)) {
1119 config = qemu_malloc(sizeof(*config));
1120 pstrcpy(config->str, sizeof(config->str), redir_str);
1121 config->flags = SLIRP_CFG_HOSTFWD | SLIRP_CFG_LEGACY;
1122 config->next = slirp_configs;
1123 slirp_configs = config;
1124 return 0;
1125 }
1126
1127 return slirp_hostfwd(QTAILQ_FIRST(&slirp_stacks), redir_str, 1);
1128 }
1129
1130 #ifndef _WIN32
1131
1132 /* automatic user mode samba server configuration */
1133 static void slirp_smb_cleanup(SlirpState *s)
1134 {
1135 char cmd[128];
1136
1137 if (s->smb_dir[0] != '\0') {
1138 snprintf(cmd, sizeof(cmd), "rm -rf %s", s->smb_dir);
1139 system(cmd);
1140 s->smb_dir[0] = '\0';
1141 }
1142 }
1143
1144 static int slirp_smb(SlirpState* s, const char *exported_dir,
1145 struct in_addr vserver_addr)
1146 {
1147 static int instance;
1148 char smb_conf[128];
1149 char smb_cmdline[128];
1150 FILE *f;
1151
1152 snprintf(s->smb_dir, sizeof(s->smb_dir), "/tmp/qemu-smb.%ld-%d",
1153 (long)getpid(), instance++);
1154 if (mkdir(s->smb_dir, 0700) < 0) {
1155 qemu_error("could not create samba server dir '%s'\n", s->smb_dir);
1156 return -1;
1157 }
1158 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", s->smb_dir, "smb.conf");
1159
1160 f = fopen(smb_conf, "w");
1161 if (!f) {
1162 slirp_smb_cleanup(s);
1163 qemu_error("could not create samba server configuration file '%s'\n",
1164 smb_conf);
1165 return -1;
1166 }
1167 fprintf(f,
1168 "[global]\n"
1169 "private dir=%s\n"
1170 "smb ports=0\n"
1171 "socket address=127.0.0.1\n"
1172 "pid directory=%s\n"
1173 "lock directory=%s\n"
1174 "log file=%s/log.smbd\n"
1175 "smb passwd file=%s/smbpasswd\n"
1176 "security = share\n"
1177 "[qemu]\n"
1178 "path=%s\n"
1179 "read only=no\n"
1180 "guest ok=yes\n",
1181 s->smb_dir,
1182 s->smb_dir,
1183 s->smb_dir,
1184 s->smb_dir,
1185 s->smb_dir,
1186 exported_dir
1187 );
1188 fclose(f);
1189
1190 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
1191 SMBD_COMMAND, smb_conf);
1192
1193 if (slirp_add_exec(s->slirp, 0, smb_cmdline, &vserver_addr, 139) < 0) {
1194 slirp_smb_cleanup(s);
1195 qemu_error("conflicting/invalid smbserver address\n");
1196 return -1;
1197 }
1198 return 0;
1199 }
1200
1201 /* automatic user mode samba server configuration (legacy interface) */
1202 int net_slirp_smb(const char *exported_dir)
1203 {
1204 struct in_addr vserver_addr = { .s_addr = 0 };
1205
1206 if (legacy_smb_export) {
1207 fprintf(stderr, "-smb given twice\n");
1208 return -1;
1209 }
1210 legacy_smb_export = exported_dir;
1211 if (!QTAILQ_EMPTY(&slirp_stacks)) {
1212 return slirp_smb(QTAILQ_FIRST(&slirp_stacks), exported_dir,
1213 vserver_addr);
1214 }
1215 return 0;
1216 }
1217
1218 #endif /* !defined(_WIN32) */
1219
1220 struct GuestFwd {
1221 CharDriverState *hd;
1222 struct in_addr server;
1223 int port;
1224 Slirp *slirp;
1225 };
1226
1227 static int guestfwd_can_read(void *opaque)
1228 {
1229 struct GuestFwd *fwd = opaque;
1230 return slirp_socket_can_recv(fwd->slirp, fwd->server, fwd->port);
1231 }
1232
1233 static void guestfwd_read(void *opaque, const uint8_t *buf, int size)
1234 {
1235 struct GuestFwd *fwd = opaque;
1236 slirp_socket_recv(fwd->slirp, fwd->server, fwd->port, buf, size);
1237 }
1238
1239 static int slirp_guestfwd(SlirpState *s, const char *config_str,
1240 int legacy_format)
1241 {
1242 struct in_addr server = { .s_addr = 0 };
1243 struct GuestFwd *fwd;
1244 const char *p;
1245 char buf[128];
1246 char *end;
1247 int port;
1248
1249 p = config_str;
1250 if (legacy_format) {
1251 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1252 goto fail_syntax;
1253 }
1254 } else {
1255 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1256 goto fail_syntax;
1257 }
1258 if (strcmp(buf, "tcp") && buf[0] != '\0') {
1259 goto fail_syntax;
1260 }
1261 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1262 goto fail_syntax;
1263 }
1264 if (buf[0] != '\0' && !inet_aton(buf, &server)) {
1265 goto fail_syntax;
1266 }
1267 if (get_str_sep(buf, sizeof(buf), &p, '-') < 0) {
1268 goto fail_syntax;
1269 }
1270 }
1271 port = strtol(buf, &end, 10);
1272 if (*end != '\0' || port < 1 || port > 65535) {
1273 goto fail_syntax;
1274 }
1275
1276 fwd = qemu_malloc(sizeof(struct GuestFwd));
1277 snprintf(buf, sizeof(buf), "guestfwd.tcp:%d", port);
1278 fwd->hd = qemu_chr_open(buf, p, NULL);
1279 if (!fwd->hd) {
1280 qemu_error("could not open guest forwarding device '%s'\n", buf);
1281 qemu_free(fwd);
1282 return -1;
1283 }
1284
1285 if (slirp_add_exec(s->slirp, 3, fwd->hd, &server, port) < 0) {
1286 qemu_error("conflicting/invalid host:port in guest forwarding "
1287 "rule '%s'\n", config_str);
1288 qemu_free(fwd);
1289 return -1;
1290 }
1291 fwd->server = server;
1292 fwd->port = port;
1293 fwd->slirp = s->slirp;
1294
1295 qemu_chr_add_handlers(fwd->hd, guestfwd_can_read, guestfwd_read,
1296 NULL, fwd);
1297 return 0;
1298
1299 fail_syntax:
1300 qemu_error("invalid guest forwarding rule '%s'\n", config_str);
1301 return -1;
1302 }
1303
1304 void do_info_usernet(Monitor *mon)
1305 {
1306 SlirpState *s;
1307
1308 QTAILQ_FOREACH(s, &slirp_stacks, entry) {
1309 monitor_printf(mon, "VLAN %d (%s):\n", s->vc->vlan->id, s->vc->name);
1310 slirp_connection_info(s->slirp, mon);
1311 }
1312 }
1313
1314 #endif /* CONFIG_SLIRP */
1315
1316 #if defined(CONFIG_VDE)
1317 typedef struct VDEState {
1318 VLANClientState *vc;
1319 VDECONN *vde;
1320 } VDEState;
1321
1322 static void vde_to_qemu(void *opaque)
1323 {
1324 VDEState *s = opaque;
1325 uint8_t buf[4096];
1326 int size;
1327
1328 size = vde_recv(s->vde, (char *)buf, sizeof(buf), 0);
1329 if (size > 0) {
1330 qemu_send_packet(s->vc, buf, size);
1331 }
1332 }
1333
1334 static ssize_t vde_receive(VLANClientState *vc, const uint8_t *buf, size_t size)
1335 {
1336 VDEState *s = vc->opaque;
1337 ssize_t ret;
1338
1339 do {
1340 ret = vde_send(s->vde, (const char *)buf, size, 0);
1341 } while (ret < 0 && errno == EINTR);
1342
1343 return ret;
1344 }
1345
1346 static void vde_cleanup(VLANClientState *vc)
1347 {
1348 VDEState *s = vc->opaque;
1349 qemu_set_fd_handler(vde_datafd(s->vde), NULL, NULL, NULL);
1350 vde_close(s->vde);
1351 qemu_free(s);
1352 }
1353
1354 static int net_vde_init(VLANState *vlan, const char *model,
1355 const char *name, const char *sock,
1356 int port, const char *group, int mode)
1357 {
1358 VDEState *s;
1359 char *init_group = (char *)group;
1360 char *init_sock = (char *)sock;
1361
1362 struct vde_open_args args = {
1363 .port = port,
1364 .group = init_group,
1365 .mode = mode,
1366 };
1367
1368 s = qemu_mallocz(sizeof(VDEState));
1369 s->vde = vde_open(init_sock, (char *)"QEMU", &args);
1370 if (!s->vde){
1371 free(s);
1372 return -1;
1373 }
1374 s->vc = qemu_new_vlan_client(NET_CLIENT_TYPE_VDE,
1375 vlan, NULL, model, name, NULL,
1376 vde_receive, NULL, NULL,
1377 vde_cleanup, s);
1378 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
1379 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "sock=%s,fd=%d",
1380 sock, vde_datafd(s->vde));
1381 return 0;
1382 }
1383 #endif
1384
1385 /* network connection */
1386 typedef struct NetSocketState {
1387 VLANClientState *vc;
1388 int fd;
1389 int state; /* 0 = getting length, 1 = getting data */
1390 unsigned int index;
1391 unsigned int packet_len;
1392 uint8_t buf[4096];
1393 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
1394 } NetSocketState;
1395
1396 typedef struct NetSocketListenState {
1397 VLANState *vlan;
1398 char *model;
1399 char *name;
1400 int fd;
1401 } NetSocketListenState;
1402
1403 /* XXX: we consider we can send the whole packet without blocking */
1404 static ssize_t net_socket_receive(VLANClientState *vc, const uint8_t *buf, size_t size)
1405 {
1406 NetSocketState *s = vc->opaque;
1407 uint32_t len;
1408 len = htonl(size);
1409
1410 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
1411 return send_all(s->fd, buf, size);
1412 }
1413
1414 static ssize_t net_socket_receive_dgram(VLANClientState *vc, const uint8_t *buf, size_t size)
1415 {
1416 NetSocketState *s = vc->opaque;
1417
1418 return sendto(s->fd, (const void *)buf, size, 0,
1419 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
1420 }
1421
1422 static void net_socket_send(void *opaque)
1423 {
1424 NetSocketState *s = opaque;
1425 int size, err;
1426 unsigned l;
1427 uint8_t buf1[4096];
1428 const uint8_t *buf;
1429
1430 size = recv(s->fd, (void *)buf1, sizeof(buf1), 0);
1431 if (size < 0) {
1432 err = socket_error();
1433 if (err != EWOULDBLOCK)
1434 goto eoc;
1435 } else if (size == 0) {
1436 /* end of connection */
1437 eoc:
1438 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1439 closesocket(s->fd);
1440 return;
1441 }
1442 buf = buf1;
1443 while (size > 0) {
1444 /* reassemble a packet from the network */
1445 switch(s->state) {
1446 case 0:
1447 l = 4 - s->index;
1448 if (l > size)
1449 l = size;
1450 memcpy(s->buf + s->index, buf, l);
1451 buf += l;
1452 size -= l;
1453 s->index += l;
1454 if (s->index == 4) {
1455 /* got length */
1456 s->packet_len = ntohl(*(uint32_t *)s->buf);
1457 s->index = 0;
1458 s->state = 1;
1459 }
1460 break;
1461 case 1:
1462 l = s->packet_len - s->index;
1463 if (l > size)
1464 l = size;
1465 if (s->index + l <= sizeof(s->buf)) {
1466 memcpy(s->buf + s->index, buf, l);
1467 } else {
1468 fprintf(stderr, "serious error: oversized packet received,"
1469 "connection terminated.\n");
1470 s->state = 0;
1471 goto eoc;
1472 }
1473
1474 s->index += l;
1475 buf += l;
1476 size -= l;
1477 if (s->index >= s->packet_len) {
1478 qemu_send_packet(s->vc, s->buf, s->packet_len);
1479 s->index = 0;
1480 s->state = 0;
1481 }
1482 break;
1483 }
1484 }
1485 }
1486
1487 static void net_socket_send_dgram(void *opaque)
1488 {
1489 NetSocketState *s = opaque;
1490 int size;
1491
1492 size = recv(s->fd, (void *)s->buf, sizeof(s->buf), 0);
1493 if (size < 0)
1494 return;
1495 if (size == 0) {
1496 /* end of connection */
1497 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1498 return;
1499 }
1500 qemu_send_packet(s->vc, s->buf, size);
1501 }
1502
1503 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
1504 {
1505 struct ip_mreq imr;
1506 int fd;
1507 int val, ret;
1508 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
1509 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
1510 inet_ntoa(mcastaddr->sin_addr),
1511 (int)ntohl(mcastaddr->sin_addr.s_addr));
1512 return -1;
1513
1514 }
1515 fd = socket(PF_INET, SOCK_DGRAM, 0);
1516 if (fd < 0) {
1517 perror("socket(PF_INET, SOCK_DGRAM)");
1518 return -1;
1519 }
1520
1521 val = 1;
1522 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1523 (const char *)&val, sizeof(val));
1524 if (ret < 0) {
1525 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
1526 goto fail;
1527 }
1528
1529 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
1530 if (ret < 0) {
1531 perror("bind");
1532 goto fail;
1533 }
1534
1535 /* Add host to multicast group */
1536 imr.imr_multiaddr = mcastaddr->sin_addr;
1537 imr.imr_interface.s_addr = htonl(INADDR_ANY);
1538
1539 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1540 (const char *)&imr, sizeof(struct ip_mreq));
1541 if (ret < 0) {
1542 perror("setsockopt(IP_ADD_MEMBERSHIP)");
1543 goto fail;
1544 }
1545
1546 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
1547 val = 1;
1548 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1549 (const char *)&val, sizeof(val));
1550 if (ret < 0) {
1551 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
1552 goto fail;
1553 }
1554
1555 socket_set_nonblock(fd);
1556 return fd;
1557 fail:
1558 if (fd >= 0)
1559 closesocket(fd);
1560 return -1;
1561 }
1562
1563 static void net_socket_cleanup(VLANClientState *vc)
1564 {
1565 NetSocketState *s = vc->opaque;
1566 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1567 close(s->fd);
1568 qemu_free(s);
1569 }
1570
1571 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan,
1572 const char *model,
1573 const char *name,
1574 int fd, int is_connected)
1575 {
1576 struct sockaddr_in saddr;
1577 int newfd;
1578 socklen_t saddr_len;
1579 NetSocketState *s;
1580
1581 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
1582 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
1583 * by ONLY ONE process: we must "clone" this dgram socket --jjo
1584 */
1585
1586 if (is_connected) {
1587 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
1588 /* must be bound */
1589 if (saddr.sin_addr.s_addr==0) {
1590 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
1591 fd);
1592 return NULL;
1593 }
1594 /* clone dgram socket */
1595 newfd = net_socket_mcast_create(&saddr);
1596 if (newfd < 0) {
1597 /* error already reported by net_socket_mcast_create() */
1598 close(fd);
1599 return NULL;
1600 }
1601 /* clone newfd to fd, close newfd */
1602 dup2(newfd, fd);
1603 close(newfd);
1604
1605 } else {
1606 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
1607 fd, strerror(errno));
1608 return NULL;
1609 }
1610 }
1611
1612 s = qemu_mallocz(sizeof(NetSocketState));
1613 s->fd = fd;
1614
1615 s->vc = qemu_new_vlan_client(NET_CLIENT_TYPE_SOCKET,
1616 vlan, NULL, model, name, NULL,
1617 net_socket_receive_dgram, NULL, NULL,
1618 net_socket_cleanup, s);
1619 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
1620
1621 /* mcast: save bound address as dst */
1622 if (is_connected) s->dgram_dst=saddr;
1623
1624 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1625 "socket: fd=%d (%s mcast=%s:%d)",
1626 fd, is_connected? "cloned" : "",
1627 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1628 return s;
1629 }
1630
1631 static void net_socket_connect(void *opaque)
1632 {
1633 NetSocketState *s = opaque;
1634 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
1635 }
1636
1637 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan,
1638 const char *model,
1639 const char *name,
1640 int fd, int is_connected)
1641 {
1642 NetSocketState *s;
1643 s = qemu_mallocz(sizeof(NetSocketState));
1644 s->fd = fd;
1645 s->vc = qemu_new_vlan_client(NET_CLIENT_TYPE_SOCKET,
1646 vlan, NULL, model, name, NULL,
1647 net_socket_receive, NULL, NULL,
1648 net_socket_cleanup, s);
1649 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1650 "socket: fd=%d", fd);
1651 if (is_connected) {
1652 net_socket_connect(s);
1653 } else {
1654 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
1655 }
1656 return s;
1657 }
1658
1659 static NetSocketState *net_socket_fd_init(VLANState *vlan,
1660 const char *model, const char *name,
1661 int fd, int is_connected)
1662 {
1663 int so_type = -1, optlen=sizeof(so_type);
1664
1665 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
1666 (socklen_t *)&optlen)< 0) {
1667 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
1668 return NULL;
1669 }
1670 switch(so_type) {
1671 case SOCK_DGRAM:
1672 return net_socket_fd_init_dgram(vlan, model, name, fd, is_connected);
1673 case SOCK_STREAM:
1674 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1675 default:
1676 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
1677 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
1678 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1679 }
1680 return NULL;
1681 }
1682
1683 static void net_socket_accept(void *opaque)
1684 {
1685 NetSocketListenState *s = opaque;
1686 NetSocketState *s1;
1687 struct sockaddr_in saddr;
1688 socklen_t len;
1689 int fd;
1690
1691 for(;;) {
1692 len = sizeof(saddr);
1693 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
1694 if (fd < 0 && errno != EINTR) {
1695 return;
1696 } else if (fd >= 0) {
1697 break;
1698 }
1699 }
1700 s1 = net_socket_fd_init(s->vlan, s->model, s->name, fd, 1);
1701 if (!s1) {
1702 closesocket(fd);
1703 } else {
1704 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
1705 "socket: connection from %s:%d",
1706 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1707 }
1708 }
1709
1710 static int net_socket_listen_init(VLANState *vlan,
1711 const char *model,
1712 const char *name,
1713 const char *host_str)
1714 {
1715 NetSocketListenState *s;
1716 int fd, val, ret;
1717 struct sockaddr_in saddr;
1718
1719 if (parse_host_port(&saddr, host_str) < 0)
1720 return -1;
1721
1722 s = qemu_mallocz(sizeof(NetSocketListenState));
1723
1724 fd = socket(PF_INET, SOCK_STREAM, 0);
1725 if (fd < 0) {
1726 perror("socket");
1727 return -1;
1728 }
1729 socket_set_nonblock(fd);
1730
1731 /* allow fast reuse */
1732 val = 1;
1733 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
1734
1735 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1736 if (ret < 0) {
1737 perror("bind");
1738 return -1;
1739 }
1740 ret = listen(fd, 0);
1741 if (ret < 0) {
1742 perror("listen");
1743 return -1;
1744 }
1745 s->vlan = vlan;
1746 s->model = qemu_strdup(model);
1747 s->name = name ? qemu_strdup(name) : NULL;
1748 s->fd = fd;
1749 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
1750 return 0;
1751 }
1752
1753 static int net_socket_connect_init(VLANState *vlan,
1754 const char *model,
1755 const char *name,
1756 const char *host_str)
1757 {
1758 NetSocketState *s;
1759 int fd, connected, ret, err;
1760 struct sockaddr_in saddr;
1761
1762 if (parse_host_port(&saddr, host_str) < 0)
1763 return -1;
1764
1765 fd = socket(PF_INET, SOCK_STREAM, 0);
1766 if (fd < 0) {
1767 perror("socket");
1768 return -1;
1769 }
1770 socket_set_nonblock(fd);
1771
1772 connected = 0;
1773 for(;;) {
1774 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1775 if (ret < 0) {
1776 err = socket_error();
1777 if (err == EINTR || err == EWOULDBLOCK) {
1778 } else if (err == EINPROGRESS) {
1779 break;
1780 #ifdef _WIN32
1781 } else if (err == WSAEALREADY) {
1782 break;
1783 #endif
1784 } else {
1785 perror("connect");
1786 closesocket(fd);
1787 return -1;
1788 }
1789 } else {
1790 connected = 1;
1791 break;
1792 }
1793 }
1794 s = net_socket_fd_init(vlan, model, name, fd, connected);
1795 if (!s)
1796 return -1;
1797 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1798 "socket: connect to %s:%d",
1799 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1800 return 0;
1801 }
1802
1803 static int net_socket_mcast_init(VLANState *vlan,
1804 const char *model,
1805 const char *name,
1806 const char *host_str)
1807 {
1808 NetSocketState *s;
1809 int fd;
1810 struct sockaddr_in saddr;
1811
1812 if (parse_host_port(&saddr, host_str) < 0)
1813 return -1;
1814
1815
1816 fd = net_socket_mcast_create(&saddr);
1817 if (fd < 0)
1818 return -1;
1819
1820 s = net_socket_fd_init(vlan, model, name, fd, 0);
1821 if (!s)
1822 return -1;
1823
1824 s->dgram_dst = saddr;
1825
1826 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1827 "socket: mcast=%s:%d",
1828 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1829 return 0;
1830
1831 }
1832
1833 typedef struct DumpState {
1834 VLANClientState *pcap_vc;
1835 int fd;
1836 int pcap_caplen;
1837 } DumpState;
1838
1839 #define PCAP_MAGIC 0xa1b2c3d4
1840
1841 struct pcap_file_hdr {
1842 uint32_t magic;
1843 uint16_t version_major;
1844 uint16_t version_minor;
1845 int32_t thiszone;
1846 uint32_t sigfigs;
1847 uint32_t snaplen;
1848 uint32_t linktype;
1849 };
1850
1851 struct pcap_sf_pkthdr {
1852 struct {
1853 int32_t tv_sec;
1854 int32_t tv_usec;
1855 } ts;
1856 uint32_t caplen;
1857 uint32_t len;
1858 };
1859
1860 static ssize_t dump_receive(VLANClientState *vc, const uint8_t *buf, size_t size)
1861 {
1862 DumpState *s = vc->opaque;
1863 struct pcap_sf_pkthdr hdr;
1864 int64_t ts;
1865 int caplen;
1866
1867 /* Early return in case of previous error. */
1868 if (s->fd < 0) {
1869 return size;
1870 }
1871
1872 ts = muldiv64(qemu_get_clock(vm_clock), 1000000, get_ticks_per_sec());
1873 caplen = size > s->pcap_caplen ? s->pcap_caplen : size;
1874
1875 hdr.ts.tv_sec = ts / 1000000;
1876 hdr.ts.tv_usec = ts % 1000000;
1877 hdr.caplen = caplen;
1878 hdr.len = size;
1879 if (write(s->fd, &hdr, sizeof(hdr)) != sizeof(hdr) ||
1880 write(s->fd, buf, caplen) != caplen) {
1881 qemu_log("-net dump write error - stop dump\n");
1882 close(s->fd);
1883 s->fd = -1;
1884 }
1885
1886 return size;
1887 }
1888
1889 static void net_dump_cleanup(VLANClientState *vc)
1890 {
1891 DumpState *s = vc->opaque;
1892
1893 close(s->fd);
1894 qemu_free(s);
1895 }
1896
1897 static int net_dump_init(VLANState *vlan, const char *device,
1898 const char *name, const char *filename, int len)
1899 {
1900 struct pcap_file_hdr hdr;
1901 DumpState *s;
1902
1903 s = qemu_malloc(sizeof(DumpState));
1904
1905 s->fd = open(filename, O_CREAT | O_WRONLY | O_BINARY, 0644);
1906 if (s->fd < 0) {
1907 qemu_error("-net dump: can't open %s\n", filename);
1908 return -1;
1909 }
1910
1911 s->pcap_caplen = len;
1912
1913 hdr.magic = PCAP_MAGIC;
1914 hdr.version_major = 2;
1915 hdr.version_minor = 4;
1916 hdr.thiszone = 0;
1917 hdr.sigfigs = 0;
1918 hdr.snaplen = s->pcap_caplen;
1919 hdr.linktype = 1;
1920
1921 if (write(s->fd, &hdr, sizeof(hdr)) < sizeof(hdr)) {
1922 qemu_error("-net dump write error: %s\n", strerror(errno));
1923 close(s->fd);
1924 qemu_free(s);
1925 return -1;
1926 }
1927
1928 s->pcap_vc = qemu_new_vlan_client(NET_CLIENT_TYPE_DUMP,
1929 vlan, NULL, device, name, NULL,
1930 dump_receive, NULL, NULL,
1931 net_dump_cleanup, s);
1932 snprintf(s->pcap_vc->info_str, sizeof(s->pcap_vc->info_str),
1933 "dump to %s (len=%d)", filename, len);
1934 return 0;
1935 }
1936
1937 /* find or alloc a new VLAN */
1938 VLANState *qemu_find_vlan(int id, int allocate)
1939 {
1940 VLANState *vlan;
1941
1942 QTAILQ_FOREACH(vlan, &vlans, next) {
1943 if (vlan->id == id) {
1944 return vlan;
1945 }
1946 }
1947
1948 if (!allocate) {
1949 return NULL;
1950 }
1951
1952 vlan = qemu_mallocz(sizeof(VLANState));
1953 vlan->id = id;
1954 QTAILQ_INIT(&vlan->clients);
1955
1956 vlan->send_queue = qemu_new_net_queue(qemu_vlan_deliver_packet,
1957 qemu_vlan_deliver_packet_iov,
1958 vlan);
1959
1960 QTAILQ_INSERT_TAIL(&vlans, vlan, next);
1961
1962 return vlan;
1963 }
1964
1965 VLANClientState *qemu_find_netdev(const char *id)
1966 {
1967 VLANClientState *vc;
1968
1969 QTAILQ_FOREACH(vc, &non_vlan_clients, next) {
1970 if (!strcmp(vc->name, id)) {
1971 return vc;
1972 }
1973 }
1974
1975 return NULL;
1976 }
1977
1978 static int nic_get_free_idx(void)
1979 {
1980 int index;
1981
1982 for (index = 0; index < MAX_NICS; index++)
1983 if (!nd_table[index].used)
1984 return index;
1985 return -1;
1986 }
1987
1988 int qemu_show_nic_models(const char *arg, const char *const *models)
1989 {
1990 int i;
1991
1992 if (!arg || strcmp(arg, "?"))
1993 return 0;
1994
1995 fprintf(stderr, "qemu: Supported NIC models: ");
1996 for (i = 0 ; models[i]; i++)
1997 fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
1998 return 1;
1999 }
2000
2001 void qemu_check_nic_model(NICInfo *nd, const char *model)
2002 {
2003 const char *models[2];
2004
2005 models[0] = model;
2006 models[1] = NULL;
2007
2008 if (qemu_show_nic_models(nd->model, models))
2009 exit(0);
2010 if (qemu_find_nic_model(nd, models, model) < 0)
2011 exit(1);
2012 }
2013
2014 int qemu_find_nic_model(NICInfo *nd, const char * const *models,
2015 const char *default_model)
2016 {
2017 int i;
2018
2019 if (!nd->model)
2020 nd->model = qemu_strdup(default_model);
2021
2022 for (i = 0 ; models[i]; i++) {
2023 if (strcmp(nd->model, models[i]) == 0)
2024 return i;
2025 }
2026
2027 qemu_error("qemu: Unsupported NIC model: %s\n", nd->model);
2028 return -1;
2029 }
2030
2031 int net_handle_fd_param(Monitor *mon, const char *param)
2032 {
2033 if (!qemu_isdigit(param[0])) {
2034 int fd;
2035
2036 fd = monitor_get_fd(mon, param);
2037 if (fd == -1) {
2038 qemu_error("No file descriptor named %s found", param);
2039 return -1;
2040 }
2041
2042 return fd;
2043 } else {
2044 return strtol(param, NULL, 0);
2045 }
2046 }
2047
2048 static int net_init_nic(QemuOpts *opts,
2049 Monitor *mon,
2050 const char *name,
2051 VLANState *vlan)
2052 {
2053 int idx;
2054 NICInfo *nd;
2055 const char *netdev;
2056
2057 idx = nic_get_free_idx();
2058 if (idx == -1 || nb_nics >= MAX_NICS) {
2059 qemu_error("Too Many NICs\n");
2060 return -1;
2061 }
2062
2063 nd = &nd_table[idx];
2064
2065 memset(nd, 0, sizeof(*nd));
2066
2067 if ((netdev = qemu_opt_get(opts, "netdev"))) {
2068 nd->netdev = qemu_find_netdev(netdev);
2069 if (!nd->netdev) {
2070 qemu_error("netdev '%s' not found\n", netdev);
2071 return -1;
2072 }
2073 } else {
2074 assert(vlan);
2075 nd->vlan = vlan;
2076 }
2077 if (name) {
2078 nd->name = qemu_strdup(name);
2079 }
2080 if (qemu_opt_get(opts, "model")) {
2081 nd->model = qemu_strdup(qemu_opt_get(opts, "model"));
2082 }
2083 if (qemu_opt_get(opts, "addr")) {
2084 nd->devaddr = qemu_strdup(qemu_opt_get(opts, "addr"));
2085 }
2086
2087 nd->macaddr[0] = 0x52;
2088 nd->macaddr[1] = 0x54;
2089 nd->macaddr[2] = 0x00;
2090 nd->macaddr[3] = 0x12;
2091 nd->macaddr[4] = 0x34;
2092 nd->macaddr[5] = 0x56 + idx;
2093
2094 if (qemu_opt_get(opts, "macaddr") &&
2095 parse_macaddr(nd->macaddr, qemu_opt_get(opts, "macaddr")) < 0) {
2096 qemu_error("invalid syntax for ethernet address\n");
2097 return -1;
2098 }
2099
2100 nd->nvectors = qemu_opt_get_number(opts, "vectors", NIC_NVECTORS_UNSPECIFIED);
2101 if (nd->nvectors != NIC_NVECTORS_UNSPECIFIED &&
2102 (nd->nvectors < 0 || nd->nvectors > 0x7ffffff)) {
2103 qemu_error("invalid # of vectors: %d\n", nd->nvectors);
2104 return -1;
2105 }
2106
2107 nd->used = 1;
2108 if (vlan) {
2109 nd->vlan->nb_guest_devs++;
2110 }
2111 nb_nics++;
2112
2113 return idx;
2114 }
2115
2116 #if defined(CONFIG_SLIRP)
2117 static int net_init_slirp_configs(const char *name, const char *value, void *opaque)
2118 {
2119 struct slirp_config_str *config;
2120
2121 if (strcmp(name, "hostfwd") != 0 && strcmp(name, "guestfwd") != 0) {
2122 return 0;
2123 }
2124
2125 config = qemu_mallocz(sizeof(*config));
2126
2127 pstrcpy(config->str, sizeof(config->str), value);
2128
2129 if (!strcmp(name, "hostfwd")) {
2130 config->flags = SLIRP_CFG_HOSTFWD;
2131 }
2132
2133 config->next = slirp_configs;
2134 slirp_configs = config;
2135
2136 return 0;
2137 }
2138
2139 static int net_init_slirp(QemuOpts *opts,
2140 Monitor *mon,
2141 const char *name,
2142 VLANState *vlan)
2143 {
2144 struct slirp_config_str *config;
2145 const char *vhost;
2146 const char *vhostname;
2147 const char *vdhcp_start;
2148 const char *vnamesrv;
2149 const char *tftp_export;
2150 const char *bootfile;
2151 const char *smb_export;
2152 const char *vsmbsrv;
2153 char *vnet = NULL;
2154 int restricted = 0;
2155 int ret;
2156
2157 vhost = qemu_opt_get(opts, "host");
2158 vhostname = qemu_opt_get(opts, "hostname");
2159 vdhcp_start = qemu_opt_get(opts, "dhcpstart");
2160 vnamesrv = qemu_opt_get(opts, "dns");
2161 tftp_export = qemu_opt_get(opts, "tftp");
2162 bootfile = qemu_opt_get(opts, "bootfile");
2163 smb_export = qemu_opt_get(opts, "smb");
2164 vsmbsrv = qemu_opt_get(opts, "smbserver");
2165
2166 if (qemu_opt_get(opts, "ip")) {
2167 const char *ip = qemu_opt_get(opts, "ip");
2168 int l = strlen(ip) + strlen("/24") + 1;
2169
2170 vnet = qemu_malloc(l);
2171
2172 /* emulate legacy ip= parameter */
2173 pstrcpy(vnet, l, ip);
2174 pstrcat(vnet, l, "/24");
2175 }
2176
2177 if (qemu_opt_get(opts, "net")) {
2178 if (vnet) {
2179 qemu_free(vnet);
2180 }
2181 vnet = qemu_strdup(qemu_opt_get(opts, "net"));
2182 }
2183
2184 if (qemu_opt_get(opts, "restrict") &&
2185 qemu_opt_get(opts, "restrict")[0] == 'y') {
2186 restricted = 1;
2187 }
2188
2189 qemu_opt_foreach(opts, net_init_slirp_configs, NULL, 0);
2190
2191 ret = net_slirp_init(vlan, "user", name, restricted, vnet, vhost,
2192 vhostname, tftp_export, bootfile, vdhcp_start,
2193 vnamesrv, smb_export, vsmbsrv);
2194
2195 while (slirp_configs) {
2196 config = slirp_configs;
2197 slirp_configs = config->next;
2198 qemu_free(config);
2199 }
2200
2201 if (ret != -1 && vlan) {
2202 vlan->nb_host_devs++;
2203 }
2204
2205 qemu_free(vnet);
2206
2207 return ret;
2208 }
2209 #endif /* CONFIG_SLIRP */
2210
2211 static int net_init_socket(QemuOpts *opts,
2212 Monitor *mon,
2213 const char *name,
2214 VLANState *vlan)
2215 {
2216 if (qemu_opt_get(opts, "fd")) {
2217 int fd;
2218
2219 if (qemu_opt_get(opts, "listen") ||
2220 qemu_opt_get(opts, "connect") ||
2221 qemu_opt_get(opts, "mcast")) {
2222 qemu_error("listen=, connect= and mcast= is invalid with fd=\n");
2223 return -1;
2224 }
2225
2226 fd = net_handle_fd_param(mon, qemu_opt_get(opts, "fd"));
2227 if (fd == -1) {
2228 return -1;
2229 }
2230
2231 if (!net_socket_fd_init(vlan, "socket", name, fd, 1)) {
2232 close(fd);
2233 return -1;
2234 }
2235 } else if (qemu_opt_get(opts, "listen")) {
2236 const char *listen;
2237
2238 if (qemu_opt_get(opts, "fd") ||
2239 qemu_opt_get(opts, "connect") ||
2240 qemu_opt_get(opts, "mcast")) {
2241 qemu_error("fd=, connect= and mcast= is invalid with listen=\n");
2242 return -1;
2243 }
2244
2245 listen = qemu_opt_get(opts, "listen");
2246
2247 if (net_socket_listen_init(vlan, "socket", name, listen) == -1) {
2248 return -1;
2249 }
2250 } else if (qemu_opt_get(opts, "connect")) {
2251 const char *connect;
2252
2253 if (qemu_opt_get(opts, "fd") ||
2254 qemu_opt_get(opts, "listen") ||
2255 qemu_opt_get(opts, "mcast")) {
2256 qemu_error("fd=, listen= and mcast= is invalid with connect=\n");
2257 return -1;
2258 }
2259
2260 connect = qemu_opt_get(opts, "connect");
2261
2262 if (net_socket_connect_init(vlan, "socket", name, connect) == -1) {
2263 return -1;
2264 }
2265 } else if (qemu_opt_get(opts, "mcast")) {
2266 const char *mcast;
2267
2268 if (qemu_opt_get(opts, "fd") ||
2269 qemu_opt_get(opts, "connect") ||
2270 qemu_opt_get(opts, "listen")) {
2271 qemu_error("fd=, connect= and listen= is invalid with mcast=\n");
2272 return -1;
2273 }
2274
2275 mcast = qemu_opt_get(opts, "mcast");
2276
2277 if (net_socket_mcast_init(vlan, "socket", name, mcast) == -1) {
2278 return -1;
2279 }
2280 } else {
2281 qemu_error("-socket requires fd=, listen=, connect= or mcast=\n");
2282 return -1;
2283 }
2284
2285 if (vlan) {
2286 vlan->nb_host_devs++;
2287 }
2288
2289 return 0;
2290 }
2291
2292 #ifdef CONFIG_VDE
2293 static int net_init_vde(QemuOpts *opts,
2294 Monitor *mon,
2295 const char *name,
2296 VLANState *vlan)
2297 {
2298 const char *sock;
2299 const char *group;
2300 int port, mode;
2301
2302 sock = qemu_opt_get(opts, "sock");
2303 group = qemu_opt_get(opts, "group");
2304
2305 port = qemu_opt_get_number(opts, "port", 0);
2306 mode = qemu_opt_get_number(opts, "mode", 0700);
2307
2308 if (net_vde_init(vlan, "vde", name, sock, port, group, mode) == -1) {
2309 return -1;
2310 }
2311
2312 if (vlan) {
2313 vlan->nb_host_devs++;
2314 }
2315
2316 return 0;
2317 }
2318 #endif
2319
2320 static int net_init_dump(QemuOpts *opts,
2321 Monitor *mon,
2322 const char *name,
2323 VLANState *vlan)
2324 {
2325 int len;
2326 const char *file;
2327 char def_file[128];
2328
2329 assert(vlan);
2330
2331 file = qemu_opt_get(opts, "file");
2332 if (!file) {
2333 snprintf(def_file, sizeof(def_file), "qemu-vlan%d.pcap", vlan->id);
2334 file = def_file;
2335 }
2336
2337 len = qemu_opt_get_size(opts, "len", 65536);
2338
2339 return net_dump_init(vlan, "dump", name, file, len);
2340 }
2341
2342 #define NET_COMMON_PARAMS_DESC \
2343 { \
2344 .name = "type", \
2345 .type = QEMU_OPT_STRING, \
2346 .help = "net client type (nic, tap etc.)", \
2347 }, { \
2348 .name = "vlan", \
2349 .type = QEMU_OPT_NUMBER, \
2350 .help = "vlan number", \
2351 }, { \
2352 .name = "name", \
2353 .type = QEMU_OPT_STRING, \
2354 .help = "identifier for monitor commands", \
2355 }
2356
2357 typedef int (*net_client_init_func)(QemuOpts *opts,
2358 Monitor *mon,
2359 const char *name,
2360 VLANState *vlan);
2361
2362 /* magic number, but compiler will warn if too small */
2363 #define NET_MAX_DESC 20
2364
2365 static struct {
2366 const char *type;
2367 net_client_init_func init;
2368 QemuOptDesc desc[NET_MAX_DESC];
2369 } net_client_types[] = {
2370 {
2371 .type = "none",
2372 .desc = {
2373 NET_COMMON_PARAMS_DESC,
2374 { /* end of list */ }
2375 },
2376 }, {
2377 .type = "nic",
2378 .init = net_init_nic,
2379 .desc = {
2380 NET_COMMON_PARAMS_DESC,
2381 {
2382 .name = "netdev",
2383 .type = QEMU_OPT_STRING,
2384 .help = "id of -netdev to connect to",
2385 },
2386 {
2387 .name = "macaddr",
2388 .type = QEMU_OPT_STRING,
2389 .help = "MAC address",
2390 }, {
2391 .name = "model",
2392 .type = QEMU_OPT_STRING,
2393 .help = "device model (e1000, rtl8139, virtio etc.)",
2394 }, {
2395 .name = "addr",
2396 .type = QEMU_OPT_STRING,
2397 .help = "PCI device address",
2398 }, {
2399 .name = "vectors",
2400 .type = QEMU_OPT_NUMBER,
2401 .help = "number of MSI-x vectors, 0 to disable MSI-X",
2402 },
2403 { /* end of list */ }
2404 },
2405 #ifdef CONFIG_SLIRP
2406 }, {
2407 .type = "user",
2408 .init = net_init_slirp,
2409 .desc = {
2410 NET_COMMON_PARAMS_DESC,
2411 {
2412 .name = "hostname",
2413 .type = QEMU_OPT_STRING,
2414 .help = "client hostname reported by the builtin DHCP server",
2415 }, {
2416 .name = "restrict",
2417 .type = QEMU_OPT_STRING,
2418 .help = "isolate the guest from the host (y|yes|n|no)",
2419 }, {
2420 .name = "ip",
2421 .type = QEMU_OPT_STRING,
2422 .help = "legacy parameter, use net= instead",
2423 }, {
2424 .name = "net",
2425 .type = QEMU_OPT_STRING,
2426 .help = "IP address and optional netmask",
2427 }, {
2428 .name = "host",
2429 .type = QEMU_OPT_STRING,
2430 .help = "guest-visible address of the host",
2431 }, {
2432 .name = "tftp",
2433 .type = QEMU_OPT_STRING,
2434 .help = "root directory of the built-in TFTP server",
2435 }, {
2436 .name = "bootfile",
2437 .type = QEMU_OPT_STRING,
2438 .help = "BOOTP filename, for use with tftp=",
2439 }, {
2440 .name = "dhcpstart",
2441 .type = QEMU_OPT_STRING,
2442 .help = "the first of the 16 IPs the built-in DHCP server can assign",
2443 }, {
2444 .name = "dns",
2445 .type = QEMU_OPT_STRING,
2446 .help = "guest-visible address of the virtual nameserver",
2447 }, {
2448 .name = "smb",
2449 .type = QEMU_OPT_STRING,
2450 .help = "root directory of the built-in SMB server",
2451 }, {
2452 .name = "smbserver",
2453 .type = QEMU_OPT_STRING,
2454 .help = "IP address of the built-in SMB server",
2455 }, {
2456 .name = "hostfwd",
2457 .type = QEMU_OPT_STRING,
2458 .help = "guest port number to forward incoming TCP or UDP connections",
2459 }, {
2460 .name = "guestfwd",
2461 .type = QEMU_OPT_STRING,
2462 .help = "IP address and port to forward guest TCP connections",
2463 },
2464 { /* end of list */ }
2465 },
2466 #endif
2467 }, {
2468 .type = "tap",
2469 .init = net_init_tap,
2470 .desc = {
2471 NET_COMMON_PARAMS_DESC,
2472 {
2473 .name = "ifname",
2474 .type = QEMU_OPT_STRING,
2475 .help = "interface name",
2476 },
2477 #ifndef _WIN32
2478 {
2479 .name = "fd",
2480 .type = QEMU_OPT_STRING,
2481 .help = "file descriptor of an already opened tap",
2482 }, {
2483 .name = "script",
2484 .type = QEMU_OPT_STRING,
2485 .help = "script to initialize the interface",
2486 }, {
2487 .name = "downscript",
2488 .type = QEMU_OPT_STRING,
2489 .help = "script to shut down the interface",
2490 }, {
2491 .name = "sndbuf",
2492 .type = QEMU_OPT_SIZE,
2493 .help = "send buffer limit"
2494 }, {
2495 .name = "vnet_hdr",
2496 .type = QEMU_OPT_BOOL,
2497 .help = "enable the IFF_VNET_HDR flag on the tap interface"
2498 },
2499 #endif /* _WIN32 */
2500 { /* end of list */ }
2501 },
2502 }, {
2503 .type = "socket",
2504 .init = net_init_socket,
2505 .desc = {
2506 NET_COMMON_PARAMS_DESC,
2507 {
2508 .name = "fd",
2509 .type = QEMU_OPT_STRING,
2510 .help = "file descriptor of an already opened socket",
2511 }, {
2512 .name = "listen",
2513 .type = QEMU_OPT_STRING,
2514 .help = "port number, and optional hostname, to listen on",
2515 }, {
2516 .name = "connect",
2517 .type = QEMU_OPT_STRING,
2518 .help = "port number, and optional hostname, to connect to",
2519 }, {
2520 .name = "mcast",
2521 .type = QEMU_OPT_STRING,
2522 .help = "UDP multicast address and port number",
2523 },
2524 { /* end of list */ }
2525 },
2526 #ifdef CONFIG_VDE
2527 }, {
2528 .type = "vde",
2529 .init = net_init_vde,
2530 .desc = {
2531 NET_COMMON_PARAMS_DESC,
2532 {
2533 .name = "sock",
2534 .type = QEMU_OPT_STRING,
2535 .help = "socket path",
2536 }, {
2537 .name = "port",
2538 .type = QEMU_OPT_NUMBER,
2539 .help = "port number",
2540 }, {
2541 .name = "group",
2542 .type = QEMU_OPT_STRING,
2543 .help = "group owner of socket",
2544 }, {
2545 .name = "mode",
2546 .type = QEMU_OPT_NUMBER,
2547 .help = "permissions for socket",
2548 },
2549 { /* end of list */ }
2550 },
2551 #endif
2552 }, {
2553 .type = "dump",
2554 .init = net_init_dump,
2555 .desc = {
2556 NET_COMMON_PARAMS_DESC,
2557 {
2558 .name = "len",
2559 .type = QEMU_OPT_SIZE,
2560 .help = "per-packet size limit (64k default)",
2561 }, {
2562 .name = "file",
2563 .type = QEMU_OPT_STRING,
2564 .help = "dump file path (default is qemu-vlan0.pcap)",
2565 },
2566 { /* end of list */ }
2567 },
2568 },
2569 { /* end of list */ }
2570 };
2571
2572 int net_client_init(Monitor *mon, QemuOpts *opts, int is_netdev)
2573 {
2574 const char *name;
2575 const char *type;
2576 int i;
2577
2578 type = qemu_opt_get(opts, "type");
2579 if (!type) {
2580 qemu_error("No type specified for -net\n");
2581 return -1;
2582 }
2583
2584 if (is_netdev) {
2585 if (strcmp(type, "tap") != 0 &&
2586 #ifdef CONFIG_SLIRP
2587 strcmp(type, "user") != 0 &&
2588 #endif
2589 #ifdef CONFIG_VDE
2590 strcmp(type, "vde") != 0 &&
2591 #endif
2592 strcmp(type, "socket") != 0) {
2593 qemu_error("The '%s' network backend type is not valid with -netdev\n",
2594 type);
2595 return -1;
2596 }
2597
2598 if (qemu_opt_get(opts, "vlan")) {
2599 qemu_error("The 'vlan' parameter is not valid with -netdev\n");
2600 return -1;
2601 }
2602 if (qemu_opt_get(opts, "name")) {
2603 qemu_error("The 'name' parameter is not valid with -netdev\n");
2604 return -1;
2605 }
2606 if (!qemu_opts_id(opts)) {
2607 qemu_error("The id= parameter is required with -netdev\n");
2608 return -1;
2609 }
2610 }
2611
2612 name = qemu_opts_id(opts);
2613 if (!name) {
2614 name = qemu_opt_get(opts, "name");
2615 }
2616
2617 for (i = 0; net_client_types[i].type != NULL; i++) {
2618 if (!strcmp(net_client_types[i].type, type)) {
2619 VLANState *vlan = NULL;
2620
2621 if (qemu_opts_validate(opts, &net_client_types[i].desc[0]) == -1) {
2622 return -1;
2623 }
2624
2625 /* Do not add to a vlan if it's a -netdev or a nic with a
2626 * netdev= parameter. */
2627 if (!(is_netdev ||
2628 (strcmp(type, "nic") == 0 && qemu_opt_get(opts, "netdev")))) {
2629 vlan = qemu_find_vlan(qemu_opt_get_number(opts, "vlan", 0), 1);
2630 }
2631
2632 if (net_client_types[i].init) {
2633 return net_client_types[i].init(opts, mon, name, vlan);
2634 } else {
2635 return 0;
2636 }
2637 }
2638 }
2639
2640 qemu_error("Invalid -net type '%s'\n", type);
2641 return -1;
2642 }
2643
2644 void net_client_uninit(NICInfo *nd)
2645 {
2646 if (nd->vlan) {
2647 nd->vlan->nb_guest_devs--;
2648 }
2649 nb_nics--;
2650
2651 qemu_free(nd->model);
2652 qemu_free(nd->name);
2653 qemu_free(nd->devaddr);
2654
2655 nd->used = 0;
2656 }
2657
2658 static int net_host_check_device(const char *device)
2659 {
2660 int i;
2661 const char *valid_param_list[] = { "tap", "socket", "dump"
2662 #ifdef CONFIG_SLIRP
2663 ,"user"
2664 #endif
2665 #ifdef CONFIG_VDE
2666 ,"vde"
2667 #endif
2668 };
2669 for (i = 0; i < sizeof(valid_param_list) / sizeof(char *); i++) {
2670 if (!strncmp(valid_param_list[i], device,
2671 strlen(valid_param_list[i])))
2672 return 1;
2673 }
2674
2675 return 0;
2676 }
2677
2678 void net_host_device_add(Monitor *mon, const QDict *qdict)
2679 {
2680 const char *device = qdict_get_str(qdict, "device");
2681 const char *opts_str = qdict_get_try_str(qdict, "opts");
2682 QemuOpts *opts;
2683
2684 if (!net_host_check_device(device)) {
2685 monitor_printf(mon, "invalid host network device %s\n", device);
2686 return;
2687 }
2688
2689 opts = qemu_opts_parse(&qemu_net_opts, opts_str ? opts_str : "", NULL);
2690 if (!opts) {
2691 monitor_printf(mon, "parsing network options '%s' failed\n",
2692 opts_str ? opts_str : "");
2693 return;
2694 }
2695
2696 qemu_opt_set(opts, "type", device);
2697
2698 if (net_client_init(mon, opts, 0) < 0) {
2699 monitor_printf(mon, "adding host network device %s failed\n", device);
2700 }
2701 }
2702
2703 void net_host_device_remove(Monitor *mon, const QDict *qdict)
2704 {
2705 VLANClientState *vc;
2706 int vlan_id = qdict_get_int(qdict, "vlan_id");
2707 const char *device = qdict_get_str(qdict, "device");
2708
2709 vc = qemu_find_vlan_client_by_name(mon, vlan_id, device);
2710 if (!vc) {
2711 return;
2712 }
2713 if (!net_host_check_device(vc->model)) {
2714 monitor_printf(mon, "invalid host network device %s\n", device);
2715 return;
2716 }
2717 qemu_del_vlan_client(vc);
2718 }
2719
2720 void net_set_boot_mask(int net_boot_mask)
2721 {
2722 int i;
2723
2724 /* Only the first four NICs may be bootable */
2725 net_boot_mask = net_boot_mask & 0xF;
2726
2727 for (i = 0; i < nb_nics; i++) {
2728 if (net_boot_mask & (1 << i)) {
2729 nd_table[i].bootable = 1;
2730 net_boot_mask &= ~(1 << i);
2731 }
2732 }
2733
2734 if (net_boot_mask) {
2735 fprintf(stderr, "Cannot boot from non-existent NIC\n");
2736 exit(1);
2737 }
2738 }
2739
2740 void do_info_network(Monitor *mon)
2741 {
2742 VLANState *vlan;
2743
2744 QTAILQ_FOREACH(vlan, &vlans, next) {
2745 VLANClientState *vc;
2746
2747 monitor_printf(mon, "VLAN %d devices:\n", vlan->id);
2748
2749 QTAILQ_FOREACH(vc, &vlan->clients, next) {
2750 monitor_printf(mon, " %s: %s\n", vc->name, vc->info_str);
2751 }
2752 }
2753 }
2754
2755 void do_set_link(Monitor *mon, const QDict *qdict)
2756 {
2757 VLANState *vlan;
2758 VLANClientState *vc = NULL;
2759 const char *name = qdict_get_str(qdict, "name");
2760 const char *up_or_down = qdict_get_str(qdict, "up_or_down");
2761
2762 QTAILQ_FOREACH(vlan, &vlans, next) {
2763 QTAILQ_FOREACH(vc, &vlan->clients, next) {
2764 if (strcmp(vc->name, name) == 0) {
2765 goto done;
2766 }
2767 }
2768 }
2769 done:
2770
2771 if (!vc) {
2772 monitor_printf(mon, "could not find network device '%s'\n", name);
2773 return;
2774 }
2775
2776 if (strcmp(up_or_down, "up") == 0)
2777 vc->link_down = 0;
2778 else if (strcmp(up_or_down, "down") == 0)
2779 vc->link_down = 1;
2780 else
2781 monitor_printf(mon, "invalid link status '%s'; only 'up' or 'down' "
2782 "valid\n", up_or_down);
2783
2784 if (vc->link_status_changed)
2785 vc->link_status_changed(vc);
2786 }
2787
2788 void net_cleanup(void)
2789 {
2790 VLANState *vlan;
2791 VLANClientState *vc, *next_vc;
2792
2793 QTAILQ_FOREACH(vlan, &vlans, next) {
2794 QTAILQ_FOREACH_SAFE(vc, &vlan->clients, next, next_vc) {
2795 qemu_del_vlan_client(vc);
2796 }
2797 }
2798
2799 QTAILQ_FOREACH_SAFE(vc, &non_vlan_clients, next, next_vc) {
2800 qemu_del_vlan_client(vc);
2801 }
2802 }
2803
2804 static void net_check_clients(void)
2805 {
2806 VLANState *vlan;
2807
2808 QTAILQ_FOREACH(vlan, &vlans, next) {
2809 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
2810 continue;
2811 if (vlan->nb_guest_devs == 0)
2812 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
2813 if (vlan->nb_host_devs == 0)
2814 fprintf(stderr,
2815 "Warning: vlan %d is not connected to host network\n",
2816 vlan->id);
2817 }
2818 }
2819
2820 static int net_init_client(QemuOpts *opts, void *dummy)
2821 {
2822 if (net_client_init(NULL, opts, 0) < 0)
2823 return -1;
2824 return 0;
2825 }
2826
2827 static int net_init_netdev(QemuOpts *opts, void *dummy)
2828 {
2829 return net_client_init(NULL, opts, 1);
2830 }
2831
2832 int net_init_clients(void)
2833 {
2834 if (QTAILQ_EMPTY(&qemu_net_opts.head)) {
2835 /* if no clients, we use a default config */
2836 qemu_opts_set(&qemu_net_opts, NULL, "type", "nic");
2837 #ifdef CONFIG_SLIRP
2838 qemu_opts_set(&qemu_net_opts, NULL, "type", "user");
2839 #endif
2840 }
2841
2842 QTAILQ_INIT(&vlans);
2843 QTAILQ_INIT(&non_vlan_clients);
2844
2845 if (qemu_opts_foreach(&qemu_netdev_opts, net_init_netdev, NULL, 1) == -1)
2846 return -1;
2847
2848 if (qemu_opts_foreach(&qemu_net_opts, net_init_client, NULL, 1) == -1) {
2849 return -1;
2850 }
2851
2852 net_check_clients();
2853
2854 return 0;
2855 }
2856
2857 int net_client_parse(QemuOptsList *opts_list, const char *optarg)
2858 {
2859 #if defined(CONFIG_SLIRP)
2860 /* handle legacy -net channel,port:chr */
2861 if (!strcmp(opts_list->name, "net") &&
2862 !strncmp(optarg, "channel,", strlen("channel,"))) {
2863 int ret;
2864
2865 optarg += strlen("channel,");
2866
2867 if (QTAILQ_EMPTY(&slirp_stacks)) {
2868 struct slirp_config_str *config;
2869
2870 config = qemu_malloc(sizeof(*config));
2871 pstrcpy(config->str, sizeof(config->str), optarg);
2872 config->flags = SLIRP_CFG_LEGACY;
2873 config->next = slirp_configs;
2874 slirp_configs = config;
2875 ret = 0;
2876 } else {
2877 ret = slirp_guestfwd(QTAILQ_FIRST(&slirp_stacks), optarg, 1);
2878 }
2879
2880 return ret;
2881 }
2882 #endif
2883 if (!qemu_opts_parse(opts_list, optarg, "type")) {
2884 return -1;
2885 }
2886
2887 return 0;
2888 }