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