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