Update irqs on reset and device load
[qemu/hppa.git] / net.c
blob2d24a7ce5fad9c0bfd7ef494aa461892513041ea
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 <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>
32 /* Needed early for HOST_BSD etc. */
33 #include "config-host.h"
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 #ifdef __NetBSD__
46 #include <net/if_tap.h>
47 #endif
48 #ifdef __linux__
49 #include <linux/if_tun.h>
50 #endif
51 #include <arpa/inet.h>
52 #include <dirent.h>
53 #include <netdb.h>
54 #include <sys/select.h>
55 #ifdef HOST_BSD
56 #include <sys/stat.h>
57 #if defined(__FreeBSD__) || defined(__DragonFly__)
58 #include <libutil.h>
59 #else
60 #include <util.h>
61 #endif
62 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
63 #include <freebsd/stdlib.h>
64 #else
65 #ifdef __linux__
66 #include <pty.h>
67 #include <malloc.h>
68 #include <linux/rtc.h>
70 /* For the benefit of older linux systems which don't supply it,
71 we use a local copy of hpet.h. */
72 /* #include <linux/hpet.h> */
73 #include "hpet.h"
75 #include <linux/ppdev.h>
76 #include <linux/parport.h>
77 #endif
78 #ifdef __sun__
79 #include <sys/stat.h>
80 #include <sys/ethernet.h>
81 #include <sys/sockio.h>
82 #include <netinet/arp.h>
83 #include <netinet/in.h>
84 #include <netinet/in_systm.h>
85 #include <netinet/ip.h>
86 #include <netinet/ip_icmp.h> // must come after ip.h
87 #include <netinet/udp.h>
88 #include <netinet/tcp.h>
89 #include <net/if.h>
90 #include <syslog.h>
91 #include <stropts.h>
92 #endif
93 #endif
94 #endif
96 #if defined(__OpenBSD__)
97 #include <util.h>
98 #endif
100 #if defined(CONFIG_VDE)
101 #include <libvdeplug.h>
102 #endif
104 #ifdef _WIN32
105 #include <windows.h>
106 #include <malloc.h>
107 #include <sys/timeb.h>
108 #include <mmsystem.h>
109 #define getopt_long_only getopt_long
110 #define memalign(align, size) malloc(size)
111 #endif
113 #include "qemu-common.h"
114 #include "net.h"
115 #include "monitor.h"
116 #include "sysemu.h"
117 #include "qemu-timer.h"
118 #include "qemu-char.h"
119 #include "audio/audio.h"
120 #include "qemu_socket.h"
121 #include "qemu-log.h"
123 #if defined(CONFIG_SLIRP)
124 #include "libslirp.h"
125 #endif
128 static VLANState *first_vlan;
130 /***********************************************************/
131 /* network device redirectors */
133 #if defined(DEBUG_NET) || defined(DEBUG_SLIRP)
134 static void hex_dump(FILE *f, const uint8_t *buf, int size)
136 int len, i, j, c;
138 for(i=0;i<size;i+=16) {
139 len = size - i;
140 if (len > 16)
141 len = 16;
142 fprintf(f, "%08x ", i);
143 for(j=0;j<16;j++) {
144 if (j < len)
145 fprintf(f, " %02x", buf[i+j]);
146 else
147 fprintf(f, " ");
149 fprintf(f, " ");
150 for(j=0;j<len;j++) {
151 c = buf[i+j];
152 if (c < ' ' || c > '~')
153 c = '.';
154 fprintf(f, "%c", c);
156 fprintf(f, "\n");
159 #endif
161 static int parse_macaddr(uint8_t *macaddr, const char *p)
163 int i;
164 char *last_char;
165 long int offset;
167 errno = 0;
168 offset = strtol(p, &last_char, 0);
169 if (0 == errno && '\0' == *last_char &&
170 offset >= 0 && offset <= 0xFFFFFF) {
171 macaddr[3] = (offset & 0xFF0000) >> 16;
172 macaddr[4] = (offset & 0xFF00) >> 8;
173 macaddr[5] = offset & 0xFF;
174 return 0;
175 } else {
176 for(i = 0; i < 6; i++) {
177 macaddr[i] = strtol(p, (char **)&p, 16);
178 if (i == 5) {
179 if (*p != '\0')
180 return -1;
181 } else {
182 if (*p != ':' && *p != '-')
183 return -1;
184 p++;
187 return 0;
190 return -1;
193 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
195 const char *p, *p1;
196 int len;
197 p = *pp;
198 p1 = strchr(p, sep);
199 if (!p1)
200 return -1;
201 len = p1 - p;
202 p1++;
203 if (buf_size > 0) {
204 if (len > buf_size - 1)
205 len = buf_size - 1;
206 memcpy(buf, p, len);
207 buf[len] = '\0';
209 *pp = p1;
210 return 0;
213 int parse_host_src_port(struct sockaddr_in *haddr,
214 struct sockaddr_in *saddr,
215 const char *input_str)
217 char *str = strdup(input_str);
218 char *host_str = str;
219 char *src_str;
220 const char *src_str2;
221 char *ptr;
224 * Chop off any extra arguments at the end of the string which
225 * would start with a comma, then fill in the src port information
226 * if it was provided else use the "any address" and "any port".
228 if ((ptr = strchr(str,',')))
229 *ptr = '\0';
231 if ((src_str = strchr(input_str,'@'))) {
232 *src_str = '\0';
233 src_str++;
236 if (parse_host_port(haddr, host_str) < 0)
237 goto fail;
239 src_str2 = src_str;
240 if (!src_str || *src_str == '\0')
241 src_str2 = ":0";
243 if (parse_host_port(saddr, src_str2) < 0)
244 goto fail;
246 free(str);
247 return(0);
249 fail:
250 free(str);
251 return -1;
254 int parse_host_port(struct sockaddr_in *saddr, const char *str)
256 char buf[512];
257 struct hostent *he;
258 const char *p, *r;
259 int port;
261 p = str;
262 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
263 return -1;
264 saddr->sin_family = AF_INET;
265 if (buf[0] == '\0') {
266 saddr->sin_addr.s_addr = 0;
267 } else {
268 if (qemu_isdigit(buf[0])) {
269 if (!inet_aton(buf, &saddr->sin_addr))
270 return -1;
271 } else {
272 if ((he = gethostbyname(buf)) == NULL)
273 return - 1;
274 saddr->sin_addr = *(struct in_addr *)he->h_addr;
277 port = strtol(p, (char **)&r, 0);
278 if (r == p)
279 return -1;
280 saddr->sin_port = htons(port);
281 return 0;
284 #if !defined(_WIN32) && 0
285 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
287 const char *p;
288 int len;
290 len = MIN(108, strlen(str));
291 p = strchr(str, ',');
292 if (p)
293 len = MIN(len, p - str);
295 memset(uaddr, 0, sizeof(*uaddr));
297 uaddr->sun_family = AF_UNIX;
298 memcpy(uaddr->sun_path, str, len);
300 return 0;
302 #endif
304 void qemu_format_nic_info_str(VLANClientState *vc, uint8_t macaddr[6])
306 snprintf(vc->info_str, sizeof(vc->info_str),
307 "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
308 vc->model,
309 macaddr[0], macaddr[1], macaddr[2],
310 macaddr[3], macaddr[4], macaddr[5]);
313 static char *assign_name(VLANClientState *vc1, const char *model)
315 VLANState *vlan;
316 char buf[256];
317 int id = 0;
319 for (vlan = first_vlan; vlan; vlan = vlan->next) {
320 VLANClientState *vc;
322 for (vc = vlan->first_client; vc; vc = vc->next)
323 if (vc != vc1 && strcmp(vc->model, model) == 0)
324 id++;
327 snprintf(buf, sizeof(buf), "%s.%d", model, id);
329 return strdup(buf);
332 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
333 const char *model,
334 const char *name,
335 IOReadHandler *fd_read,
336 IOCanRWHandler *fd_can_read,
337 NetCleanup *cleanup,
338 void *opaque)
340 VLANClientState *vc, **pvc;
341 vc = qemu_mallocz(sizeof(VLANClientState));
342 vc->model = strdup(model);
343 if (name)
344 vc->name = strdup(name);
345 else
346 vc->name = assign_name(vc, model);
347 vc->fd_read = fd_read;
348 vc->fd_can_read = fd_can_read;
349 vc->cleanup = cleanup;
350 vc->opaque = opaque;
351 vc->vlan = vlan;
353 vc->next = NULL;
354 pvc = &vlan->first_client;
355 while (*pvc != NULL)
356 pvc = &(*pvc)->next;
357 *pvc = vc;
358 return vc;
361 void qemu_del_vlan_client(VLANClientState *vc)
363 VLANClientState **pvc = &vc->vlan->first_client;
365 while (*pvc != NULL)
366 if (*pvc == vc) {
367 *pvc = vc->next;
368 if (vc->cleanup) {
369 vc->cleanup(vc);
371 free(vc->name);
372 free(vc->model);
373 qemu_free(vc);
374 break;
375 } else
376 pvc = &(*pvc)->next;
379 VLANClientState *qemu_find_vlan_client(VLANState *vlan, void *opaque)
381 VLANClientState **pvc = &vlan->first_client;
383 while (*pvc != NULL)
384 if ((*pvc)->opaque == opaque)
385 return *pvc;
386 else
387 pvc = &(*pvc)->next;
389 return NULL;
392 int qemu_can_send_packet(VLANClientState *vc1)
394 VLANState *vlan = vc1->vlan;
395 VLANClientState *vc;
397 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
398 if (vc != vc1) {
399 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
400 return 1;
403 return 0;
406 static void
407 qemu_deliver_packet(VLANClientState *sender, const uint8_t *buf, int size)
409 VLANClientState *vc;
411 for (vc = sender->vlan->first_client; vc != NULL; vc = vc->next) {
412 if (vc != sender && !vc->link_down) {
413 vc->fd_read(vc->opaque, buf, size);
418 void qemu_send_packet(VLANClientState *vc, const uint8_t *buf, int size)
420 VLANState *vlan = vc->vlan;
421 VLANPacket *packet;
423 if (vc->link_down)
424 return;
426 #ifdef DEBUG_NET
427 printf("vlan %d send:\n", vlan->id);
428 hex_dump(stdout, buf, size);
429 #endif
430 if (vlan->delivering) {
431 packet = qemu_malloc(sizeof(VLANPacket) + size);
432 packet->next = vlan->send_queue;
433 packet->sender = vc;
434 packet->size = size;
435 memcpy(packet->data, buf, size);
436 vlan->send_queue = packet;
437 } else {
438 vlan->delivering = 1;
439 qemu_deliver_packet(vc, buf, size);
440 while ((packet = vlan->send_queue) != NULL) {
441 qemu_deliver_packet(packet->sender, packet->data, packet->size);
442 vlan->send_queue = packet->next;
443 qemu_free(packet);
445 vlan->delivering = 0;
449 static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
450 int iovcnt)
452 uint8_t buffer[4096];
453 size_t offset = 0;
454 int i;
456 for (i = 0; i < iovcnt; i++) {
457 size_t len;
459 len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
460 memcpy(buffer + offset, iov[i].iov_base, len);
461 offset += len;
464 vc->fd_read(vc->opaque, buffer, offset);
466 return offset;
469 static ssize_t calc_iov_length(const struct iovec *iov, int iovcnt)
471 size_t offset = 0;
472 int i;
474 for (i = 0; i < iovcnt; i++)
475 offset += iov[i].iov_len;
476 return offset;
479 ssize_t qemu_sendv_packet(VLANClientState *vc1, const struct iovec *iov,
480 int iovcnt)
482 VLANState *vlan = vc1->vlan;
483 VLANClientState *vc;
484 ssize_t max_len = 0;
486 if (vc1->link_down)
487 return calc_iov_length(iov, iovcnt);
489 for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
490 ssize_t len = 0;
492 if (vc == vc1)
493 continue;
495 if (vc->link_down)
496 len = calc_iov_length(iov, iovcnt);
497 if (vc->fd_readv)
498 len = vc->fd_readv(vc->opaque, iov, iovcnt);
499 else if (vc->fd_read)
500 len = vc_sendv_compat(vc, iov, iovcnt);
502 max_len = MAX(max_len, len);
505 return max_len;
508 #if defined(CONFIG_SLIRP)
510 /* slirp network adapter */
512 static int slirp_inited;
513 static int slirp_restrict;
514 static char *slirp_ip;
515 static VLANClientState *slirp_vc;
517 int slirp_can_output(void)
519 return !slirp_vc || qemu_can_send_packet(slirp_vc);
522 void slirp_output(const uint8_t *pkt, int pkt_len)
524 #ifdef DEBUG_SLIRP
525 printf("slirp output:\n");
526 hex_dump(stdout, pkt, pkt_len);
527 #endif
528 if (!slirp_vc)
529 return;
530 qemu_send_packet(slirp_vc, pkt, pkt_len);
533 int slirp_is_inited(void)
535 return slirp_inited;
538 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
540 #ifdef DEBUG_SLIRP
541 printf("slirp input:\n");
542 hex_dump(stdout, buf, size);
543 #endif
544 slirp_input(buf, size);
547 static int slirp_in_use;
549 static void net_slirp_cleanup(VLANClientState *vc)
551 slirp_in_use = 0;
554 static int net_slirp_init(VLANState *vlan, const char *model, const char *name)
556 if (slirp_in_use) {
557 /* slirp only supports a single instance so far */
558 return -1;
560 if (!slirp_inited) {
561 slirp_inited = 1;
562 slirp_init(slirp_restrict, slirp_ip);
564 slirp_vc = qemu_new_vlan_client(vlan, model, name,
565 slirp_receive, NULL, net_slirp_cleanup, NULL);
566 slirp_vc->info_str[0] = '\0';
567 slirp_in_use = 1;
568 return 0;
571 static void net_slirp_redir_print(void *opaque, int is_udp,
572 struct in_addr *laddr, u_int lport,
573 struct in_addr *faddr, u_int fport)
575 Monitor *mon = (Monitor *)opaque;
576 uint32_t h_addr;
577 uint32_t g_addr;
578 char buf[16];
580 h_addr = ntohl(faddr->s_addr);
581 g_addr = ntohl(laddr->s_addr);
583 monitor_printf(mon, " %s |", is_udp ? "udp" : "tcp" );
584 snprintf(buf, 15, "%d.%d.%d.%d", (h_addr >> 24) & 0xff,
585 (h_addr >> 16) & 0xff,
586 (h_addr >> 8) & 0xff,
587 (h_addr) & 0xff);
588 monitor_printf(mon, " %15s |", buf);
589 monitor_printf(mon, " %5d |", fport);
591 snprintf(buf, 15, "%d.%d.%d.%d", (g_addr >> 24) & 0xff,
592 (g_addr >> 16) & 0xff,
593 (g_addr >> 8) & 0xff,
594 (g_addr) & 0xff);
595 monitor_printf(mon, " %15s |", buf);
596 monitor_printf(mon, " %5d\n", lport);
600 static void net_slirp_redir_list(Monitor *mon)
602 if (!mon)
603 return;
605 monitor_printf(mon, " Prot | Host Addr | HPort | Guest Addr | GPort\n");
606 monitor_printf(mon, " | | | | \n");
607 slirp_redir_loop(net_slirp_redir_print, mon);
610 static void net_slirp_redir_rm(Monitor *mon, const char *port_str)
612 int host_port;
613 char buf[256] = "";
614 const char *p = port_str;
615 int is_udp = 0;
616 int n;
618 if (!mon)
619 return;
621 if (!port_str || !port_str[0])
622 goto fail_syntax;
624 get_str_sep(buf, sizeof(buf), &p, ':');
626 if (!strcmp(buf, "tcp") || buf[0] == '\0') {
627 is_udp = 0;
628 } else if (!strcmp(buf, "udp")) {
629 is_udp = 1;
630 } else {
631 goto fail_syntax;
634 host_port = atoi(p);
636 n = slirp_redir_rm(is_udp, host_port);
638 monitor_printf(mon, "removed %d redirections to %s port %d\n", n,
639 is_udp ? "udp" : "tcp", host_port);
640 return;
642 fail_syntax:
643 monitor_printf(mon, "invalid format\n");
646 void net_slirp_redir(Monitor *mon, const char *redir_str, const char *redir_opt2)
648 int is_udp;
649 char buf[256], *r;
650 const char *p, *errmsg;
651 struct in_addr guest_addr;
652 int host_port, guest_port;
654 if (!slirp_inited) {
655 slirp_inited = 1;
656 slirp_init(slirp_restrict, slirp_ip);
659 if (!strcmp(redir_str, "remove")) {
660 net_slirp_redir_rm(mon, redir_opt2);
661 return;
664 if (!strcmp(redir_str, "list")) {
665 net_slirp_redir_list(mon);
666 return;
669 p = redir_str;
670 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
671 goto fail_syntax;
672 if (!strcmp(buf, "tcp") || buf[0] == '\0') {
673 is_udp = 0;
674 } else if (!strcmp(buf, "udp")) {
675 is_udp = 1;
676 } else {
677 goto fail_syntax;
680 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
681 goto fail_syntax;
682 host_port = strtol(buf, &r, 0);
683 if (r == buf)
684 goto fail_syntax;
686 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
687 goto fail_syntax;
688 if (buf[0] == '\0') {
689 pstrcpy(buf, sizeof(buf), "10.0.2.15");
691 if (!inet_aton(buf, &guest_addr))
692 goto fail_syntax;
694 guest_port = strtol(p, &r, 0);
695 if (r == p)
696 goto fail_syntax;
698 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
699 errmsg = "could not set up redirection\n";
700 goto fail;
702 return;
704 fail_syntax:
705 errmsg = "invalid redirection format\n";
706 fail:
707 if (mon) {
708 monitor_printf(mon, "%s", errmsg);
709 } else {
710 fprintf(stderr, "qemu: %s", errmsg);
711 exit(1);
715 #ifndef _WIN32
717 static char smb_dir[1024];
719 static void erase_dir(char *dir_name)
721 DIR *d;
722 struct dirent *de;
723 char filename[1024];
725 /* erase all the files in the directory */
726 if ((d = opendir(dir_name)) != NULL) {
727 for(;;) {
728 de = readdir(d);
729 if (!de)
730 break;
731 if (strcmp(de->d_name, ".") != 0 &&
732 strcmp(de->d_name, "..") != 0) {
733 snprintf(filename, sizeof(filename), "%s/%s",
734 smb_dir, de->d_name);
735 if (unlink(filename) != 0) /* is it a directory? */
736 erase_dir(filename);
739 closedir(d);
740 rmdir(dir_name);
744 /* automatic user mode samba server configuration */
745 static void smb_exit(void)
747 erase_dir(smb_dir);
750 /* automatic user mode samba server configuration */
751 void net_slirp_smb(const char *exported_dir)
753 char smb_conf[1024];
754 char smb_cmdline[1024];
755 FILE *f;
757 if (!slirp_inited) {
758 slirp_inited = 1;
759 slirp_init(slirp_restrict, slirp_ip);
762 /* XXX: better tmp dir construction */
763 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%ld", (long)getpid());
764 if (mkdir(smb_dir, 0700) < 0) {
765 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
766 exit(1);
768 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
770 f = fopen(smb_conf, "w");
771 if (!f) {
772 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
773 exit(1);
775 fprintf(f,
776 "[global]\n"
777 "private dir=%s\n"
778 "smb ports=0\n"
779 "socket address=127.0.0.1\n"
780 "pid directory=%s\n"
781 "lock directory=%s\n"
782 "log file=%s/log.smbd\n"
783 "smb passwd file=%s/smbpasswd\n"
784 "security = share\n"
785 "[qemu]\n"
786 "path=%s\n"
787 "read only=no\n"
788 "guest ok=yes\n",
789 smb_dir,
790 smb_dir,
791 smb_dir,
792 smb_dir,
793 smb_dir,
794 exported_dir
796 fclose(f);
797 atexit(smb_exit);
799 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
800 SMBD_COMMAND, smb_conf);
802 slirp_add_exec(0, smb_cmdline, 4, 139);
805 #endif /* !defined(_WIN32) */
806 void do_info_slirp(Monitor *mon)
808 slirp_stats();
811 struct VMChannel {
812 CharDriverState *hd;
813 int port;
816 static int vmchannel_can_read(void *opaque)
818 struct VMChannel *vmc = (struct VMChannel*)opaque;
819 return slirp_socket_can_recv(4, vmc->port);
822 static void vmchannel_read(void *opaque, const uint8_t *buf, int size)
824 struct VMChannel *vmc = (struct VMChannel*)opaque;
825 slirp_socket_recv(4, vmc->port, buf, size);
828 #endif /* CONFIG_SLIRP */
830 #if !defined(_WIN32)
832 typedef struct TAPState {
833 VLANClientState *vc;
834 int fd;
835 char down_script[1024];
836 char down_script_arg[128];
837 } TAPState;
839 static int launch_script(const char *setup_script, const char *ifname, int fd);
841 static ssize_t tap_receive_iov(void *opaque, const struct iovec *iov,
842 int iovcnt)
844 TAPState *s = opaque;
845 ssize_t len;
847 do {
848 len = writev(s->fd, iov, iovcnt);
849 } while (len == -1 && (errno == EINTR || errno == EAGAIN));
851 return len;
854 static void tap_receive(void *opaque, const uint8_t *buf, int size)
856 TAPState *s = opaque;
857 int ret;
858 for(;;) {
859 ret = write(s->fd, buf, size);
860 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
861 } else {
862 break;
867 static void tap_send(void *opaque)
869 TAPState *s = opaque;
870 uint8_t buf[4096];
871 int size;
873 #ifdef __sun__
874 struct strbuf sbuf;
875 int f = 0;
876 sbuf.maxlen = sizeof(buf);
877 sbuf.buf = (char *)buf;
878 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
879 #else
880 size = read(s->fd, buf, sizeof(buf));
881 #endif
882 if (size > 0) {
883 qemu_send_packet(s->vc, buf, size);
887 static void tap_cleanup(VLANClientState *vc)
889 TAPState *s = vc->opaque;
891 if (s->down_script[0])
892 launch_script(s->down_script, s->down_script_arg, s->fd);
894 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
895 close(s->fd);
896 qemu_free(s);
899 /* fd support */
901 static TAPState *net_tap_fd_init(VLANState *vlan,
902 const char *model,
903 const char *name,
904 int fd)
906 TAPState *s;
908 s = qemu_mallocz(sizeof(TAPState));
909 s->fd = fd;
910 s->vc = qemu_new_vlan_client(vlan, model, name, tap_receive,
911 NULL, tap_cleanup, s);
912 s->vc->fd_readv = tap_receive_iov;
913 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
914 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "fd=%d", fd);
915 return s;
918 #if defined (HOST_BSD) || defined (__FreeBSD_kernel__)
919 static int tap_open(char *ifname, int ifname_size)
921 int fd;
922 char *dev;
923 struct stat s;
925 TFR(fd = open("/dev/tap", O_RDWR));
926 if (fd < 0) {
927 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
928 return -1;
931 fstat(fd, &s);
932 dev = devname(s.st_rdev, S_IFCHR);
933 pstrcpy(ifname, ifname_size, dev);
935 fcntl(fd, F_SETFL, O_NONBLOCK);
936 return fd;
938 #elif defined(__sun__)
939 #define TUNNEWPPA (('T'<<16) | 0x0001)
941 * Allocate TAP device, returns opened fd.
942 * Stores dev name in the first arg(must be large enough).
944 static int tap_alloc(char *dev, size_t dev_size)
946 int tap_fd, if_fd, ppa = -1;
947 static int ip_fd = 0;
948 char *ptr;
950 static int arp_fd = 0;
951 int ip_muxid, arp_muxid;
952 struct strioctl strioc_if, strioc_ppa;
953 int link_type = I_PLINK;;
954 struct lifreq ifr;
955 char actual_name[32] = "";
957 memset(&ifr, 0x0, sizeof(ifr));
959 if( *dev ){
960 ptr = dev;
961 while( *ptr && !qemu_isdigit((int)*ptr) ) ptr++;
962 ppa = atoi(ptr);
965 /* Check if IP device was opened */
966 if( ip_fd )
967 close(ip_fd);
969 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
970 if (ip_fd < 0) {
971 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
972 return -1;
975 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
976 if (tap_fd < 0) {
977 syslog(LOG_ERR, "Can't open /dev/tap");
978 return -1;
981 /* Assign a new PPA and get its unit number. */
982 strioc_ppa.ic_cmd = TUNNEWPPA;
983 strioc_ppa.ic_timout = 0;
984 strioc_ppa.ic_len = sizeof(ppa);
985 strioc_ppa.ic_dp = (char *)&ppa;
986 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
987 syslog (LOG_ERR, "Can't assign new interface");
989 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
990 if (if_fd < 0) {
991 syslog(LOG_ERR, "Can't open /dev/tap (2)");
992 return -1;
994 if(ioctl(if_fd, I_PUSH, "ip") < 0){
995 syslog(LOG_ERR, "Can't push IP module");
996 return -1;
999 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
1000 syslog(LOG_ERR, "Can't get flags\n");
1002 snprintf (actual_name, 32, "tap%d", ppa);
1003 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
1005 ifr.lifr_ppa = ppa;
1006 /* Assign ppa according to the unit number returned by tun device */
1008 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
1009 syslog (LOG_ERR, "Can't set PPA %d", ppa);
1010 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
1011 syslog (LOG_ERR, "Can't get flags\n");
1012 /* Push arp module to if_fd */
1013 if (ioctl (if_fd, I_PUSH, "arp") < 0)
1014 syslog (LOG_ERR, "Can't push ARP module (2)");
1016 /* Push arp module to ip_fd */
1017 if (ioctl (ip_fd, I_POP, NULL) < 0)
1018 syslog (LOG_ERR, "I_POP failed\n");
1019 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
1020 syslog (LOG_ERR, "Can't push ARP module (3)\n");
1021 /* Open arp_fd */
1022 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
1023 if (arp_fd < 0)
1024 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
1026 /* Set ifname to arp */
1027 strioc_if.ic_cmd = SIOCSLIFNAME;
1028 strioc_if.ic_timout = 0;
1029 strioc_if.ic_len = sizeof(ifr);
1030 strioc_if.ic_dp = (char *)&ifr;
1031 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
1032 syslog (LOG_ERR, "Can't set ifname to arp\n");
1035 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
1036 syslog(LOG_ERR, "Can't link TAP device to IP");
1037 return -1;
1040 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
1041 syslog (LOG_ERR, "Can't link TAP device to ARP");
1043 close (if_fd);
1045 memset(&ifr, 0x0, sizeof(ifr));
1046 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
1047 ifr.lifr_ip_muxid = ip_muxid;
1048 ifr.lifr_arp_muxid = arp_muxid;
1050 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
1052 ioctl (ip_fd, I_PUNLINK , arp_muxid);
1053 ioctl (ip_fd, I_PUNLINK, ip_muxid);
1054 syslog (LOG_ERR, "Can't set multiplexor id");
1057 snprintf(dev, dev_size, "tap%d", ppa);
1058 return tap_fd;
1061 static int tap_open(char *ifname, int ifname_size)
1063 char dev[10]="";
1064 int fd;
1065 if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
1066 fprintf(stderr, "Cannot allocate TAP device\n");
1067 return -1;
1069 pstrcpy(ifname, ifname_size, dev);
1070 fcntl(fd, F_SETFL, O_NONBLOCK);
1071 return fd;
1073 #elif defined (_AIX)
1074 static int tap_open(char *ifname, int ifname_size)
1076 fprintf (stderr, "no tap on AIX\n");
1077 return -1;
1079 #else
1080 static int tap_open(char *ifname, int ifname_size)
1082 struct ifreq ifr;
1083 int fd, ret;
1085 TFR(fd = open("/dev/net/tun", O_RDWR));
1086 if (fd < 0) {
1087 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1088 return -1;
1090 memset(&ifr, 0, sizeof(ifr));
1091 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1092 if (ifname[0] != '\0')
1093 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
1094 else
1095 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
1096 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1097 if (ret != 0) {
1098 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1099 close(fd);
1100 return -1;
1102 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1103 fcntl(fd, F_SETFL, O_NONBLOCK);
1104 return fd;
1106 #endif
1108 static int launch_script(const char *setup_script, const char *ifname, int fd)
1110 int pid, status;
1111 char *args[3];
1112 char **parg;
1114 /* try to launch network script */
1115 pid = fork();
1116 if (pid >= 0) {
1117 if (pid == 0) {
1118 int open_max = sysconf (_SC_OPEN_MAX), i;
1119 for (i = 0; i < open_max; i++)
1120 if (i != STDIN_FILENO &&
1121 i != STDOUT_FILENO &&
1122 i != STDERR_FILENO &&
1123 i != fd)
1124 close(i);
1126 parg = args;
1127 *parg++ = (char *)setup_script;
1128 *parg++ = (char *)ifname;
1129 *parg++ = NULL;
1130 execv(setup_script, args);
1131 _exit(1);
1133 while (waitpid(pid, &status, 0) != pid);
1134 if (!WIFEXITED(status) ||
1135 WEXITSTATUS(status) != 0) {
1136 fprintf(stderr, "%s: could not launch network script\n",
1137 setup_script);
1138 return -1;
1141 return 0;
1144 static int net_tap_init(VLANState *vlan, const char *model,
1145 const char *name, const char *ifname1,
1146 const char *setup_script, const char *down_script)
1148 TAPState *s;
1149 int fd;
1150 char ifname[128];
1152 if (ifname1 != NULL)
1153 pstrcpy(ifname, sizeof(ifname), ifname1);
1154 else
1155 ifname[0] = '\0';
1156 TFR(fd = tap_open(ifname, sizeof(ifname)));
1157 if (fd < 0)
1158 return -1;
1160 if (!setup_script || !strcmp(setup_script, "no"))
1161 setup_script = "";
1162 if (setup_script[0] != '\0') {
1163 if (launch_script(setup_script, ifname, fd))
1164 return -1;
1166 s = net_tap_fd_init(vlan, model, name, fd);
1167 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1168 "ifname=%s,script=%s,downscript=%s",
1169 ifname, setup_script, down_script);
1170 if (down_script && strcmp(down_script, "no")) {
1171 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
1172 snprintf(s->down_script_arg, sizeof(s->down_script_arg), "%s", ifname);
1174 return 0;
1177 #endif /* !_WIN32 */
1179 #if defined(CONFIG_VDE)
1180 typedef struct VDEState {
1181 VLANClientState *vc;
1182 VDECONN *vde;
1183 } VDEState;
1185 static void vde_to_qemu(void *opaque)
1187 VDEState *s = opaque;
1188 uint8_t buf[4096];
1189 int size;
1191 size = vde_recv(s->vde, (char *)buf, sizeof(buf), 0);
1192 if (size > 0) {
1193 qemu_send_packet(s->vc, buf, size);
1197 static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
1199 VDEState *s = opaque;
1200 int ret;
1201 for(;;) {
1202 ret = vde_send(s->vde, (const char *)buf, size, 0);
1203 if (ret < 0 && errno == EINTR) {
1204 } else {
1205 break;
1210 static void vde_cleanup(VLANClientState *vc)
1212 VDEState *s = vc->opaque;
1213 qemu_set_fd_handler(vde_datafd(s->vde), NULL, NULL, NULL);
1214 vde_close(s->vde);
1215 qemu_free(s);
1218 static int net_vde_init(VLANState *vlan, const char *model,
1219 const char *name, const char *sock,
1220 int port, const char *group, int mode)
1222 VDEState *s;
1223 char *init_group = strlen(group) ? (char *)group : NULL;
1224 char *init_sock = strlen(sock) ? (char *)sock : NULL;
1226 struct vde_open_args args = {
1227 .port = port,
1228 .group = init_group,
1229 .mode = mode,
1232 s = qemu_mallocz(sizeof(VDEState));
1233 s->vde = vde_open(init_sock, (char *)"QEMU", &args);
1234 if (!s->vde){
1235 free(s);
1236 return -1;
1238 s->vc = qemu_new_vlan_client(vlan, model, name, vde_from_qemu,
1239 NULL, vde_cleanup, s);
1240 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
1241 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "sock=%s,fd=%d",
1242 sock, vde_datafd(s->vde));
1243 return 0;
1245 #endif
1247 /* network connection */
1248 typedef struct NetSocketState {
1249 VLANClientState *vc;
1250 int fd;
1251 int state; /* 0 = getting length, 1 = getting data */
1252 unsigned int index;
1253 unsigned int packet_len;
1254 uint8_t buf[4096];
1255 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
1256 } NetSocketState;
1258 typedef struct NetSocketListenState {
1259 VLANState *vlan;
1260 char *model;
1261 char *name;
1262 int fd;
1263 } NetSocketListenState;
1265 /* XXX: we consider we can send the whole packet without blocking */
1266 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
1268 NetSocketState *s = opaque;
1269 uint32_t len;
1270 len = htonl(size);
1272 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
1273 send_all(s->fd, buf, size);
1276 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
1278 NetSocketState *s = opaque;
1279 sendto(s->fd, buf, size, 0,
1280 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
1283 static void net_socket_send(void *opaque)
1285 NetSocketState *s = opaque;
1286 int size, err;
1287 unsigned l;
1288 uint8_t buf1[4096];
1289 const uint8_t *buf;
1291 size = recv(s->fd, buf1, sizeof(buf1), 0);
1292 if (size < 0) {
1293 err = socket_error();
1294 if (err != EWOULDBLOCK)
1295 goto eoc;
1296 } else if (size == 0) {
1297 /* end of connection */
1298 eoc:
1299 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1300 closesocket(s->fd);
1301 return;
1303 buf = buf1;
1304 while (size > 0) {
1305 /* reassemble a packet from the network */
1306 switch(s->state) {
1307 case 0:
1308 l = 4 - s->index;
1309 if (l > size)
1310 l = size;
1311 memcpy(s->buf + s->index, buf, l);
1312 buf += l;
1313 size -= l;
1314 s->index += l;
1315 if (s->index == 4) {
1316 /* got length */
1317 s->packet_len = ntohl(*(uint32_t *)s->buf);
1318 s->index = 0;
1319 s->state = 1;
1321 break;
1322 case 1:
1323 l = s->packet_len - s->index;
1324 if (l > size)
1325 l = size;
1326 if (s->index + l <= sizeof(s->buf)) {
1327 memcpy(s->buf + s->index, buf, l);
1328 } else {
1329 fprintf(stderr, "serious error: oversized packet received,"
1330 "connection terminated.\n");
1331 s->state = 0;
1332 goto eoc;
1335 s->index += l;
1336 buf += l;
1337 size -= l;
1338 if (s->index >= s->packet_len) {
1339 qemu_send_packet(s->vc, s->buf, s->packet_len);
1340 s->index = 0;
1341 s->state = 0;
1343 break;
1348 static void net_socket_send_dgram(void *opaque)
1350 NetSocketState *s = opaque;
1351 int size;
1353 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
1354 if (size < 0)
1355 return;
1356 if (size == 0) {
1357 /* end of connection */
1358 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1359 return;
1361 qemu_send_packet(s->vc, s->buf, size);
1364 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
1366 struct ip_mreq imr;
1367 int fd;
1368 int val, ret;
1369 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
1370 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
1371 inet_ntoa(mcastaddr->sin_addr),
1372 (int)ntohl(mcastaddr->sin_addr.s_addr));
1373 return -1;
1376 fd = socket(PF_INET, SOCK_DGRAM, 0);
1377 if (fd < 0) {
1378 perror("socket(PF_INET, SOCK_DGRAM)");
1379 return -1;
1382 val = 1;
1383 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1384 (const char *)&val, sizeof(val));
1385 if (ret < 0) {
1386 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
1387 goto fail;
1390 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
1391 if (ret < 0) {
1392 perror("bind");
1393 goto fail;
1396 /* Add host to multicast group */
1397 imr.imr_multiaddr = mcastaddr->sin_addr;
1398 imr.imr_interface.s_addr = htonl(INADDR_ANY);
1400 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1401 (const char *)&imr, sizeof(struct ip_mreq));
1402 if (ret < 0) {
1403 perror("setsockopt(IP_ADD_MEMBERSHIP)");
1404 goto fail;
1407 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
1408 val = 1;
1409 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1410 (const char *)&val, sizeof(val));
1411 if (ret < 0) {
1412 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
1413 goto fail;
1416 socket_set_nonblock(fd);
1417 return fd;
1418 fail:
1419 if (fd >= 0)
1420 closesocket(fd);
1421 return -1;
1424 static void net_socket_cleanup(VLANClientState *vc)
1426 NetSocketState *s = vc->opaque;
1427 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1428 close(s->fd);
1429 qemu_free(s);
1432 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan,
1433 const char *model,
1434 const char *name,
1435 int fd, int is_connected)
1437 struct sockaddr_in saddr;
1438 int newfd;
1439 socklen_t saddr_len;
1440 NetSocketState *s;
1442 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
1443 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
1444 * by ONLY ONE process: we must "clone" this dgram socket --jjo
1447 if (is_connected) {
1448 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
1449 /* must be bound */
1450 if (saddr.sin_addr.s_addr==0) {
1451 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
1452 fd);
1453 return NULL;
1455 /* clone dgram socket */
1456 newfd = net_socket_mcast_create(&saddr);
1457 if (newfd < 0) {
1458 /* error already reported by net_socket_mcast_create() */
1459 close(fd);
1460 return NULL;
1462 /* clone newfd to fd, close newfd */
1463 dup2(newfd, fd);
1464 close(newfd);
1466 } else {
1467 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
1468 fd, strerror(errno));
1469 return NULL;
1473 s = qemu_mallocz(sizeof(NetSocketState));
1474 s->fd = fd;
1476 s->vc = qemu_new_vlan_client(vlan, model, name, net_socket_receive_dgram,
1477 NULL, net_socket_cleanup, s);
1478 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
1480 /* mcast: save bound address as dst */
1481 if (is_connected) s->dgram_dst=saddr;
1483 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1484 "socket: fd=%d (%s mcast=%s:%d)",
1485 fd, is_connected? "cloned" : "",
1486 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1487 return s;
1490 static void net_socket_connect(void *opaque)
1492 NetSocketState *s = opaque;
1493 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
1496 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan,
1497 const char *model,
1498 const char *name,
1499 int fd, int is_connected)
1501 NetSocketState *s;
1502 s = qemu_mallocz(sizeof(NetSocketState));
1503 s->fd = fd;
1504 s->vc = qemu_new_vlan_client(vlan, model, name, net_socket_receive,
1505 NULL, net_socket_cleanup, s);
1506 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1507 "socket: fd=%d", fd);
1508 if (is_connected) {
1509 net_socket_connect(s);
1510 } else {
1511 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
1513 return s;
1516 static NetSocketState *net_socket_fd_init(VLANState *vlan,
1517 const char *model, const char *name,
1518 int fd, int is_connected)
1520 int so_type=-1, optlen=sizeof(so_type);
1522 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
1523 (socklen_t *)&optlen)< 0) {
1524 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
1525 return NULL;
1527 switch(so_type) {
1528 case SOCK_DGRAM:
1529 return net_socket_fd_init_dgram(vlan, model, name, fd, is_connected);
1530 case SOCK_STREAM:
1531 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1532 default:
1533 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
1534 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
1535 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1537 return NULL;
1540 static void net_socket_accept(void *opaque)
1542 NetSocketListenState *s = opaque;
1543 NetSocketState *s1;
1544 struct sockaddr_in saddr;
1545 socklen_t len;
1546 int fd;
1548 for(;;) {
1549 len = sizeof(saddr);
1550 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
1551 if (fd < 0 && errno != EINTR) {
1552 return;
1553 } else if (fd >= 0) {
1554 break;
1557 s1 = net_socket_fd_init(s->vlan, s->model, s->name, fd, 1);
1558 if (!s1) {
1559 closesocket(fd);
1560 } else {
1561 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
1562 "socket: connection from %s:%d",
1563 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1567 static int net_socket_listen_init(VLANState *vlan,
1568 const char *model,
1569 const char *name,
1570 const char *host_str)
1572 NetSocketListenState *s;
1573 int fd, val, ret;
1574 struct sockaddr_in saddr;
1576 if (parse_host_port(&saddr, host_str) < 0)
1577 return -1;
1579 s = qemu_mallocz(sizeof(NetSocketListenState));
1581 fd = socket(PF_INET, SOCK_STREAM, 0);
1582 if (fd < 0) {
1583 perror("socket");
1584 return -1;
1586 socket_set_nonblock(fd);
1588 /* allow fast reuse */
1589 val = 1;
1590 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
1592 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1593 if (ret < 0) {
1594 perror("bind");
1595 return -1;
1597 ret = listen(fd, 0);
1598 if (ret < 0) {
1599 perror("listen");
1600 return -1;
1602 s->vlan = vlan;
1603 s->model = strdup(model);
1604 s->name = name ? strdup(name) : NULL;
1605 s->fd = fd;
1606 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
1607 return 0;
1610 static int net_socket_connect_init(VLANState *vlan,
1611 const char *model,
1612 const char *name,
1613 const char *host_str)
1615 NetSocketState *s;
1616 int fd, connected, ret, err;
1617 struct sockaddr_in saddr;
1619 if (parse_host_port(&saddr, host_str) < 0)
1620 return -1;
1622 fd = socket(PF_INET, SOCK_STREAM, 0);
1623 if (fd < 0) {
1624 perror("socket");
1625 return -1;
1627 socket_set_nonblock(fd);
1629 connected = 0;
1630 for(;;) {
1631 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1632 if (ret < 0) {
1633 err = socket_error();
1634 if (err == EINTR || err == EWOULDBLOCK) {
1635 } else if (err == EINPROGRESS) {
1636 break;
1637 #ifdef _WIN32
1638 } else if (err == WSAEALREADY) {
1639 break;
1640 #endif
1641 } else {
1642 perror("connect");
1643 closesocket(fd);
1644 return -1;
1646 } else {
1647 connected = 1;
1648 break;
1651 s = net_socket_fd_init(vlan, model, name, fd, connected);
1652 if (!s)
1653 return -1;
1654 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1655 "socket: connect to %s:%d",
1656 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1657 return 0;
1660 static int net_socket_mcast_init(VLANState *vlan,
1661 const char *model,
1662 const char *name,
1663 const char *host_str)
1665 NetSocketState *s;
1666 int fd;
1667 struct sockaddr_in saddr;
1669 if (parse_host_port(&saddr, host_str) < 0)
1670 return -1;
1673 fd = net_socket_mcast_create(&saddr);
1674 if (fd < 0)
1675 return -1;
1677 s = net_socket_fd_init(vlan, model, name, fd, 0);
1678 if (!s)
1679 return -1;
1681 s->dgram_dst = saddr;
1683 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1684 "socket: mcast=%s:%d",
1685 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1686 return 0;
1690 typedef struct DumpState {
1691 VLANClientState *pcap_vc;
1692 int fd;
1693 int pcap_caplen;
1694 } DumpState;
1696 #define PCAP_MAGIC 0xa1b2c3d4
1698 struct pcap_file_hdr {
1699 uint32_t magic;
1700 uint16_t version_major;
1701 uint16_t version_minor;
1702 int32_t thiszone;
1703 uint32_t sigfigs;
1704 uint32_t snaplen;
1705 uint32_t linktype;
1708 struct pcap_sf_pkthdr {
1709 struct {
1710 int32_t tv_sec;
1711 int32_t tv_usec;
1712 } ts;
1713 uint32_t caplen;
1714 uint32_t len;
1717 static void dump_receive(void *opaque, const uint8_t *buf, int size)
1719 DumpState *s = opaque;
1720 struct pcap_sf_pkthdr hdr;
1721 int64_t ts;
1722 int caplen;
1724 /* Early return in case of previous error. */
1725 if (s->fd < 0) {
1726 return;
1729 ts = muldiv64(qemu_get_clock(vm_clock), 1000000, ticks_per_sec);
1730 caplen = size > s->pcap_caplen ? s->pcap_caplen : size;
1732 hdr.ts.tv_sec = ts / 1000000;
1733 hdr.ts.tv_usec = ts % 1000000;
1734 hdr.caplen = caplen;
1735 hdr.len = size;
1736 if (write(s->fd, &hdr, sizeof(hdr)) != sizeof(hdr) ||
1737 write(s->fd, buf, caplen) != caplen) {
1738 qemu_log("-net dump write error - stop dump\n");
1739 close(s->fd);
1740 s->fd = -1;
1744 static void net_dump_cleanup(VLANClientState *vc)
1746 DumpState *s = vc->opaque;
1748 close(s->fd);
1749 qemu_free(s);
1752 static int net_dump_init(VLANState *vlan, const char *device,
1753 const char *name, const char *filename, int len)
1755 struct pcap_file_hdr hdr;
1756 DumpState *s;
1758 s = qemu_malloc(sizeof(DumpState));
1760 s->fd = open(filename, O_CREAT | O_WRONLY, 0644);
1761 if (s->fd < 0) {
1762 fprintf(stderr, "-net dump: can't open %s\n", filename);
1763 return -1;
1766 s->pcap_caplen = len;
1768 hdr.magic = PCAP_MAGIC;
1769 hdr.version_major = 2;
1770 hdr.version_minor = 4;
1771 hdr.thiszone = 0;
1772 hdr.sigfigs = 0;
1773 hdr.snaplen = s->pcap_caplen;
1774 hdr.linktype = 1;
1776 if (write(s->fd, &hdr, sizeof(hdr)) < sizeof(hdr)) {
1777 perror("-net dump write error");
1778 close(s->fd);
1779 qemu_free(s);
1780 return -1;
1783 s->pcap_vc = qemu_new_vlan_client(vlan, device, name, dump_receive, NULL,
1784 net_dump_cleanup, s);
1785 snprintf(s->pcap_vc->info_str, sizeof(s->pcap_vc->info_str),
1786 "dump to %s (len=%d)", filename, len);
1787 return 0;
1790 /* find or alloc a new VLAN */
1791 VLANState *qemu_find_vlan(int id)
1793 VLANState **pvlan, *vlan;
1794 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1795 if (vlan->id == id)
1796 return vlan;
1798 vlan = qemu_mallocz(sizeof(VLANState));
1799 vlan->id = id;
1800 vlan->next = NULL;
1801 pvlan = &first_vlan;
1802 while (*pvlan != NULL)
1803 pvlan = &(*pvlan)->next;
1804 *pvlan = vlan;
1805 return vlan;
1808 static int nic_get_free_idx(void)
1810 int index;
1812 for (index = 0; index < MAX_NICS; index++)
1813 if (!nd_table[index].used)
1814 return index;
1815 return -1;
1818 void qemu_check_nic_model(NICInfo *nd, const char *model)
1820 const char *models[2];
1822 models[0] = model;
1823 models[1] = NULL;
1825 qemu_check_nic_model_list(nd, models, model);
1828 void qemu_check_nic_model_list(NICInfo *nd, const char * const *models,
1829 const char *default_model)
1831 int i, exit_status = 0;
1833 if (!nd->model)
1834 nd->model = strdup(default_model);
1836 if (strcmp(nd->model, "?") != 0) {
1837 for (i = 0 ; models[i]; i++)
1838 if (strcmp(nd->model, models[i]) == 0)
1839 return;
1841 fprintf(stderr, "qemu: Unsupported NIC model: %s\n", nd->model);
1842 exit_status = 1;
1845 fprintf(stderr, "qemu: Supported NIC models: ");
1846 for (i = 0 ; models[i]; i++)
1847 fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
1849 exit(exit_status);
1852 int net_client_init(const char *device, const char *p)
1854 static const char * const fd_params[] = {
1855 "vlan", "name", "fd", NULL
1857 char buf[1024];
1858 int vlan_id, ret;
1859 VLANState *vlan;
1860 char *name = NULL;
1862 vlan_id = 0;
1863 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
1864 vlan_id = strtol(buf, NULL, 0);
1866 vlan = qemu_find_vlan(vlan_id);
1868 if (get_param_value(buf, sizeof(buf), "name", p)) {
1869 name = strdup(buf);
1871 if (!strcmp(device, "nic")) {
1872 static const char * const nic_params[] = {
1873 "vlan", "name", "macaddr", "model", NULL
1875 NICInfo *nd;
1876 uint8_t *macaddr;
1877 int idx = nic_get_free_idx();
1879 if (check_params(nic_params, p) < 0) {
1880 fprintf(stderr, "qemu: invalid parameter in '%s'\n", p);
1881 return -1;
1883 if (idx == -1 || nb_nics >= MAX_NICS) {
1884 fprintf(stderr, "Too Many NICs\n");
1885 ret = -1;
1886 goto out;
1888 nd = &nd_table[idx];
1889 macaddr = nd->macaddr;
1890 macaddr[0] = 0x52;
1891 macaddr[1] = 0x54;
1892 macaddr[2] = 0x00;
1893 macaddr[3] = 0x12;
1894 macaddr[4] = 0x34;
1895 macaddr[5] = 0x56 + idx;
1897 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
1898 if (parse_macaddr(macaddr, buf) < 0) {
1899 fprintf(stderr, "invalid syntax for ethernet address\n");
1900 ret = -1;
1901 goto out;
1904 if (get_param_value(buf, sizeof(buf), "model", p)) {
1905 nd->model = strdup(buf);
1907 nd->vlan = vlan;
1908 nd->name = name;
1909 nd->used = 1;
1910 name = NULL;
1911 nb_nics++;
1912 vlan->nb_guest_devs++;
1913 ret = idx;
1914 } else
1915 if (!strcmp(device, "none")) {
1916 if (*p != '\0') {
1917 fprintf(stderr, "qemu: 'none' takes no parameters\n");
1918 return -1;
1920 /* does nothing. It is needed to signal that no network cards
1921 are wanted */
1922 ret = 0;
1923 } else
1924 #ifdef CONFIG_SLIRP
1925 if (!strcmp(device, "user")) {
1926 static const char * const slirp_params[] = {
1927 "vlan", "name", "hostname", "restrict", "ip", NULL
1929 if (check_params(slirp_params, p) < 0) {
1930 fprintf(stderr, "qemu: invalid parameter in '%s'\n", p);
1931 return -1;
1933 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
1934 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
1936 if (get_param_value(buf, sizeof(buf), "restrict", p)) {
1937 slirp_restrict = (buf[0] == 'y') ? 1 : 0;
1939 if (get_param_value(buf, sizeof(buf), "ip", p)) {
1940 slirp_ip = strdup(buf);
1942 vlan->nb_host_devs++;
1943 ret = net_slirp_init(vlan, device, name);
1944 } else if (!strcmp(device, "channel")) {
1945 long port;
1946 char name[20], *devname;
1947 struct VMChannel *vmc;
1949 port = strtol(p, &devname, 10);
1950 devname++;
1951 if (port < 1 || port > 65535) {
1952 fprintf(stderr, "vmchannel wrong port number\n");
1953 ret = -1;
1954 goto out;
1956 vmc = malloc(sizeof(struct VMChannel));
1957 snprintf(name, 20, "vmchannel%ld", port);
1958 vmc->hd = qemu_chr_open(name, devname, NULL);
1959 if (!vmc->hd) {
1960 fprintf(stderr, "qemu: could not open vmchannel device"
1961 "'%s'\n", devname);
1962 ret = -1;
1963 goto out;
1965 vmc->port = port;
1966 slirp_add_exec(3, vmc->hd, 4, port);
1967 qemu_chr_add_handlers(vmc->hd, vmchannel_can_read, vmchannel_read,
1968 NULL, vmc);
1969 ret = 0;
1970 } else
1971 #endif
1972 #ifdef _WIN32
1973 if (!strcmp(device, "tap")) {
1974 static const char * const tap_params[] = {
1975 "vlan", "name", "ifname", NULL
1977 char ifname[64];
1979 if (check_params(tap_params, p) < 0) {
1980 fprintf(stderr, "qemu: invalid parameter in '%s'\n", p);
1981 return -1;
1983 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1984 fprintf(stderr, "tap: no interface name\n");
1985 ret = -1;
1986 goto out;
1988 vlan->nb_host_devs++;
1989 ret = tap_win32_init(vlan, device, name, ifname);
1990 } else
1991 #elif defined (_AIX)
1992 #else
1993 if (!strcmp(device, "tap")) {
1994 char ifname[64];
1995 char setup_script[1024], down_script[1024];
1996 int fd;
1997 vlan->nb_host_devs++;
1998 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1999 if (check_params(fd_params, p) < 0) {
2000 fprintf(stderr, "qemu: invalid parameter in '%s'\n", p);
2001 return -1;
2003 fd = strtol(buf, NULL, 0);
2004 fcntl(fd, F_SETFL, O_NONBLOCK);
2005 net_tap_fd_init(vlan, device, name, fd);
2006 ret = 0;
2007 } else {
2008 static const char * const tap_params[] = {
2009 "vlan", "name", "ifname", "script", "downscript", NULL
2011 if (check_params(tap_params, p) < 0) {
2012 fprintf(stderr, "qemu: invalid parameter in '%s'\n", p);
2013 return -1;
2015 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
2016 ifname[0] = '\0';
2018 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
2019 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
2021 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
2022 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
2024 ret = net_tap_init(vlan, device, name, ifname, setup_script, down_script);
2026 } else
2027 #endif
2028 if (!strcmp(device, "socket")) {
2029 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2030 int fd;
2031 if (check_params(fd_params, p) < 0) {
2032 fprintf(stderr, "qemu: invalid parameter in '%s'\n", p);
2033 return -1;
2035 fd = strtol(buf, NULL, 0);
2036 ret = -1;
2037 if (net_socket_fd_init(vlan, device, name, fd, 1))
2038 ret = 0;
2039 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
2040 static const char * const listen_params[] = {
2041 "vlan", "name", "listen", NULL
2043 if (check_params(listen_params, p) < 0) {
2044 fprintf(stderr, "qemu: invalid parameter in '%s'\n", p);
2045 return -1;
2047 ret = net_socket_listen_init(vlan, device, name, buf);
2048 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
2049 static const char * const connect_params[] = {
2050 "vlan", "name", "connect", NULL
2052 if (check_params(connect_params, p) < 0) {
2053 fprintf(stderr, "qemu: invalid parameter in '%s'\n", p);
2054 return -1;
2056 ret = net_socket_connect_init(vlan, device, name, buf);
2057 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
2058 static const char * const mcast_params[] = {
2059 "vlan", "name", "mcast", NULL
2061 if (check_params(mcast_params, p) < 0) {
2062 fprintf(stderr, "qemu: invalid parameter in '%s'\n", p);
2063 return -1;
2065 ret = net_socket_mcast_init(vlan, device, name, buf);
2066 } else {
2067 fprintf(stderr, "Unknown socket options: %s\n", p);
2068 ret = -1;
2069 goto out;
2071 vlan->nb_host_devs++;
2072 } else
2073 #ifdef CONFIG_VDE
2074 if (!strcmp(device, "vde")) {
2075 static const char * const vde_params[] = {
2076 "vlan", "name", "sock", "port", "group", "mode", NULL
2078 char vde_sock[1024], vde_group[512];
2079 int vde_port, vde_mode;
2081 if (check_params(vde_params, p) < 0) {
2082 fprintf(stderr, "qemu: invalid parameter in '%s'\n", p);
2083 return -1;
2085 vlan->nb_host_devs++;
2086 if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
2087 vde_sock[0] = '\0';
2089 if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
2090 vde_port = strtol(buf, NULL, 10);
2091 } else {
2092 vde_port = 0;
2094 if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
2095 vde_group[0] = '\0';
2097 if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
2098 vde_mode = strtol(buf, NULL, 8);
2099 } else {
2100 vde_mode = 0700;
2102 ret = net_vde_init(vlan, device, name, vde_sock, vde_port, vde_group, vde_mode);
2103 } else
2104 #endif
2105 if (!strcmp(device, "dump")) {
2106 int len = 65536;
2108 if (get_param_value(buf, sizeof(buf), "len", p) > 0) {
2109 len = strtol(buf, NULL, 0);
2111 if (!get_param_value(buf, sizeof(buf), "file", p)) {
2112 snprintf(buf, sizeof(buf), "qemu-vlan%d.pcap", vlan_id);
2114 ret = net_dump_init(vlan, device, name, buf, len);
2115 } else {
2116 fprintf(stderr, "Unknown network device: %s\n", device);
2117 ret = -1;
2118 goto out;
2120 if (ret < 0) {
2121 fprintf(stderr, "Could not initialize device '%s'\n", device);
2123 out:
2124 if (name)
2125 free(name);
2126 return ret;
2129 void net_client_uninit(NICInfo *nd)
2131 nd->vlan->nb_guest_devs--;
2132 nb_nics--;
2133 nd->used = 0;
2134 free((void *)nd->model);
2137 static int net_host_check_device(const char *device)
2139 int i;
2140 const char *valid_param_list[] = { "tap", "socket", "dump"
2141 #ifdef CONFIG_SLIRP
2142 ,"user"
2143 #endif
2144 #ifdef CONFIG_VDE
2145 ,"vde"
2146 #endif
2148 for (i = 0; i < sizeof(valid_param_list) / sizeof(char *); i++) {
2149 if (!strncmp(valid_param_list[i], device,
2150 strlen(valid_param_list[i])))
2151 return 1;
2154 return 0;
2157 void net_host_device_add(Monitor *mon, const char *device, const char *opts)
2159 if (!net_host_check_device(device)) {
2160 monitor_printf(mon, "invalid host network device %s\n", device);
2161 return;
2163 if (net_client_init(device, opts ? opts : "") < 0) {
2164 monitor_printf(mon, "adding host network device %s failed\n", device);
2168 void net_host_device_remove(Monitor *mon, int vlan_id, const char *device)
2170 VLANState *vlan;
2171 VLANClientState *vc;
2173 vlan = qemu_find_vlan(vlan_id);
2175 for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
2176 if (!strcmp(vc->name, device)) {
2177 break;
2181 if (!vc) {
2182 monitor_printf(mon, "can't find device %s\n", device);
2183 return;
2185 if (!net_host_check_device(vc->model)) {
2186 monitor_printf(mon, "invalid host network device %s\n", device);
2187 return;
2189 qemu_del_vlan_client(vc);
2192 int net_client_parse(const char *str)
2194 const char *p;
2195 char *q;
2196 char device[64];
2198 p = str;
2199 q = device;
2200 while (*p != '\0' && *p != ',') {
2201 if ((q - device) < sizeof(device) - 1)
2202 *q++ = *p;
2203 p++;
2205 *q = '\0';
2206 if (*p == ',')
2207 p++;
2209 return net_client_init(device, p);
2212 void do_info_network(Monitor *mon)
2214 VLANState *vlan;
2215 VLANClientState *vc;
2217 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2218 monitor_printf(mon, "VLAN %d devices:\n", vlan->id);
2219 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2220 monitor_printf(mon, " %s: %s\n", vc->name, vc->info_str);
2224 int do_set_link(Monitor *mon, const char *name, const char *up_or_down)
2226 VLANState *vlan;
2227 VLANClientState *vc = NULL;
2229 for (vlan = first_vlan; vlan != NULL; vlan = vlan->next)
2230 for (vc = vlan->first_client; vc != NULL; vc = vc->next)
2231 if (strcmp(vc->name, name) == 0)
2232 goto done;
2233 done:
2235 if (!vc) {
2236 monitor_printf(mon, "could not find network device '%s'", name);
2237 return 0;
2240 if (strcmp(up_or_down, "up") == 0)
2241 vc->link_down = 0;
2242 else if (strcmp(up_or_down, "down") == 0)
2243 vc->link_down = 1;
2244 else
2245 monitor_printf(mon, "invalid link status '%s'; only 'up' or 'down' "
2246 "valid\n", up_or_down);
2248 if (vc->link_status_changed)
2249 vc->link_status_changed(vc);
2251 return 1;
2254 void net_cleanup(void)
2256 VLANState *vlan;
2258 /* close network clients */
2259 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2260 VLANClientState *vc = vlan->first_client;
2262 while (vc) {
2263 VLANClientState *next = vc->next;
2265 qemu_del_vlan_client(vc);
2267 vc = next;
2272 void net_client_check(void)
2274 VLANState *vlan;
2276 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2277 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
2278 continue;
2279 if (vlan->nb_guest_devs == 0)
2280 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
2281 if (vlan->nb_host_devs == 0)
2282 fprintf(stderr,
2283 "Warning: vlan %d is not connected to host network\n",
2284 vlan->id);