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