net-android.c revision ce0f4b02160ee72d7d2428867fe757bc37c68c98
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 HOST_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 (HOST_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 sendto(s->fd, (const void *)buf, size, 0,
1596                  (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
1597}
1598
1599static void net_socket_send(void *opaque)
1600{
1601    NetSocketState *s = opaque;
1602    int size, err;
1603    unsigned l;
1604    uint8_t buf1[4096];
1605    const uint8_t *buf;
1606
1607    size = recv(s->fd, (void *)buf1, sizeof(buf1), 0);
1608    if (size < 0) {
1609        err = socket_error();
1610        if (err != EWOULDBLOCK && err != EAGAIN)
1611            goto eoc;
1612    } else if (size == 0) {
1613        /* end of connection */
1614    eoc:
1615        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1616        closesocket(s->fd);
1617        return;
1618    }
1619    buf = buf1;
1620    while (size > 0) {
1621        /* reassemble a packet from the network */
1622        switch(s->state) {
1623        case 0:
1624            l = 4 - s->index;
1625            if (l > size)
1626                l = size;
1627            memcpy(s->buf + s->index, buf, l);
1628            buf += l;
1629            size -= l;
1630            s->index += l;
1631            if (s->index == 4) {
1632                /* got length */
1633                s->packet_len = ntohl(*(uint32_t *)s->buf);
1634                s->index = 0;
1635                s->state = 1;
1636            }
1637            break;
1638        case 1:
1639            l = s->packet_len - s->index;
1640            if (l > size)
1641                l = size;
1642            if (s->index + l <= sizeof(s->buf)) {
1643                memcpy(s->buf + s->index, buf, l);
1644            } else {
1645                fprintf(stderr, "serious error: oversized packet received,"
1646                    "connection terminated.\n");
1647                s->state = 0;
1648                goto eoc;
1649            }
1650
1651            s->index += l;
1652            buf += l;
1653            size -= l;
1654            if (s->index >= s->packet_len) {
1655                qemu_send_packet(s->vc, s->buf, s->packet_len);
1656                s->index = 0;
1657                s->state = 0;
1658            }
1659            break;
1660        }
1661    }
1662}
1663
1664static void net_socket_send_dgram(void *opaque)
1665{
1666    NetSocketState *s = opaque;
1667    int size;
1668
1669    size = recv(s->fd, (void *)s->buf, sizeof(s->buf), 0);
1670    if (size < 0)
1671        return;
1672    if (size == 0) {
1673        /* end of connection */
1674        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1675        return;
1676    }
1677    qemu_send_packet(s->vc, s->buf, size);
1678}
1679
1680static int net_socket_mcast_create(SockAddress *mcastaddr)
1681{
1682    int fd;
1683    int ret;
1684    if (!IN_MULTICAST(sock_address_get_ip(mcastaddr))) {
1685	fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
1686		sock_address_to_string(mcastaddr),
1687                sock_address_get_ip(mcastaddr));
1688	return -1;
1689
1690    }
1691    fd = socket_create_inet(SOCKET_DGRAM);
1692    if (fd < 0) {
1693        perror("socket(PF_INET, SOCK_DGRAM)");
1694        return -1;
1695    }
1696
1697    ret = socket_set_xreuseaddr(fd);
1698    if (ret < 0) {
1699	perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
1700	goto fail;
1701    }
1702
1703    ret = socket_bind(fd, mcastaddr);
1704    if (ret < 0) {
1705        perror("bind");
1706        goto fail;
1707    }
1708
1709    /* Add host to multicast group */
1710    ret = socket_mcast_inet_add_membership(fd, sock_address_get_ip(mcastaddr));
1711    if (ret < 0) {
1712	perror("setsockopt(IP_ADD_MEMBERSHIP)");
1713	goto fail;
1714    }
1715
1716    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
1717    ret = socket_mcast_inet_set_loop(fd, 1);
1718    if (ret < 0) {
1719	perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
1720	goto fail;
1721    }
1722
1723    socket_set_nonblock(fd);
1724    return fd;
1725fail:
1726    if (fd >= 0)
1727        socket_close(fd);
1728    return -1;
1729}
1730
1731static void net_socket_cleanup(VLANClientState *vc)
1732{
1733    NetSocketState *s = vc->opaque;
1734    qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1735    socket_close(s->fd);
1736    qemu_free(s);
1737}
1738
1739static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan,
1740                                                const char *model,
1741                                                const char *name,
1742                                                int fd, int is_connected)
1743{
1744    SockAddress  saddr;
1745    int newfd;
1746    NetSocketState *s;
1747
1748    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
1749     * Because this may be "shared" socket from a "master" process, datagrams would be recv()
1750     * by ONLY ONE process: we must "clone" this dgram socket --jjo
1751     */
1752
1753    if (is_connected) {
1754	if (socket_get_address(fd, &saddr) == 0) {
1755	    /* must be bound */
1756	    if (sock_address_get_ip(&saddr) == 0) {
1757		fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
1758			fd);
1759		return NULL;
1760	    }
1761	    /* clone dgram socket */
1762	    newfd = net_socket_mcast_create(&saddr);
1763	    if (newfd < 0) {
1764		/* error already reported by net_socket_mcast_create() */
1765		socket_close(fd);
1766		return NULL;
1767	    }
1768	    /* clone newfd to fd, close newfd */
1769	    dup2(newfd, fd);
1770	    socket_close(newfd);
1771
1772	} else {
1773	    fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
1774		    fd, strerror(errno));
1775	    return NULL;
1776	}
1777    }
1778
1779    s = qemu_mallocz(sizeof(NetSocketState));
1780    s->fd = fd;
1781
1782    s->vc = qemu_new_vlan_client(vlan, model, name, NULL, net_socket_receive_dgram,
1783                                 NULL, net_socket_cleanup, s);
1784    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
1785
1786    /* mcast: save bound address as dst */
1787    if (is_connected) s->dgram_dst=saddr;
1788
1789    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1790	    "socket: fd=%d (%s mcast=%s)",
1791	    fd, is_connected? "cloned" : "",
1792	    sock_address_to_string(&saddr));
1793    return s;
1794}
1795
1796static void net_socket_connect(void *opaque)
1797{
1798    NetSocketState *s = opaque;
1799    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
1800}
1801
1802static NetSocketState *net_socket_fd_init_stream(VLANState *vlan,
1803                                                 const char *model,
1804                                                 const char *name,
1805                                                 int fd, int is_connected)
1806{
1807    NetSocketState *s;
1808    s = qemu_mallocz(sizeof(NetSocketState));
1809    s->fd = fd;
1810    s->vc = qemu_new_vlan_client(vlan, model, name, NULL, net_socket_receive,
1811                                 NULL, net_socket_cleanup, s);
1812    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1813             "socket: fd=%d", fd);
1814    if (is_connected) {
1815        net_socket_connect(s);
1816    } else {
1817        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
1818    }
1819    return s;
1820}
1821
1822static NetSocketState *net_socket_fd_init(VLANState *vlan,
1823                                          const char *model, const char *name,
1824                                          int fd, int is_connected)
1825{
1826    SocketType  so_type = socket_get_type(fd);
1827
1828    switch(so_type) {
1829    case SOCKET_DGRAM:
1830        return net_socket_fd_init_dgram(vlan, model, name, fd, is_connected);
1831    case SOCKET_STREAM:
1832        return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1833    default:
1834        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
1835        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
1836        return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1837    }
1838    return NULL;
1839}
1840
1841static void net_socket_accept(void *opaque)
1842{
1843    NetSocketListenState *s = opaque;
1844    NetSocketState *s1;
1845    SockAddress  saddr;
1846    int fd;
1847
1848    for(;;) {
1849        fd = socket_accept(s->fd, &saddr);
1850        if (fd < 0) {
1851            return;
1852        } else if (fd >= 0) {
1853            break;
1854        }
1855    }
1856    s1 = net_socket_fd_init(s->vlan, s->model, s->name, fd, 1);
1857    if (!s1) {
1858        socket_close(fd);
1859    } else {
1860        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
1861                 "socket: connection from %s", sock_address_to_string(&saddr));
1862    }
1863}
1864
1865static int net_socket_listen_init(VLANState *vlan,
1866                                  const char *model,
1867                                  const char *name,
1868                                  const char *host_str)
1869{
1870    NetSocketListenState *s;
1871    int fd, ret;
1872    SockAddress  saddr;
1873
1874    if (parse_host_port(&saddr, host_str) < 0)
1875        return -1;
1876
1877    s = qemu_mallocz(sizeof(NetSocketListenState));
1878
1879    fd = socket_create_inet(SOCKET_STREAM);
1880    if (fd < 0) {
1881        perror("socket");
1882        return -1;
1883    }
1884    socket_set_nonblock(fd);
1885
1886    /* allow fast reuse */
1887    socket_set_xreuseaddr(fd);
1888
1889    ret = socket_bind(fd, &saddr);
1890    if (ret < 0) {
1891        perror("bind");
1892        return -1;
1893    }
1894    ret = socket_listen(fd, 0);
1895    if (ret < 0) {
1896        perror("listen");
1897        return -1;
1898    }
1899    s->vlan = vlan;
1900    s->model = strdup(model);
1901    s->name = name ? strdup(name) : NULL;
1902    s->fd = fd;
1903    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
1904    return 0;
1905}
1906
1907static int net_socket_connect_init(VLANState *vlan,
1908                                   const char *model,
1909                                   const char *name,
1910                                   const char *host_str)
1911{
1912    NetSocketState *s;
1913    int fd, connected, ret, err;
1914    SockAddress saddr;
1915
1916    if (parse_host_port(&saddr, host_str) < 0)
1917        return -1;
1918
1919    fd = socket_create_inet(SOCKET_STREAM);
1920    if (fd < 0) {
1921        perror("socket");
1922        return -1;
1923    }
1924    socket_set_nonblock(fd);
1925
1926    connected = 0;
1927    for(;;) {
1928        ret = socket_connect(fd, &saddr);
1929        if (ret < 0) {
1930            err = socket_error();
1931            if (err == EWOULDBLOCK || err == EAGAIN) {
1932            } else if (err == EINPROGRESS || err == EALREADY) {
1933                break;
1934            } else {
1935                perror("connect");
1936                socket_close(fd);
1937                return -1;
1938            }
1939        } else {
1940            connected = 1;
1941            break;
1942        }
1943    }
1944    s = net_socket_fd_init(vlan, model, name, fd, connected);
1945    if (!s)
1946        return -1;
1947    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1948             "socket: connect to %s",
1949             sock_address_to_string(&saddr));
1950    return 0;
1951}
1952
1953static int net_socket_mcast_init(VLANState *vlan,
1954                                 const char *model,
1955                                 const char *name,
1956                                 const char *host_str)
1957{
1958    NetSocketState *s;
1959    int fd;
1960    SockAddress saddr;
1961
1962    if (parse_host_port(&saddr, host_str) < 0)
1963        return -1;
1964
1965
1966    fd = net_socket_mcast_create(&saddr);
1967    if (fd < 0)
1968	return -1;
1969
1970    s = net_socket_fd_init(vlan, model, name, fd, 0);
1971    if (!s)
1972        return -1;
1973
1974    s->dgram_dst = saddr;
1975
1976    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1977             "socket: mcast=%s",
1978             sock_address_to_string(&saddr));
1979    return 0;
1980
1981}
1982
1983typedef struct DumpState {
1984    VLANClientState *pcap_vc;
1985    int fd;
1986    int pcap_caplen;
1987} DumpState;
1988
1989#define PCAP_MAGIC 0xa1b2c3d4
1990
1991struct pcap_file_hdr {
1992    uint32_t magic;
1993    uint16_t version_major;
1994    uint16_t version_minor;
1995    int32_t thiszone;
1996    uint32_t sigfigs;
1997    uint32_t snaplen;
1998    uint32_t linktype;
1999};
2000
2001struct pcap_sf_pkthdr {
2002    struct {
2003        int32_t tv_sec;
2004        int32_t tv_usec;
2005    } ts;
2006    uint32_t caplen;
2007    uint32_t len;
2008};
2009
2010static ssize_t dump_receive(VLANClientState *vc, const uint8_t *buf, size_t size)
2011{
2012    DumpState *s = vc->opaque;
2013    struct pcap_sf_pkthdr hdr;
2014    int64_t ts;
2015    int caplen;
2016
2017    /* Early return in case of previous error. */
2018    if (s->fd < 0) {
2019        return size;
2020    }
2021
2022    ts = muldiv64(qemu_get_clock(vm_clock), 1000000, ticks_per_sec);
2023    caplen = size > s->pcap_caplen ? s->pcap_caplen : size;
2024
2025    hdr.ts.tv_sec = ts / 1000000;
2026    hdr.ts.tv_usec = ts % 1000000;
2027    hdr.caplen = caplen;
2028    hdr.len = size;
2029    if (write(s->fd, &hdr, sizeof(hdr)) != sizeof(hdr) ||
2030        write(s->fd, buf, caplen) != caplen) {
2031        qemu_log("-net dump write error - stop dump\n");
2032        close(s->fd);
2033        s->fd = -1;
2034    }
2035
2036    return size;
2037}
2038
2039static void net_dump_cleanup(VLANClientState *vc)
2040{
2041    DumpState *s = vc->opaque;
2042
2043    close(s->fd);
2044    qemu_free(s);
2045}
2046
2047static int net_dump_init(Monitor *mon, VLANState *vlan, const char *device,
2048                         const char *name, const char *filename, int len)
2049{
2050    struct pcap_file_hdr hdr;
2051    DumpState *s;
2052
2053    s = qemu_malloc(sizeof(DumpState));
2054
2055    s->fd = open(filename, O_CREAT | O_WRONLY, 0644);
2056    if (s->fd < 0) {
2057        config_error(mon, "-net dump: can't open %s\n", filename);
2058        return -1;
2059    }
2060
2061    s->pcap_caplen = len;
2062
2063    hdr.magic = PCAP_MAGIC;
2064    hdr.version_major = 2;
2065    hdr.version_minor = 4;
2066    hdr.thiszone = 0;
2067    hdr.sigfigs = 0;
2068    hdr.snaplen = s->pcap_caplen;
2069    hdr.linktype = 1;
2070
2071    if (write(s->fd, &hdr, sizeof(hdr)) < sizeof(hdr)) {
2072        config_error(mon, "-net dump write error: %s\n", strerror(errno));
2073        close(s->fd);
2074        qemu_free(s);
2075        return -1;
2076    }
2077
2078    s->pcap_vc = qemu_new_vlan_client(vlan, device, name, NULL, dump_receive, NULL,
2079                                      net_dump_cleanup, s);
2080    snprintf(s->pcap_vc->info_str, sizeof(s->pcap_vc->info_str),
2081             "dump to %s (len=%d)", filename, len);
2082    return 0;
2083}
2084
2085/* find or alloc a new VLAN */
2086VLANState *qemu_find_vlan(int id)
2087{
2088    VLANState **pvlan, *vlan;
2089    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2090        if (vlan->id == id)
2091            return vlan;
2092    }
2093    vlan = qemu_mallocz(sizeof(VLANState));
2094    vlan->id = id;
2095    vlan->next = NULL;
2096    pvlan = &first_vlan;
2097    while (*pvlan != NULL)
2098        pvlan = &(*pvlan)->next;
2099    *pvlan = vlan;
2100    return vlan;
2101}
2102
2103static int nic_get_free_idx(void)
2104{
2105    int index;
2106
2107    for (index = 0; index < MAX_NICS; index++)
2108        if (!nd_table[index].used)
2109            return index;
2110    return -1;
2111}
2112
2113void qemu_check_nic_model(NICInfo *nd, const char *model)
2114{
2115    const char *models[2];
2116
2117    models[0] = model;
2118    models[1] = NULL;
2119
2120    qemu_check_nic_model_list(nd, models, model);
2121}
2122
2123void qemu_check_nic_model_list(NICInfo *nd, const char * const *models,
2124                               const char *default_model)
2125{
2126    int i, exit_status = 0;
2127
2128    if (!nd->model)
2129        nd->model = strdup(default_model);
2130
2131    if (strcmp(nd->model, "?") != 0) {
2132        for (i = 0 ; models[i]; i++)
2133            if (strcmp(nd->model, models[i]) == 0)
2134                return;
2135
2136        fprintf(stderr, "qemu: Unsupported NIC model: %s\n", nd->model);
2137        exit_status = 1;
2138    }
2139
2140    fprintf(stderr, "qemu: Supported NIC models: ");
2141    for (i = 0 ; models[i]; i++)
2142        fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
2143
2144    exit(exit_status);
2145}
2146
2147int net_client_init(Monitor *mon, const char *device, const char *p)
2148{
2149    static const char * const fd_params[] = {
2150        "vlan", "name", "fd", NULL
2151    };
2152    char buf[1024];
2153    int vlan_id, ret;
2154    VLANState *vlan;
2155    char *name = NULL;
2156
2157    vlan_id = 0;
2158    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
2159        vlan_id = strtol(buf, NULL, 0);
2160    }
2161    vlan = qemu_find_vlan(vlan_id);
2162
2163    if (get_param_value(buf, sizeof(buf), "name", p)) {
2164        name = qemu_strdup(buf);
2165    }
2166    if (!strcmp(device, "nic")) {
2167        static const char * const nic_params[] = {
2168            "vlan", "name", "macaddr", "model", NULL
2169        };
2170        NICInfo *nd;
2171        uint8_t *macaddr;
2172        int idx = nic_get_free_idx();
2173
2174        if (check_params(buf, sizeof(buf), nic_params, p) < 0) {
2175            config_error(mon, "invalid parameter '%s' in '%s'\n", buf, p);
2176            ret = -1;
2177            goto out;
2178        }
2179        if (idx == -1 || nb_nics >= MAX_NICS) {
2180            config_error(mon, "Too Many NICs\n");
2181            ret = -1;
2182            goto out;
2183        }
2184        nd = &nd_table[idx];
2185        macaddr = nd->macaddr;
2186        macaddr[0] = 0x52;
2187        macaddr[1] = 0x54;
2188        macaddr[2] = 0x00;
2189        macaddr[3] = 0x12;
2190        macaddr[4] = 0x34;
2191        macaddr[5] = 0x56 + idx;
2192
2193        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
2194            if (parse_macaddr(macaddr, buf) < 0) {
2195                config_error(mon, "invalid syntax for ethernet address\n");
2196                ret = -1;
2197                goto out;
2198            }
2199        }
2200        if (get_param_value(buf, sizeof(buf), "model", p)) {
2201            nd->model = strdup(buf);
2202        }
2203        nd->vlan = vlan;
2204        nd->name = name;
2205        nd->used = 1;
2206        name = NULL;
2207        nb_nics++;
2208        vlan->nb_guest_devs++;
2209        ret = idx;
2210    } else
2211    if (!strcmp(device, "none")) {
2212        if (*p != '\0') {
2213            config_error(mon, "'none' takes no parameters\n");
2214            ret = -1;
2215            goto out;
2216        }
2217        /* does nothing. It is needed to signal that no network cards
2218           are wanted */
2219        ret = 0;
2220    } else
2221#ifdef CONFIG_SLIRP
2222    if (!strcmp(device, "user")) {
2223        static const char * const slirp_params[] = {
2224            "vlan", "name", "hostname", "restrict", "ip", NULL
2225        };
2226        int restricted = 0;
2227        char *ip = NULL;
2228
2229        if (check_params(buf, sizeof(buf), slirp_params, p) < 0) {
2230            config_error(mon, "invalid parameter '%s' in '%s'\n", buf, p);
2231            ret = -1;
2232            goto out;
2233        }
2234        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
2235            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
2236        }
2237        if (get_param_value(buf, sizeof(buf), "restrict", p)) {
2238            restricted = (buf[0] == 'y') ? 1 : 0;
2239        }
2240        if (get_param_value(buf, sizeof(buf), "ip", p)) {
2241            ip = qemu_strdup(buf);
2242        }
2243        vlan->nb_host_devs++;
2244        ret = net_slirp_init(vlan, device, name, restricted, ip);
2245        qemu_free(ip);
2246    } else if (!strcmp(device, "channel")) {
2247        long port;
2248        char name[20], *devname;
2249        struct VMChannel *vmc;
2250
2251        port = strtol(p, &devname, 10);
2252        devname++;
2253        if (port < 1 || port > 65535) {
2254            config_error(mon, "vmchannel wrong port number\n");
2255            ret = -1;
2256            goto out;
2257        }
2258        vmc = malloc(sizeof(struct VMChannel));
2259        snprintf(name, 20, "vmchannel%ld", port);
2260        vmc->hd = qemu_chr_open(name, devname, NULL);
2261        if (!vmc->hd) {
2262            config_error(mon, "could not open vmchannel device '%s'\n",
2263                         devname);
2264            ret = -1;
2265            goto out;
2266        }
2267        vmc->port = port;
2268        slirp_add_exec(3, vmc->hd, 4, port);
2269        qemu_chr_add_handlers(vmc->hd, vmchannel_can_read, vmchannel_read,
2270                NULL, vmc);
2271        ret = 0;
2272    } else
2273#endif
2274#ifdef _WIN32
2275    if (!strcmp(device, "tap")) {
2276        static const char * const tap_params[] = {
2277            "vlan", "name", "ifname", NULL
2278        };
2279        char ifname[64];
2280
2281        if (check_params(buf, sizeof(buf), tap_params, p) < 0) {
2282            config_error(mon, "invalid parameter '%s' in '%s'\n", buf, p);
2283            ret = -1;
2284            goto out;
2285        }
2286        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
2287            config_error(mon, "tap: no interface name\n");
2288            ret = -1;
2289            goto out;
2290        }
2291        vlan->nb_host_devs++;
2292        ret = tap_win32_init(vlan, device, name, ifname);
2293    } else
2294#elif defined (_AIX)
2295#else
2296    if (!strcmp(device, "tap")) {
2297        char ifname[64], chkbuf[64];
2298        char setup_script[1024], down_script[1024];
2299        int fd;
2300        vlan->nb_host_devs++;
2301        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2302            if (check_params(chkbuf, sizeof(chkbuf), fd_params, p) < 0) {
2303                config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);
2304                ret = -1;
2305                goto out;
2306            }
2307            fd = strtol(buf, NULL, 0);
2308            fcntl(fd, F_SETFL, O_NONBLOCK);
2309            net_tap_fd_init(vlan, device, name, fd);
2310            ret = 0;
2311        } else {
2312            static const char * const tap_params[] = {
2313                "vlan", "name", "ifname", "script", "downscript", NULL
2314            };
2315            if (check_params(chkbuf, sizeof(chkbuf), tap_params, p) < 0) {
2316                config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);
2317                ret = -1;
2318                goto out;
2319            }
2320            if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
2321                ifname[0] = '\0';
2322            }
2323            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
2324                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
2325            }
2326            if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
2327                pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
2328            }
2329            ret = net_tap_init(vlan, device, name, ifname, setup_script, down_script);
2330        }
2331    } else
2332#endif
2333    if (!strcmp(device, "socket")) {
2334        char chkbuf[64];
2335        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2336            int fd;
2337            if (check_params(chkbuf, sizeof(chkbuf), fd_params, p) < 0) {
2338                config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);
2339                ret = -1;
2340                goto out;
2341            }
2342            fd = strtol(buf, NULL, 0);
2343            ret = -1;
2344            if (net_socket_fd_init(vlan, device, name, fd, 1))
2345                ret = 0;
2346        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
2347            static const char * const listen_params[] = {
2348                "vlan", "name", "listen", NULL
2349            };
2350            if (check_params(chkbuf, sizeof(chkbuf), listen_params, p) < 0) {
2351                config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);
2352                ret = -1;
2353                goto out;
2354            }
2355            ret = net_socket_listen_init(vlan, device, name, buf);
2356        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
2357            static const char * const connect_params[] = {
2358                "vlan", "name", "connect", NULL
2359            };
2360            if (check_params(chkbuf, sizeof(chkbuf), connect_params, p) < 0) {
2361                config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);
2362                ret = -1;
2363                goto out;
2364            }
2365            ret = net_socket_connect_init(vlan, device, name, buf);
2366        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
2367            static const char * const mcast_params[] = {
2368                "vlan", "name", "mcast", NULL
2369            };
2370            if (check_params(chkbuf, sizeof(chkbuf), mcast_params, p) < 0) {
2371                config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);
2372                ret = -1;
2373                goto out;
2374            }
2375            ret = net_socket_mcast_init(vlan, device, name, buf);
2376        } else {
2377            config_error(mon, "Unknown socket options: %s\n", p);
2378            ret = -1;
2379            goto out;
2380        }
2381        vlan->nb_host_devs++;
2382    } else
2383#ifdef CONFIG_VDE
2384    if (!strcmp(device, "vde")) {
2385        static const char * const vde_params[] = {
2386            "vlan", "name", "sock", "port", "group", "mode", NULL
2387        };
2388        char vde_sock[1024], vde_group[512];
2389	int vde_port, vde_mode;
2390
2391        if (check_params(buf, sizeof(buf), vde_params, p) < 0) {
2392            config_error(mon, "invalid parameter '%s' in '%s'\n", buf, p);
2393            ret = -1;
2394            goto out;
2395        }
2396        vlan->nb_host_devs++;
2397        if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
2398	    vde_sock[0] = '\0';
2399	}
2400	if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
2401	    vde_port = strtol(buf, NULL, 10);
2402	} else {
2403	    vde_port = 0;
2404	}
2405	if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
2406	    vde_group[0] = '\0';
2407	}
2408	if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
2409	    vde_mode = strtol(buf, NULL, 8);
2410	} else {
2411	    vde_mode = 0700;
2412	}
2413	ret = net_vde_init(vlan, device, name, vde_sock, vde_port, vde_group, vde_mode);
2414    } else
2415#endif
2416    if (!strcmp(device, "dump")) {
2417        int len = 65536;
2418
2419        if (get_param_value(buf, sizeof(buf), "len", p) > 0) {
2420            len = strtol(buf, NULL, 0);
2421        }
2422        if (!get_param_value(buf, sizeof(buf), "file", p)) {
2423            snprintf(buf, sizeof(buf), "qemu-vlan%d.pcap", vlan_id);
2424        }
2425        ret = net_dump_init(mon, vlan, device, name, buf, len);
2426    } else {
2427        config_error(mon, "Unknown network device: %s\n", device);
2428        ret = -1;
2429        goto out;
2430    }
2431    if (ret < 0) {
2432        config_error(mon, "Could not initialize device '%s'\n", device);
2433    }
2434out:
2435    qemu_free(name);
2436    return ret;
2437}
2438
2439void net_client_uninit(NICInfo *nd)
2440{
2441    nd->vlan->nb_guest_devs--;
2442    nb_nics--;
2443    nd->used = 0;
2444    free((void *)nd->model);
2445}
2446
2447static int net_host_check_device(const char *device)
2448{
2449    int i;
2450    const char *valid_param_list[] = { "tap", "socket", "dump"
2451#ifdef CONFIG_SLIRP
2452                                       ,"user"
2453#endif
2454#ifdef CONFIG_VDE
2455                                       ,"vde"
2456#endif
2457    };
2458    for (i = 0; i < sizeof(valid_param_list) / sizeof(char *); i++) {
2459        if (!strncmp(valid_param_list[i], device,
2460                     strlen(valid_param_list[i])))
2461            return 1;
2462    }
2463
2464    return 0;
2465}
2466
2467void net_host_device_add(Monitor *mon, const char *device, const char *opts)
2468{
2469    if (!net_host_check_device(device)) {
2470        monitor_printf(mon, "invalid host network device %s\n", device);
2471        return;
2472    }
2473    if (net_client_init(mon, device, opts ? opts : "") < 0) {
2474        monitor_printf(mon, "adding host network device %s failed\n", device);
2475    }
2476}
2477
2478void net_host_device_remove(Monitor *mon, int vlan_id, const char *device)
2479{
2480    VLANState *vlan;
2481    VLANClientState *vc;
2482
2483    vlan = qemu_find_vlan(vlan_id);
2484
2485    for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
2486        if (!strcmp(vc->name, device)) {
2487            break;
2488        }
2489    }
2490
2491    if (!vc) {
2492        monitor_printf(mon, "can't find device %s\n", device);
2493        return;
2494    }
2495    if (!net_host_check_device(vc->model)) {
2496        monitor_printf(mon, "invalid host network device %s\n", device);
2497        return;
2498    }
2499    qemu_del_vlan_client(vc);
2500}
2501
2502int net_client_parse(const char *str)
2503{
2504    const char *p;
2505    char *q;
2506    char device[64];
2507
2508    p = str;
2509    q = device;
2510    while (*p != '\0' && *p != ',') {
2511        if ((q - device) < sizeof(device) - 1)
2512            *q++ = *p;
2513        p++;
2514    }
2515    *q = '\0';
2516    if (*p == ',')
2517        p++;
2518
2519    return net_client_init(NULL, device, p);
2520}
2521
2522void do_info_network(Monitor *mon)
2523{
2524    VLANState *vlan;
2525    VLANClientState *vc;
2526
2527    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2528        monitor_printf(mon, "VLAN %d devices:\n", vlan->id);
2529        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2530            monitor_printf(mon, "  %s: %s\n", vc->name, vc->info_str);
2531    }
2532}
2533
2534int do_set_link(Monitor *mon, const char *name, const char *up_or_down)
2535{
2536    VLANState *vlan;
2537    VLANClientState *vc = NULL;
2538
2539    for (vlan = first_vlan; vlan != NULL; vlan = vlan->next)
2540        for (vc = vlan->first_client; vc != NULL; vc = vc->next)
2541            if (strcmp(vc->name, name) == 0)
2542                goto done;
2543done:
2544
2545    if (!vc) {
2546        monitor_printf(mon, "could not find network device '%s'", name);
2547        return 0;
2548    }
2549
2550    if (strcmp(up_or_down, "up") == 0)
2551        vc->link_down = 0;
2552    else if (strcmp(up_or_down, "down") == 0)
2553        vc->link_down = 1;
2554    else
2555        monitor_printf(mon, "invalid link status '%s'; only 'up' or 'down' "
2556                       "valid\n", up_or_down);
2557
2558    if (vc->link_status_changed)
2559        vc->link_status_changed(vc);
2560
2561    return 1;
2562}
2563
2564void net_cleanup(void)
2565{
2566    VLANState *vlan;
2567
2568    /* close network clients */
2569    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2570        VLANClientState *vc = vlan->first_client;
2571
2572        while (vc) {
2573            VLANClientState *next = vc->next;
2574
2575            qemu_del_vlan_client(vc);
2576
2577            vc = next;
2578        }
2579    }
2580}
2581
2582void net_client_check(void)
2583{
2584    VLANState *vlan;
2585
2586    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2587        if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
2588            continue;
2589        if (vlan->nb_guest_devs == 0)
2590            fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
2591        if (vlan->nb_host_devs == 0)
2592            fprintf(stderr,
2593                    "Warning: vlan %d is not connected to host network\n",
2594                    vlan->id);
2595    }
2596}
2597