musicpal: Fix regression caused by 6839 (Jan Kiszka)
[qemu] / 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 HOST_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 #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>
69
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"
74
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
95
96 #if defined(__OpenBSD__)
97 #include <util.h>
98 #endif
99
100 #if defined(CONFIG_VDE)
101 #include <libvdeplug.h>
102 #endif
103
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
112
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
122 #if defined(CONFIG_SLIRP)
123 #include "libslirp.h"
124 #endif
125
126
127 static VLANState *first_vlan;
128
129 /***********************************************************/
130 /* network device redirectors */
131
132 #if defined(DEBUG_NET) || defined(DEBUG_SLIRP)
133 static void hex_dump(FILE *f, const uint8_t *buf, int size)
134 {
135     int len, i, j, c;
136
137     for(i=0;i<size;i+=16) {
138         len = size - i;
139         if (len > 16)
140             len = 16;
141         fprintf(f, "%08x ", i);
142         for(j=0;j<16;j++) {
143             if (j < len)
144                 fprintf(f, " %02x", buf[i+j]);
145             else
146                 fprintf(f, "   ");
147         }
148         fprintf(f, " ");
149         for(j=0;j<len;j++) {
150             c = buf[i+j];
151             if (c < ' ' || c > '~')
152                 c = '.';
153             fprintf(f, "%c", c);
154         }
155         fprintf(f, "\n");
156     }
157 }
158 #endif
159
160 static int parse_macaddr(uint8_t *macaddr, const char *p)
161 {
162     int i;
163     char *last_char;
164     long int offset;
165
166     errno = 0;
167     offset = strtol(p, &last_char, 0);    
168     if (0 == errno && '\0' == *last_char &&
169             offset >= 0 && offset <= 0xFFFFFF) {
170         macaddr[3] = (offset & 0xFF0000) >> 16;
171         macaddr[4] = (offset & 0xFF00) >> 8;
172         macaddr[5] = offset & 0xFF;
173         return 0;
174     } else {
175         for(i = 0; i < 6; i++) {
176             macaddr[i] = strtol(p, (char **)&p, 16);
177             if (i == 5) {
178                 if (*p != '\0')
179                     return -1;
180             } else {
181                 if (*p != ':' && *p != '-')
182                     return -1;
183                 p++;
184             }
185         }
186         return 0;    
187     }
188
189     return -1;
190 }
191
192 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
193 {
194     const char *p, *p1;
195     int len;
196     p = *pp;
197     p1 = strchr(p, sep);
198     if (!p1)
199         return -1;
200     len = p1 - p;
201     p1++;
202     if (buf_size > 0) {
203         if (len > buf_size - 1)
204             len = buf_size - 1;
205         memcpy(buf, p, len);
206         buf[len] = '\0';
207     }
208     *pp = p1;
209     return 0;
210 }
211
212 int parse_host_src_port(struct sockaddr_in *haddr,
213                         struct sockaddr_in *saddr,
214                         const char *input_str)
215 {
216     char *str = strdup(input_str);
217     char *host_str = str;
218     char *src_str;
219     const char *src_str2;
220     char *ptr;
221
222     /*
223      * Chop off any extra arguments at the end of the string which
224      * would start with a comma, then fill in the src port information
225      * if it was provided else use the "any address" and "any port".
226      */
227     if ((ptr = strchr(str,',')))
228         *ptr = '\0';
229
230     if ((src_str = strchr(input_str,'@'))) {
231         *src_str = '\0';
232         src_str++;
233     }
234
235     if (parse_host_port(haddr, host_str) < 0)
236         goto fail;
237
238     src_str2 = src_str;
239     if (!src_str || *src_str == '\0')
240         src_str2 = ":0";
241
242     if (parse_host_port(saddr, src_str2) < 0)
243         goto fail;
244
245     free(str);
246     return(0);
247
248 fail:
249     free(str);
250     return -1;
251 }
252
253 int parse_host_port(struct sockaddr_in *saddr, const char *str)
254 {
255     char buf[512];
256     struct hostent *he;
257     const char *p, *r;
258     int port;
259
260     p = str;
261     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
262         return -1;
263     saddr->sin_family = AF_INET;
264     if (buf[0] == '\0') {
265         saddr->sin_addr.s_addr = 0;
266     } else {
267         if (qemu_isdigit(buf[0])) {
268             if (!inet_aton(buf, &saddr->sin_addr))
269                 return -1;
270         } else {
271             if ((he = gethostbyname(buf)) == NULL)
272                 return - 1;
273             saddr->sin_addr = *(struct in_addr *)he->h_addr;
274         }
275     }
276     port = strtol(p, (char **)&r, 0);
277     if (r == p)
278         return -1;
279     saddr->sin_port = htons(port);
280     return 0;
281 }
282
283 #if !defined(_WIN32) && 0
284 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
285 {
286     const char *p;
287     int len;
288
289     len = MIN(108, strlen(str));
290     p = strchr(str, ',');
291     if (p)
292         len = MIN(len, p - str);
293
294     memset(uaddr, 0, sizeof(*uaddr));
295
296     uaddr->sun_family = AF_UNIX;
297     memcpy(uaddr->sun_path, str, len);
298
299     return 0;
300 }
301 #endif
302
303 void qemu_format_nic_info_str(VLANClientState *vc, uint8_t macaddr[6])
304 {
305     snprintf(vc->info_str, sizeof(vc->info_str),
306              "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
307              vc->model,
308              macaddr[0], macaddr[1], macaddr[2],
309              macaddr[3], macaddr[4], macaddr[5]);
310 }
311
312 static char *assign_name(VLANClientState *vc1, const char *model)
313 {
314     VLANState *vlan;
315     char buf[256];
316     int id = 0;
317
318     for (vlan = first_vlan; vlan; vlan = vlan->next) {
319         VLANClientState *vc;
320
321         for (vc = vlan->first_client; vc; vc = vc->next)
322             if (vc != vc1 && strcmp(vc->model, model) == 0)
323                 id++;
324     }
325
326     snprintf(buf, sizeof(buf), "%s.%d", model, id);
327
328     return strdup(buf);
329 }
330
331 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
332                                       const char *model,
333                                       const char *name,
334                                       IOReadHandler *fd_read,
335                                       IOCanRWHandler *fd_can_read,
336                                       void *opaque)
337 {
338     VLANClientState *vc, **pvc;
339     vc = qemu_mallocz(sizeof(VLANClientState));
340     vc->model = strdup(model);
341     if (name)
342         vc->name = strdup(name);
343     else
344         vc->name = assign_name(vc, model);
345     vc->fd_read = fd_read;
346     vc->fd_can_read = fd_can_read;
347     vc->opaque = opaque;
348     vc->vlan = vlan;
349
350     vc->next = NULL;
351     pvc = &vlan->first_client;
352     while (*pvc != NULL)
353         pvc = &(*pvc)->next;
354     *pvc = vc;
355     return vc;
356 }
357
358 void qemu_del_vlan_client(VLANClientState *vc)
359 {
360     VLANClientState **pvc = &vc->vlan->first_client;
361
362     while (*pvc != NULL)
363         if (*pvc == vc) {
364             *pvc = vc->next;
365             free(vc->name);
366             free(vc->model);
367             free(vc);
368             break;
369         } else
370             pvc = &(*pvc)->next;
371 }
372
373 VLANClientState *qemu_find_vlan_client(VLANState *vlan, void *opaque)
374 {
375     VLANClientState **pvc = &vlan->first_client;
376
377     while (*pvc != NULL)
378         if ((*pvc)->opaque == opaque)
379             return *pvc;
380         else
381             pvc = &(*pvc)->next;
382
383     return NULL;
384 }
385
386 int qemu_can_send_packet(VLANClientState *vc1)
387 {
388     VLANState *vlan = vc1->vlan;
389     VLANClientState *vc;
390
391     for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
392         if (vc != vc1) {
393             if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
394                 return 1;
395         }
396     }
397     return 0;
398 }
399
400 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
401 {
402     VLANState *vlan = vc1->vlan;
403     VLANClientState *vc;
404
405     if (vc1->link_down)
406         return;
407
408 #ifdef DEBUG_NET
409     printf("vlan %d send:\n", vlan->id);
410     hex_dump(stdout, buf, size);
411 #endif
412     for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
413         if (vc != vc1 && !vc->link_down) {
414             vc->fd_read(vc->opaque, buf, size);
415         }
416     }
417 }
418
419 static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
420                                int iovcnt)
421 {
422     uint8_t buffer[4096];
423     size_t offset = 0;
424     int i;
425
426     for (i = 0; i < iovcnt; i++) {
427         size_t len;
428
429         len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
430         memcpy(buffer + offset, iov[i].iov_base, len);
431         offset += len;
432     }
433
434     vc->fd_read(vc->opaque, buffer, offset);
435
436     return offset;
437 }
438
439 static ssize_t calc_iov_length(const struct iovec *iov, int iovcnt)
440 {
441     size_t offset = 0;
442     int i;
443
444     for (i = 0; i < iovcnt; i++)
445         offset += iov[i].iov_len;
446     return offset;
447 }
448
449 ssize_t qemu_sendv_packet(VLANClientState *vc1, const struct iovec *iov,
450                           int iovcnt)
451 {
452     VLANState *vlan = vc1->vlan;
453     VLANClientState *vc;
454     ssize_t max_len = 0;
455
456     if (vc1->link_down)
457         return calc_iov_length(iov, iovcnt);
458
459     for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
460         ssize_t len = 0;
461
462         if (vc == vc1)
463             continue;
464
465         if (vc->link_down)
466             len = calc_iov_length(iov, iovcnt);
467         if (vc->fd_readv)
468             len = vc->fd_readv(vc->opaque, iov, iovcnt);
469         else if (vc->fd_read)
470             len = vc_sendv_compat(vc, iov, iovcnt);
471
472         max_len = MAX(max_len, len);
473     }
474
475     return max_len;
476 }
477
478 #if defined(CONFIG_SLIRP)
479
480 /* slirp network adapter */
481
482 static int slirp_inited;
483 static int slirp_restrict;
484 static char *slirp_ip;
485 static VLANClientState *slirp_vc;
486
487 int slirp_can_output(void)
488 {
489     return !slirp_vc || qemu_can_send_packet(slirp_vc);
490 }
491
492 void slirp_output(const uint8_t *pkt, int pkt_len)
493 {
494 #ifdef DEBUG_SLIRP
495     printf("slirp output:\n");
496     hex_dump(stdout, pkt, pkt_len);
497 #endif
498     if (!slirp_vc)
499         return;
500     qemu_send_packet(slirp_vc, pkt, pkt_len);
501 }
502
503 int slirp_is_inited(void)
504 {
505     return slirp_inited;
506 }
507
508 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
509 {
510 #ifdef DEBUG_SLIRP
511     printf("slirp input:\n");
512     hex_dump(stdout, buf, size);
513 #endif
514     slirp_input(buf, size);
515 }
516
517 static int net_slirp_init(VLANState *vlan, const char *model, const char *name)
518 {
519     if (!slirp_inited) {
520         slirp_inited = 1;
521         slirp_init(slirp_restrict, slirp_ip);
522     }
523     slirp_vc = qemu_new_vlan_client(vlan, model, name,
524                                     slirp_receive, NULL, NULL);
525     slirp_vc->info_str[0] = '\0';
526     return 0;
527 }
528
529 void net_slirp_redir(const char *redir_str)
530 {
531     int is_udp;
532     char buf[256], *r;
533     const char *p;
534     struct in_addr guest_addr;
535     int host_port, guest_port;
536
537     if (!slirp_inited) {
538         slirp_inited = 1;
539         slirp_init(slirp_restrict, slirp_ip);
540     }
541
542     p = redir_str;
543     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
544         goto fail;
545     if (!strcmp(buf, "tcp")) {
546         is_udp = 0;
547     } else if (!strcmp(buf, "udp")) {
548         is_udp = 1;
549     } else {
550         goto fail;
551     }
552
553     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
554         goto fail;
555     host_port = strtol(buf, &r, 0);
556     if (r == buf)
557         goto fail;
558
559     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
560         goto fail;
561     if (buf[0] == '\0') {
562         pstrcpy(buf, sizeof(buf), "10.0.2.15");
563     }
564     if (!inet_aton(buf, &guest_addr))
565         goto fail;
566
567     guest_port = strtol(p, &r, 0);
568     if (r == p)
569         goto fail;
570
571     if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
572         fprintf(stderr, "qemu: could not set up redirection\n");
573         exit(1);
574     }
575     return;
576  fail:
577     fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
578     exit(1);
579 }
580
581 #ifndef _WIN32
582
583 static char smb_dir[1024];
584
585 static void erase_dir(char *dir_name)
586 {
587     DIR *d;
588     struct dirent *de;
589     char filename[1024];
590
591     /* erase all the files in the directory */
592     if ((d = opendir(dir_name)) != NULL) {
593         for(;;) {
594             de = readdir(d);
595             if (!de)
596                 break;
597             if (strcmp(de->d_name, ".") != 0 &&
598                 strcmp(de->d_name, "..") != 0) {
599                 snprintf(filename, sizeof(filename), "%s/%s",
600                          smb_dir, de->d_name);
601                 if (unlink(filename) != 0)  /* is it a directory? */
602                     erase_dir(filename);
603             }
604         }
605         closedir(d);
606         rmdir(dir_name);
607     }
608 }
609
610 /* automatic user mode samba server configuration */
611 static void smb_exit(void)
612 {
613     erase_dir(smb_dir);
614 }
615
616 /* automatic user mode samba server configuration */
617 void net_slirp_smb(const char *exported_dir)
618 {
619     char smb_conf[1024];
620     char smb_cmdline[1024];
621     FILE *f;
622
623     if (!slirp_inited) {
624         slirp_inited = 1;
625         slirp_init(slirp_restrict, slirp_ip);
626     }
627
628     /* XXX: better tmp dir construction */
629     snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
630     if (mkdir(smb_dir, 0700) < 0) {
631         fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
632         exit(1);
633     }
634     snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
635
636     f = fopen(smb_conf, "w");
637     if (!f) {
638         fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
639         exit(1);
640     }
641     fprintf(f,
642             "[global]\n"
643             "private dir=%s\n"
644             "smb ports=0\n"
645             "socket address=127.0.0.1\n"
646             "pid directory=%s\n"
647             "lock directory=%s\n"
648             "log file=%s/log.smbd\n"
649             "smb passwd file=%s/smbpasswd\n"
650             "security = share\n"
651             "[qemu]\n"
652             "path=%s\n"
653             "read only=no\n"
654             "guest ok=yes\n",
655             smb_dir,
656             smb_dir,
657             smb_dir,
658             smb_dir,
659             smb_dir,
660             exported_dir
661             );
662     fclose(f);
663     atexit(smb_exit);
664
665     snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
666              SMBD_COMMAND, smb_conf);
667
668     slirp_add_exec(0, smb_cmdline, 4, 139);
669 }
670
671 #endif /* !defined(_WIN32) */
672 void do_info_slirp(Monitor *mon)
673 {
674     slirp_stats();
675 }
676
677 struct VMChannel {
678     CharDriverState *hd;
679     int port;
680 };
681
682 static int vmchannel_can_read(void *opaque)
683 {
684     struct VMChannel *vmc = (struct VMChannel*)opaque;
685     return slirp_socket_can_recv(4, vmc->port);
686 }
687
688 static void vmchannel_read(void *opaque, const uint8_t *buf, int size)
689 {
690     struct VMChannel *vmc = (struct VMChannel*)opaque;
691     slirp_socket_recv(4, vmc->port, buf, size);
692 }
693
694 #endif /* CONFIG_SLIRP */
695
696 #if !defined(_WIN32)
697
698 typedef struct TAPState {
699     VLANClientState *vc;
700     int fd;
701     char down_script[1024];
702     char down_script_arg[128];
703 } TAPState;
704
705 #ifdef HAVE_IOVEC
706 static ssize_t tap_receive_iov(void *opaque, const struct iovec *iov,
707                                int iovcnt)
708 {
709     TAPState *s = opaque;
710     ssize_t len;
711
712     do {
713         len = writev(s->fd, iov, iovcnt);
714     } while (len == -1 && (errno == EINTR || errno == EAGAIN));
715
716     return len;
717 }
718 #endif
719
720 static void tap_receive(void *opaque, const uint8_t *buf, int size)
721 {
722     TAPState *s = opaque;
723     int ret;
724     for(;;) {
725         ret = write(s->fd, buf, size);
726         if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
727         } else {
728             break;
729         }
730     }
731 }
732
733 static void tap_send(void *opaque)
734 {
735     TAPState *s = opaque;
736     uint8_t buf[4096];
737     int size;
738
739 #ifdef __sun__
740     struct strbuf sbuf;
741     int f = 0;
742     sbuf.maxlen = sizeof(buf);
743     sbuf.buf = buf;
744     size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
745 #else
746     size = read(s->fd, buf, sizeof(buf));
747 #endif
748     if (size > 0) {
749         qemu_send_packet(s->vc, buf, size);
750     }
751 }
752
753 /* fd support */
754
755 static TAPState *net_tap_fd_init(VLANState *vlan,
756                                  const char *model,
757                                  const char *name,
758                                  int fd)
759 {
760     TAPState *s;
761
762     s = qemu_mallocz(sizeof(TAPState));
763     s->fd = fd;
764     s->vc = qemu_new_vlan_client(vlan, model, name, tap_receive, NULL, s);
765 #ifdef HAVE_IOVEC
766     s->vc->fd_readv = tap_receive_iov;
767 #endif
768     qemu_set_fd_handler(s->fd, tap_send, NULL, s);
769     snprintf(s->vc->info_str, sizeof(s->vc->info_str), "fd=%d", fd);
770     return s;
771 }
772
773 #if defined (HOST_BSD) || defined (__FreeBSD_kernel__)
774 static int tap_open(char *ifname, int ifname_size)
775 {
776     int fd;
777     char *dev;
778     struct stat s;
779
780     TFR(fd = open("/dev/tap", O_RDWR));
781     if (fd < 0) {
782         fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
783         return -1;
784     }
785
786     fstat(fd, &s);
787     dev = devname(s.st_rdev, S_IFCHR);
788     pstrcpy(ifname, ifname_size, dev);
789
790     fcntl(fd, F_SETFL, O_NONBLOCK);
791     return fd;
792 }
793 #elif defined(__sun__)
794 #define TUNNEWPPA       (('T'<<16) | 0x0001)
795 /*
796  * Allocate TAP device, returns opened fd.
797  * Stores dev name in the first arg(must be large enough).
798  */
799 int tap_alloc(char *dev, size_t dev_size)
800 {
801     int tap_fd, if_fd, ppa = -1;
802     static int ip_fd = 0;
803     char *ptr;
804
805     static int arp_fd = 0;
806     int ip_muxid, arp_muxid;
807     struct strioctl  strioc_if, strioc_ppa;
808     int link_type = I_PLINK;;
809     struct lifreq ifr;
810     char actual_name[32] = "";
811
812     memset(&ifr, 0x0, sizeof(ifr));
813
814     if( *dev ){
815        ptr = dev;
816        while( *ptr && !qemu_isdigit((int)*ptr) ) ptr++;
817        ppa = atoi(ptr);
818     }
819
820     /* Check if IP device was opened */
821     if( ip_fd )
822        close(ip_fd);
823
824     TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
825     if (ip_fd < 0) {
826        syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
827        return -1;
828     }
829
830     TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
831     if (tap_fd < 0) {
832        syslog(LOG_ERR, "Can't open /dev/tap");
833        return -1;
834     }
835
836     /* Assign a new PPA and get its unit number. */
837     strioc_ppa.ic_cmd = TUNNEWPPA;
838     strioc_ppa.ic_timout = 0;
839     strioc_ppa.ic_len = sizeof(ppa);
840     strioc_ppa.ic_dp = (char *)&ppa;
841     if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
842        syslog (LOG_ERR, "Can't assign new interface");
843
844     TFR(if_fd = open("/dev/tap", O_RDWR, 0));
845     if (if_fd < 0) {
846        syslog(LOG_ERR, "Can't open /dev/tap (2)");
847        return -1;
848     }
849     if(ioctl(if_fd, I_PUSH, "ip") < 0){
850        syslog(LOG_ERR, "Can't push IP module");
851        return -1;
852     }
853
854     if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
855         syslog(LOG_ERR, "Can't get flags\n");
856
857     snprintf (actual_name, 32, "tap%d", ppa);
858     pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
859
860     ifr.lifr_ppa = ppa;
861     /* Assign ppa according to the unit number returned by tun device */
862
863     if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
864         syslog (LOG_ERR, "Can't set PPA %d", ppa);
865     if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
866         syslog (LOG_ERR, "Can't get flags\n");
867     /* Push arp module to if_fd */
868     if (ioctl (if_fd, I_PUSH, "arp") < 0)
869         syslog (LOG_ERR, "Can't push ARP module (2)");
870
871     /* Push arp module to ip_fd */
872     if (ioctl (ip_fd, I_POP, NULL) < 0)
873         syslog (LOG_ERR, "I_POP failed\n");
874     if (ioctl (ip_fd, I_PUSH, "arp") < 0)
875         syslog (LOG_ERR, "Can't push ARP module (3)\n");
876     /* Open arp_fd */
877     TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
878     if (arp_fd < 0)
879        syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
880
881     /* Set ifname to arp */
882     strioc_if.ic_cmd = SIOCSLIFNAME;
883     strioc_if.ic_timout = 0;
884     strioc_if.ic_len = sizeof(ifr);
885     strioc_if.ic_dp = (char *)&ifr;
886     if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
887         syslog (LOG_ERR, "Can't set ifname to arp\n");
888     }
889
890     if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
891        syslog(LOG_ERR, "Can't link TAP device to IP");
892        return -1;
893     }
894
895     if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
896         syslog (LOG_ERR, "Can't link TAP device to ARP");
897
898     close (if_fd);
899
900     memset(&ifr, 0x0, sizeof(ifr));
901     pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
902     ifr.lifr_ip_muxid  = ip_muxid;
903     ifr.lifr_arp_muxid = arp_muxid;
904
905     if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
906     {
907       ioctl (ip_fd, I_PUNLINK , arp_muxid);
908       ioctl (ip_fd, I_PUNLINK, ip_muxid);
909       syslog (LOG_ERR, "Can't set multiplexor id");
910     }
911
912     snprintf(dev, dev_size, "tap%d", ppa);
913     return tap_fd;
914 }
915
916 static int tap_open(char *ifname, int ifname_size)
917 {
918     char  dev[10]="";
919     int fd;
920     if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
921        fprintf(stderr, "Cannot allocate TAP device\n");
922        return -1;
923     }
924     pstrcpy(ifname, ifname_size, dev);
925     fcntl(fd, F_SETFL, O_NONBLOCK);
926     return fd;
927 }
928 #elif defined (_AIX)
929 static int tap_open(char *ifname, int ifname_size)
930 {
931     fprintf (stderr, "no tap on AIX\n");
932     return -1;
933 }
934 #else
935 static int tap_open(char *ifname, int ifname_size)
936 {
937     struct ifreq ifr;
938     int fd, ret;
939
940     TFR(fd = open("/dev/net/tun", O_RDWR));
941     if (fd < 0) {
942         fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
943         return -1;
944     }
945     memset(&ifr, 0, sizeof(ifr));
946     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
947     if (ifname[0] != '\0')
948         pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
949     else
950         pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
951     ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
952     if (ret != 0) {
953         fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
954         close(fd);
955         return -1;
956     }
957     pstrcpy(ifname, ifname_size, ifr.ifr_name);
958     fcntl(fd, F_SETFL, O_NONBLOCK);
959     return fd;
960 }
961 #endif
962
963 static int launch_script(const char *setup_script, const char *ifname, int fd)
964 {
965     int pid, status;
966     char *args[3];
967     char **parg;
968
969         /* try to launch network script */
970         pid = fork();
971         if (pid >= 0) {
972             if (pid == 0) {
973                 int open_max = sysconf (_SC_OPEN_MAX), i;
974                 for (i = 0; i < open_max; i++)
975                     if (i != STDIN_FILENO &&
976                         i != STDOUT_FILENO &&
977                         i != STDERR_FILENO &&
978                         i != fd)
979                         close(i);
980
981                 parg = args;
982                 *parg++ = (char *)setup_script;
983                 *parg++ = (char *)ifname;
984                 *parg++ = NULL;
985                 execv(setup_script, args);
986                 _exit(1);
987             }
988             while (waitpid(pid, &status, 0) != pid);
989             if (!WIFEXITED(status) ||
990                 WEXITSTATUS(status) != 0) {
991                 fprintf(stderr, "%s: could not launch network script\n",
992                         setup_script);
993                 return -1;
994             }
995         }
996     return 0;
997 }
998
999 static int net_tap_init(VLANState *vlan, const char *model,
1000                         const char *name, const char *ifname1,
1001                         const char *setup_script, const char *down_script)
1002 {
1003     TAPState *s;
1004     int fd;
1005     char ifname[128];
1006
1007     if (ifname1 != NULL)
1008         pstrcpy(ifname, sizeof(ifname), ifname1);
1009     else
1010         ifname[0] = '\0';
1011     TFR(fd = tap_open(ifname, sizeof(ifname)));
1012     if (fd < 0)
1013         return -1;
1014
1015     if (!setup_script || !strcmp(setup_script, "no"))
1016         setup_script = "";
1017     if (setup_script[0] != '\0') {
1018         if (launch_script(setup_script, ifname, fd))
1019             return -1;
1020     }
1021     s = net_tap_fd_init(vlan, model, name, fd);
1022     if (!s)
1023         return -1;
1024     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1025              "ifname=%s,script=%s,downscript=%s",
1026              ifname, setup_script, down_script);
1027     if (down_script && strcmp(down_script, "no")) {
1028         snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
1029         snprintf(s->down_script_arg, sizeof(s->down_script_arg), "%s", ifname);
1030     }
1031     return 0;
1032 }
1033
1034 #endif /* !_WIN32 */
1035
1036 #if defined(CONFIG_VDE)
1037 typedef struct VDEState {
1038     VLANClientState *vc;
1039     VDECONN *vde;
1040 } VDEState;
1041
1042 static void vde_to_qemu(void *opaque)
1043 {
1044     VDEState *s = opaque;
1045     uint8_t buf[4096];
1046     int size;
1047
1048     size = vde_recv(s->vde, buf, sizeof(buf), 0);
1049     if (size > 0) {
1050         qemu_send_packet(s->vc, buf, size);
1051     }
1052 }
1053
1054 static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
1055 {
1056     VDEState *s = opaque;
1057     int ret;
1058     for(;;) {
1059         ret = vde_send(s->vde, buf, size, 0);
1060         if (ret < 0 && errno == EINTR) {
1061         } else {
1062             break;
1063         }
1064     }
1065 }
1066
1067 static int net_vde_init(VLANState *vlan, const char *model,
1068                         const char *name, const char *sock,
1069                         int port, const char *group, int mode)
1070 {
1071     VDEState *s;
1072     char *init_group = strlen(group) ? (char *)group : NULL;
1073     char *init_sock = strlen(sock) ? (char *)sock : NULL;
1074
1075     struct vde_open_args args = {
1076         .port = port,
1077         .group = init_group,
1078         .mode = mode,
1079     };
1080
1081     s = qemu_mallocz(sizeof(VDEState));
1082     s->vde = vde_open(init_sock, "QEMU", &args);
1083     if (!s->vde){
1084         free(s);
1085         return -1;
1086     }
1087     s->vc = qemu_new_vlan_client(vlan, model, name, vde_from_qemu, NULL, s);
1088     qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
1089     snprintf(s->vc->info_str, sizeof(s->vc->info_str), "sock=%s,fd=%d",
1090              sock, vde_datafd(s->vde));
1091     return 0;
1092 }
1093 #endif
1094
1095 /* network connection */
1096 typedef struct NetSocketState {
1097     VLANClientState *vc;
1098     int fd;
1099     int state; /* 0 = getting length, 1 = getting data */
1100     unsigned int index;
1101     unsigned int packet_len;
1102     uint8_t buf[4096];
1103     struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
1104 } NetSocketState;
1105
1106 typedef struct NetSocketListenState {
1107     VLANState *vlan;
1108     char *model;
1109     char *name;
1110     int fd;
1111 } NetSocketListenState;
1112
1113 /* XXX: we consider we can send the whole packet without blocking */
1114 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
1115 {
1116     NetSocketState *s = opaque;
1117     uint32_t len;
1118     len = htonl(size);
1119
1120     send_all(s->fd, (const uint8_t *)&len, sizeof(len));
1121     send_all(s->fd, buf, size);
1122 }
1123
1124 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
1125 {
1126     NetSocketState *s = opaque;
1127     sendto(s->fd, buf, size, 0,
1128            (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
1129 }
1130
1131 static void net_socket_send(void *opaque)
1132 {
1133     NetSocketState *s = opaque;
1134     int size, err;
1135     unsigned l;
1136     uint8_t buf1[4096];
1137     const uint8_t *buf;
1138
1139     size = recv(s->fd, buf1, sizeof(buf1), 0);
1140     if (size < 0) {
1141         err = socket_error();
1142         if (err != EWOULDBLOCK)
1143             goto eoc;
1144     } else if (size == 0) {
1145         /* end of connection */
1146     eoc:
1147         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1148         closesocket(s->fd);
1149         return;
1150     }
1151     buf = buf1;
1152     while (size > 0) {
1153         /* reassemble a packet from the network */
1154         switch(s->state) {
1155         case 0:
1156             l = 4 - s->index;
1157             if (l > size)
1158                 l = size;
1159             memcpy(s->buf + s->index, buf, l);
1160             buf += l;
1161             size -= l;
1162             s->index += l;
1163             if (s->index == 4) {
1164                 /* got length */
1165                 s->packet_len = ntohl(*(uint32_t *)s->buf);
1166                 s->index = 0;
1167                 s->state = 1;
1168             }
1169             break;
1170         case 1:
1171             l = s->packet_len - s->index;
1172             if (l > size)
1173                 l = size;
1174             if (s->index + l <= sizeof(s->buf)) {
1175                 memcpy(s->buf + s->index, buf, l);
1176             } else {
1177                 fprintf(stderr, "serious error: oversized packet received,"
1178                     "connection terminated.\n");
1179                 s->state = 0;
1180                 goto eoc;
1181             }
1182
1183             s->index += l;
1184             buf += l;
1185             size -= l;
1186             if (s->index >= s->packet_len) {
1187                 qemu_send_packet(s->vc, s->buf, s->packet_len);
1188                 s->index = 0;
1189                 s->state = 0;
1190             }
1191             break;
1192         }
1193     }
1194 }
1195
1196 static void net_socket_send_dgram(void *opaque)
1197 {
1198     NetSocketState *s = opaque;
1199     int size;
1200
1201     size = recv(s->fd, s->buf, sizeof(s->buf), 0);
1202     if (size < 0)
1203         return;
1204     if (size == 0) {
1205         /* end of connection */
1206         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1207         return;
1208     }
1209     qemu_send_packet(s->vc, s->buf, size);
1210 }
1211
1212 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
1213 {
1214     struct ip_mreq imr;
1215     int fd;
1216     int val, ret;
1217     if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
1218         fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
1219                 inet_ntoa(mcastaddr->sin_addr),
1220                 (int)ntohl(mcastaddr->sin_addr.s_addr));
1221         return -1;
1222
1223     }
1224     fd = socket(PF_INET, SOCK_DGRAM, 0);
1225     if (fd < 0) {
1226         perror("socket(PF_INET, SOCK_DGRAM)");
1227         return -1;
1228     }
1229
1230     val = 1;
1231     ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1232                    (const char *)&val, sizeof(val));
1233     if (ret < 0) {
1234         perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
1235         goto fail;
1236     }
1237
1238     ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
1239     if (ret < 0) {
1240         perror("bind");
1241         goto fail;
1242     }
1243
1244     /* Add host to multicast group */
1245     imr.imr_multiaddr = mcastaddr->sin_addr;
1246     imr.imr_interface.s_addr = htonl(INADDR_ANY);
1247
1248     ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1249                      (const char *)&imr, sizeof(struct ip_mreq));
1250     if (ret < 0) {
1251         perror("setsockopt(IP_ADD_MEMBERSHIP)");
1252         goto fail;
1253     }
1254
1255     /* Force mcast msgs to loopback (eg. several QEMUs in same host */
1256     val = 1;
1257     ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1258                    (const char *)&val, sizeof(val));
1259     if (ret < 0) {
1260         perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
1261         goto fail;
1262     }
1263
1264     socket_set_nonblock(fd);
1265     return fd;
1266 fail:
1267     if (fd >= 0)
1268         closesocket(fd);
1269     return -1;
1270 }
1271
1272 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan,
1273                                                 const char *model,
1274                                                 const char *name,
1275                                                 int fd, int is_connected)
1276 {
1277     struct sockaddr_in saddr;
1278     int newfd;
1279     socklen_t saddr_len;
1280     NetSocketState *s;
1281
1282     /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
1283      * Because this may be "shared" socket from a "master" process, datagrams would be recv()
1284      * by ONLY ONE process: we must "clone" this dgram socket --jjo
1285      */
1286
1287     if (is_connected) {
1288         if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
1289             /* must be bound */
1290             if (saddr.sin_addr.s_addr==0) {
1291                 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
1292                         fd);
1293                 return NULL;
1294             }
1295             /* clone dgram socket */
1296             newfd = net_socket_mcast_create(&saddr);
1297             if (newfd < 0) {
1298                 /* error already reported by net_socket_mcast_create() */
1299                 close(fd);
1300                 return NULL;
1301             }
1302             /* clone newfd to fd, close newfd */
1303             dup2(newfd, fd);
1304             close(newfd);
1305
1306         } else {
1307             fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
1308                     fd, strerror(errno));
1309             return NULL;
1310         }
1311     }
1312
1313     s = qemu_mallocz(sizeof(NetSocketState));
1314     s->fd = fd;
1315
1316     s->vc = qemu_new_vlan_client(vlan, model, name, net_socket_receive_dgram, NULL, s);
1317     qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
1318
1319     /* mcast: save bound address as dst */
1320     if (is_connected) s->dgram_dst=saddr;
1321
1322     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1323             "socket: fd=%d (%s mcast=%s:%d)",
1324             fd, is_connected? "cloned" : "",
1325             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1326     return s;
1327 }
1328
1329 static void net_socket_connect(void *opaque)
1330 {
1331     NetSocketState *s = opaque;
1332     qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
1333 }
1334
1335 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan,
1336                                                  const char *model,
1337                                                  const char *name,
1338                                                  int fd, int is_connected)
1339 {
1340     NetSocketState *s;
1341     s = qemu_mallocz(sizeof(NetSocketState));
1342     s->fd = fd;
1343     s->vc = qemu_new_vlan_client(vlan, model, name,
1344                                  net_socket_receive, NULL, s);
1345     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1346              "socket: fd=%d", fd);
1347     if (is_connected) {
1348         net_socket_connect(s);
1349     } else {
1350         qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
1351     }
1352     return s;
1353 }
1354
1355 static NetSocketState *net_socket_fd_init(VLANState *vlan,
1356                                           const char *model, const char *name,
1357                                           int fd, int is_connected)
1358 {
1359     int so_type=-1, optlen=sizeof(so_type);
1360
1361     if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
1362         (socklen_t *)&optlen)< 0) {
1363         fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
1364         return NULL;
1365     }
1366     switch(so_type) {
1367     case SOCK_DGRAM:
1368         return net_socket_fd_init_dgram(vlan, model, name, fd, is_connected);
1369     case SOCK_STREAM:
1370         return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1371     default:
1372         /* who knows ... this could be a eg. a pty, do warn and continue as stream */
1373         fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
1374         return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1375     }
1376     return NULL;
1377 }
1378
1379 static void net_socket_accept(void *opaque)
1380 {
1381     NetSocketListenState *s = opaque;
1382     NetSocketState *s1;
1383     struct sockaddr_in saddr;
1384     socklen_t len;
1385     int fd;
1386
1387     for(;;) {
1388         len = sizeof(saddr);
1389         fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
1390         if (fd < 0 && errno != EINTR) {
1391             return;
1392         } else if (fd >= 0) {
1393             break;
1394         }
1395     }
1396     s1 = net_socket_fd_init(s->vlan, s->model, s->name, fd, 1);
1397     if (!s1) {
1398         closesocket(fd);
1399     } else {
1400         snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
1401                  "socket: connection from %s:%d",
1402                  inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1403     }
1404 }
1405
1406 static int net_socket_listen_init(VLANState *vlan,
1407                                   const char *model,
1408                                   const char *name,
1409                                   const char *host_str)
1410 {
1411     NetSocketListenState *s;
1412     int fd, val, ret;
1413     struct sockaddr_in saddr;
1414
1415     if (parse_host_port(&saddr, host_str) < 0)
1416         return -1;
1417
1418     s = qemu_mallocz(sizeof(NetSocketListenState));
1419
1420     fd = socket(PF_INET, SOCK_STREAM, 0);
1421     if (fd < 0) {
1422         perror("socket");
1423         return -1;
1424     }
1425     socket_set_nonblock(fd);
1426
1427     /* allow fast reuse */
1428     val = 1;
1429     setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
1430
1431     ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1432     if (ret < 0) {
1433         perror("bind");
1434         return -1;
1435     }
1436     ret = listen(fd, 0);
1437     if (ret < 0) {
1438         perror("listen");
1439         return -1;
1440     }
1441     s->vlan = vlan;
1442     s->model = strdup(model);
1443     s->name = strdup(name);
1444     s->fd = fd;
1445     qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
1446     return 0;
1447 }
1448
1449 static int net_socket_connect_init(VLANState *vlan,
1450                                    const char *model,
1451                                    const char *name,
1452                                    const char *host_str)
1453 {
1454     NetSocketState *s;
1455     int fd, connected, ret, err;
1456     struct sockaddr_in saddr;
1457
1458     if (parse_host_port(&saddr, host_str) < 0)
1459         return -1;
1460
1461     fd = socket(PF_INET, SOCK_STREAM, 0);
1462     if (fd < 0) {
1463         perror("socket");
1464         return -1;
1465     }
1466     socket_set_nonblock(fd);
1467
1468     connected = 0;
1469     for(;;) {
1470         ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1471         if (ret < 0) {
1472             err = socket_error();
1473             if (err == EINTR || err == EWOULDBLOCK) {
1474             } else if (err == EINPROGRESS) {
1475                 break;
1476 #ifdef _WIN32
1477             } else if (err == WSAEALREADY) {
1478                 break;
1479 #endif
1480             } else {
1481                 perror("connect");
1482                 closesocket(fd);
1483                 return -1;
1484             }
1485         } else {
1486             connected = 1;
1487             break;
1488         }
1489     }
1490     s = net_socket_fd_init(vlan, model, name, fd, connected);
1491     if (!s)
1492         return -1;
1493     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1494              "socket: connect to %s:%d",
1495              inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1496     return 0;
1497 }
1498
1499 static int net_socket_mcast_init(VLANState *vlan,
1500                                  const char *model,
1501                                  const char *name,
1502                                  const char *host_str)
1503 {
1504     NetSocketState *s;
1505     int fd;
1506     struct sockaddr_in saddr;
1507
1508     if (parse_host_port(&saddr, host_str) < 0)
1509         return -1;
1510
1511
1512     fd = net_socket_mcast_create(&saddr);
1513     if (fd < 0)
1514         return -1;
1515
1516     s = net_socket_fd_init(vlan, model, name, fd, 0);
1517     if (!s)
1518         return -1;
1519
1520     s->dgram_dst = saddr;
1521
1522     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1523              "socket: mcast=%s:%d",
1524              inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1525     return 0;
1526
1527 }
1528
1529 /* find or alloc a new VLAN */
1530 VLANState *qemu_find_vlan(int id)
1531 {
1532     VLANState **pvlan, *vlan;
1533     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1534         if (vlan->id == id)
1535             return vlan;
1536     }
1537     vlan = qemu_mallocz(sizeof(VLANState));
1538     vlan->id = id;
1539     vlan->next = NULL;
1540     pvlan = &first_vlan;
1541     while (*pvlan != NULL)
1542         pvlan = &(*pvlan)->next;
1543     *pvlan = vlan;
1544     return vlan;
1545 }
1546
1547 static int nic_get_free_idx(void)
1548 {
1549     int index;
1550
1551     for (index = 0; index < MAX_NICS; index++)
1552         if (!nd_table[index].used)
1553             return index;
1554     return -1;
1555 }
1556
1557 void qemu_check_nic_model(NICInfo *nd, const char *model)
1558 {
1559     const char *models[2];
1560
1561     models[0] = model;
1562     models[1] = NULL;
1563
1564     qemu_check_nic_model_list(nd, models, model);
1565 }
1566
1567 void qemu_check_nic_model_list(NICInfo *nd, const char * const *models,
1568                                const char *default_model)
1569 {
1570     int i, exit_status = 0;
1571
1572     if (!nd->model)
1573         nd->model = strdup(default_model);
1574
1575     if (strcmp(nd->model, "?") != 0) {
1576         for (i = 0 ; models[i]; i++)
1577             if (strcmp(nd->model, models[i]) == 0)
1578                 return;
1579
1580         fprintf(stderr, "qemu: Unsupported NIC model: %s\n", nd->model);
1581         exit_status = 1;
1582     }
1583
1584     fprintf(stderr, "qemu: Supported NIC models: ");
1585     for (i = 0 ; models[i]; i++)
1586         fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
1587
1588     exit(exit_status);
1589 }
1590
1591 int net_client_init(const char *device, const char *p)
1592 {
1593     char buf[1024];
1594     int vlan_id, ret;
1595     VLANState *vlan;
1596     char *name = NULL;
1597
1598     vlan_id = 0;
1599     if (get_param_value(buf, sizeof(buf), "vlan", p)) {
1600         vlan_id = strtol(buf, NULL, 0);
1601     }
1602     vlan = qemu_find_vlan(vlan_id);
1603     if (!vlan) {
1604         fprintf(stderr, "Could not create vlan %d\n", vlan_id);
1605         return -1;
1606     }
1607     if (get_param_value(buf, sizeof(buf), "name", p)) {
1608         name = strdup(buf);
1609     }
1610     if (!strcmp(device, "nic")) {
1611         NICInfo *nd;
1612         uint8_t *macaddr;
1613         int idx = nic_get_free_idx();
1614
1615         if (idx == -1 || nb_nics >= MAX_NICS) {
1616             fprintf(stderr, "Too Many NICs\n");
1617             return -1;
1618         }
1619         nd = &nd_table[idx];
1620         macaddr = nd->macaddr;
1621         macaddr[0] = 0x52;
1622         macaddr[1] = 0x54;
1623         macaddr[2] = 0x00;
1624         macaddr[3] = 0x12;
1625         macaddr[4] = 0x34;
1626         macaddr[5] = 0x56 + idx;
1627
1628         if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
1629             if (parse_macaddr(macaddr, buf) < 0) {
1630                 fprintf(stderr, "invalid syntax for ethernet address\n");
1631                 return -1;
1632             }
1633         }
1634         if (get_param_value(buf, sizeof(buf), "model", p)) {
1635             nd->model = strdup(buf);
1636         }
1637         nd->vlan = vlan;
1638         nd->name = name;
1639         nd->used = 1;
1640         name = NULL;
1641         nb_nics++;
1642         vlan->nb_guest_devs++;
1643         ret = idx;
1644     } else
1645     if (!strcmp(device, "none")) {
1646         /* does nothing. It is needed to signal that no network cards
1647            are wanted */
1648         ret = 0;
1649     } else
1650 #ifdef CONFIG_SLIRP
1651     if (!strcmp(device, "user")) {
1652         if (get_param_value(buf, sizeof(buf), "hostname", p)) {
1653             pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
1654         }
1655         if (get_param_value(buf, sizeof(buf), "restrict", p)) {
1656             slirp_restrict = (buf[0] == 'y') ? 1 : 0;
1657         }
1658         if (get_param_value(buf, sizeof(buf), "ip", p)) {
1659             slirp_ip = strdup(buf);
1660         }
1661         vlan->nb_host_devs++;
1662         ret = net_slirp_init(vlan, device, name);
1663     } else if (!strcmp(device, "channel")) {
1664         long port;
1665         char name[20], *devname;
1666         struct VMChannel *vmc;
1667
1668         port = strtol(p, &devname, 10);
1669         devname++;
1670         if (port < 1 || port > 65535) {
1671             fprintf(stderr, "vmchannel wrong port number\n"); 
1672             return -1;
1673         }
1674         vmc = malloc(sizeof(struct VMChannel));
1675         snprintf(name, 20, "vmchannel%ld", port);
1676         vmc->hd = qemu_chr_open(name, devname, NULL);
1677         if (!vmc->hd) {
1678             fprintf(stderr, "qemu: could not open vmchannel device"
1679                     "'%s'\n", devname);
1680             return -1;
1681         }
1682         vmc->port = port;
1683         slirp_add_exec(3, vmc->hd, 4, port);
1684         qemu_chr_add_handlers(vmc->hd, vmchannel_can_read, vmchannel_read,
1685                 NULL, vmc);
1686         ret = 0;
1687     } else
1688 #endif
1689 #ifdef _WIN32
1690     if (!strcmp(device, "tap")) {
1691         char ifname[64];
1692         if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1693             fprintf(stderr, "tap: no interface name\n");
1694             return -1;
1695         }
1696         vlan->nb_host_devs++;
1697         ret = tap_win32_init(vlan, device, name, ifname);
1698     } else
1699 #elif defined (_AIX)
1700 #else
1701     if (!strcmp(device, "tap")) {
1702         char ifname[64];
1703         char setup_script[1024], down_script[1024];
1704         int fd;
1705         vlan->nb_host_devs++;
1706         if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1707             fd = strtol(buf, NULL, 0);
1708             fcntl(fd, F_SETFL, O_NONBLOCK);
1709             ret = -1;
1710             if (net_tap_fd_init(vlan, device, name, fd))
1711                 ret = 0;
1712         } else {
1713             if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1714                 ifname[0] = '\0';
1715             }
1716             if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
1717                 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
1718             }
1719             if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
1720                 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
1721             }
1722             ret = net_tap_init(vlan, device, name, ifname, setup_script, down_script);
1723         }
1724     } else
1725 #endif
1726     if (!strcmp(device, "socket")) {
1727         if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1728             int fd;
1729             fd = strtol(buf, NULL, 0);
1730             ret = -1;
1731             if (net_socket_fd_init(vlan, device, name, fd, 1))
1732                 ret = 0;
1733         } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
1734             ret = net_socket_listen_init(vlan, device, name, buf);
1735         } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
1736             ret = net_socket_connect_init(vlan, device, name, buf);
1737         } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
1738             ret = net_socket_mcast_init(vlan, device, name, buf);
1739         } else {
1740             fprintf(stderr, "Unknown socket options: %s\n", p);
1741             return -1;
1742         }
1743         vlan->nb_host_devs++;
1744     } else
1745 #ifdef CONFIG_VDE
1746     if (!strcmp(device, "vde")) {
1747         char vde_sock[1024], vde_group[512];
1748         int vde_port, vde_mode;
1749         vlan->nb_host_devs++;
1750         if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
1751             vde_sock[0] = '\0';
1752         }
1753         if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
1754             vde_port = strtol(buf, NULL, 10);
1755         } else {
1756             vde_port = 0;
1757         }
1758         if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
1759             vde_group[0] = '\0';
1760         }
1761         if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
1762             vde_mode = strtol(buf, NULL, 8);
1763         } else {
1764             vde_mode = 0700;
1765         }
1766         ret = net_vde_init(vlan, device, name, vde_sock, vde_port, vde_group, vde_mode);
1767     } else
1768 #endif
1769     {
1770         fprintf(stderr, "Unknown network device: %s\n", device);
1771         if (name)
1772             free(name);
1773         return -1;
1774     }
1775     if (ret < 0) {
1776         fprintf(stderr, "Could not initialize device '%s'\n", device);
1777     }
1778     if (name)
1779         free(name);
1780     return ret;
1781 }
1782
1783 void net_client_uninit(NICInfo *nd)
1784 {
1785     nd->vlan->nb_guest_devs--;
1786     nb_nics--;
1787     nd->used = 0;
1788     free((void *)nd->model);
1789 }
1790
1791 static int net_host_check_device(const char *device)
1792 {
1793     int i;
1794     const char *valid_param_list[] = { "tap", "socket"
1795 #ifdef CONFIG_SLIRP
1796                                        ,"user"
1797 #endif
1798 #ifdef CONFIG_VDE
1799                                        ,"vde"
1800 #endif
1801     };
1802     for (i = 0; i < sizeof(valid_param_list) / sizeof(char *); i++) {
1803         if (!strncmp(valid_param_list[i], device,
1804                      strlen(valid_param_list[i])))
1805             return 1;
1806     }
1807
1808     return 0;
1809 }
1810
1811 void net_host_device_add(Monitor *mon, const char *device, const char *opts)
1812 {
1813     if (!net_host_check_device(device)) {
1814         monitor_printf(mon, "invalid host network device %s\n", device);
1815         return;
1816     }
1817     net_client_init(device, opts);
1818 }
1819
1820 void net_host_device_remove(Monitor *mon, int vlan_id, const char *device)
1821 {
1822     VLANState *vlan;
1823     VLANClientState *vc;
1824
1825     vlan = qemu_find_vlan(vlan_id);
1826     if (!vlan) {
1827         monitor_printf(mon, "can't find vlan %d\n", vlan_id);
1828         return;
1829     }
1830
1831    for(vc = vlan->first_client; vc != NULL; vc = vc->next)
1832         if (!strcmp(vc->name, device))
1833             break;
1834
1835     if (!vc) {
1836         monitor_printf(mon, "can't find device %s\n", device);
1837         return;
1838     }
1839     qemu_del_vlan_client(vc);
1840 }
1841
1842 int net_client_parse(const char *str)
1843 {
1844     const char *p;
1845     char *q;
1846     char device[64];
1847
1848     p = str;
1849     q = device;
1850     while (*p != '\0' && *p != ',') {
1851         if ((q - device) < sizeof(device) - 1)
1852             *q++ = *p;
1853         p++;
1854     }
1855     *q = '\0';
1856     if (*p == ',')
1857         p++;
1858
1859     return net_client_init(device, p);
1860 }
1861
1862 void do_info_network(Monitor *mon)
1863 {
1864     VLANState *vlan;
1865     VLANClientState *vc;
1866
1867     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1868         monitor_printf(mon, "VLAN %d devices:\n", vlan->id);
1869         for(vc = vlan->first_client; vc != NULL; vc = vc->next)
1870             monitor_printf(mon, "  %s: %s\n", vc->name, vc->info_str);
1871     }
1872 }
1873
1874 int do_set_link(Monitor *mon, const char *name, const char *up_or_down)
1875 {
1876     VLANState *vlan;
1877     VLANClientState *vc = NULL;
1878
1879     for (vlan = first_vlan; vlan != NULL; vlan = vlan->next)
1880         for (vc = vlan->first_client; vc != NULL; vc = vc->next)
1881             if (strcmp(vc->name, name) == 0)
1882                 goto done;
1883 done:
1884
1885     if (!vc) {
1886         monitor_printf(mon, "could not find network device '%s'", name);
1887         return 0;
1888     }
1889
1890     if (strcmp(up_or_down, "up") == 0)
1891         vc->link_down = 0;
1892     else if (strcmp(up_or_down, "down") == 0)
1893         vc->link_down = 1;
1894     else
1895         monitor_printf(mon, "invalid link status '%s'; only 'up' or 'down' "
1896                        "valid\n", up_or_down);
1897
1898     if (vc->link_status_changed)
1899         vc->link_status_changed(vc);
1900
1901     return 1;
1902 }
1903
1904 void net_cleanup(void)
1905 {
1906     VLANState *vlan;
1907
1908 #if !defined(_WIN32)
1909     /* close network clients */
1910     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1911         VLANClientState *vc;
1912
1913         for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
1914             if (vc->fd_read == tap_receive) {
1915                 TAPState *s = vc->opaque;
1916
1917                 if (s->down_script[0])
1918                     launch_script(s->down_script, s->down_script_arg, s->fd);
1919             }
1920 #if defined(CONFIG_VDE)
1921             if (vc->fd_read == vde_from_qemu) {
1922                 VDEState *s = vc->opaque;
1923                 vde_close(s->vde);
1924             }
1925 #endif
1926         }
1927     }
1928 #endif
1929 }
1930
1931 void net_client_check(void)
1932 {
1933     VLANState *vlan;
1934
1935     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1936         if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
1937             continue;
1938         if (vlan->nb_guest_devs == 0)
1939             fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
1940         if (vlan->nb_host_devs == 0)
1941             fprintf(stderr,
1942                     "Warning: vlan %d is not connected to host network\n",
1943                     vlan->id);
1944     }
1945 }