qemu/net/net.c
<<
>>
Prefs
   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
  25#include "qemu/osdep.h"
  26
  27#include "net/net.h"
  28#include "clients.h"
  29#include "hub.h"
  30#include "net/slirp.h"
  31#include "net/eth.h"
  32#include "util.h"
  33
  34#include "monitor/monitor.h"
  35#include "qemu/help_option.h"
  36#include "qapi/qapi-commands-net.h"
  37#include "qapi/qapi-visit-net.h"
  38#include "qapi/qmp/qdict.h"
  39#include "qapi/qmp/qerror.h"
  40#include "qemu/error-report.h"
  41#include "qemu/sockets.h"
  42#include "qemu/cutils.h"
  43#include "qemu/config-file.h"
  44#include "hw/qdev.h"
  45#include "qemu/iov.h"
  46#include "qemu/main-loop.h"
  47#include "qemu/option.h"
  48#include "qapi/error.h"
  49#include "qapi/opts-visitor.h"
  50#include "sysemu/sysemu.h"
  51#include "sysemu/qtest.h"
  52#include "net/filter.h"
  53#include "qapi/string-output-visitor.h"
  54
  55/* Net bridge is currently not supported for W32. */
  56#if !defined(_WIN32)
  57# define CONFIG_NET_BRIDGE
  58#endif
  59
  60static VMChangeStateEntry *net_change_state_entry;
  61static QTAILQ_HEAD(, NetClientState) net_clients;
  62
  63/***********************************************************/
  64/* network device redirectors */
  65
  66static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
  67{
  68    const char *p, *p1;
  69    int len;
  70    p = *pp;
  71    p1 = strchr(p, sep);
  72    if (!p1)
  73        return -1;
  74    len = p1 - p;
  75    p1++;
  76    if (buf_size > 0) {
  77        if (len > buf_size - 1)
  78            len = buf_size - 1;
  79        memcpy(buf, p, len);
  80        buf[len] = '\0';
  81    }
  82    *pp = p1;
  83    return 0;
  84}
  85
  86int parse_host_port(struct sockaddr_in *saddr, const char *str,
  87                    Error **errp)
  88{
  89    char buf[512];
  90    struct hostent *he;
  91    const char *p, *r;
  92    int port;
  93
  94    p = str;
  95    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
  96        error_setg(errp, "host address '%s' doesn't contain ':' "
  97                   "separating host from port", str);
  98        return -1;
  99    }
 100    saddr->sin_family = AF_INET;
 101    if (buf[0] == '\0') {
 102        saddr->sin_addr.s_addr = 0;
 103    } else {
 104        if (qemu_isdigit(buf[0])) {
 105            if (!inet_aton(buf, &saddr->sin_addr)) {
 106                error_setg(errp, "host address '%s' is not a valid "
 107                           "IPv4 address", buf);
 108                return -1;
 109            }
 110        } else {
 111            he = gethostbyname(buf);
 112            if (he == NULL) {
 113                error_setg(errp, "can't resolve host address '%s'", buf);
 114                return - 1;
 115            }
 116            saddr->sin_addr = *(struct in_addr *)he->h_addr;
 117        }
 118    }
 119    port = strtol(p, (char **)&r, 0);
 120    if (r == p) {
 121        error_setg(errp, "port number '%s' is invalid", p);
 122        return -1;
 123    }
 124    saddr->sin_port = htons(port);
 125    return 0;
 126}
 127
 128char *qemu_mac_strdup_printf(const uint8_t *macaddr)
 129{
 130    return g_strdup_printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
 131                           macaddr[0], macaddr[1], macaddr[2],
 132                           macaddr[3], macaddr[4], macaddr[5]);
 133}
 134
 135void qemu_format_nic_info_str(NetClientState *nc, uint8_t macaddr[6])
 136{
 137    snprintf(nc->info_str, sizeof(nc->info_str),
 138             "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
 139             nc->model,
 140             macaddr[0], macaddr[1], macaddr[2],
 141             macaddr[3], macaddr[4], macaddr[5]);
 142}
 143
 144static int mac_table[256] = {0};
 145
 146static void qemu_macaddr_set_used(MACAddr *macaddr)
 147{
 148    int index;
 149
 150    for (index = 0x56; index < 0xFF; index++) {
 151        if (macaddr->a[5] == index) {
 152            mac_table[index]++;
 153        }
 154    }
 155}
 156
 157static void qemu_macaddr_set_free(MACAddr *macaddr)
 158{
 159    int index;
 160    static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
 161
 162    if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
 163        return;
 164    }
 165    for (index = 0x56; index < 0xFF; index++) {
 166        if (macaddr->a[5] == index) {
 167            mac_table[index]--;
 168        }
 169    }
 170}
 171
 172static int qemu_macaddr_get_free(void)
 173{
 174    int index;
 175
 176    for (index = 0x56; index < 0xFF; index++) {
 177        if (mac_table[index] == 0) {
 178            return index;
 179        }
 180    }
 181
 182    return -1;
 183}
 184
 185void qemu_macaddr_default_if_unset(MACAddr *macaddr)
 186{
 187    static const MACAddr zero = { .a = { 0,0,0,0,0,0 } };
 188    static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
 189
 190    if (memcmp(macaddr, &zero, sizeof(zero)) != 0) {
 191        if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
 192            return;
 193        } else {
 194            qemu_macaddr_set_used(macaddr);
 195            return;
 196        }
 197    }
 198
 199    macaddr->a[0] = 0x52;
 200    macaddr->a[1] = 0x54;
 201    macaddr->a[2] = 0x00;
 202    macaddr->a[3] = 0x12;
 203    macaddr->a[4] = 0x34;
 204    macaddr->a[5] = qemu_macaddr_get_free();
 205    qemu_macaddr_set_used(macaddr);
 206}
 207
 208/**
 209 * Generate a name for net client
 210 *
 211 * Only net clients created with the legacy -net option and NICs need this.
 212 */
 213static char *assign_name(NetClientState *nc1, const char *model)
 214{
 215    NetClientState *nc;
 216    int id = 0;
 217
 218    QTAILQ_FOREACH(nc, &net_clients, next) {
 219        if (nc == nc1) {
 220            continue;
 221        }
 222        if (strcmp(nc->model, model) == 0) {
 223            id++;
 224        }
 225    }
 226
 227    return g_strdup_printf("%s.%d", model, id);
 228}
 229
 230static void qemu_net_client_destructor(NetClientState *nc)
 231{
 232    g_free(nc);
 233}
 234static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
 235                                       unsigned flags,
 236                                       const struct iovec *iov,
 237                                       int iovcnt,
 238                                       void *opaque);
 239
 240static void qemu_net_client_setup(NetClientState *nc,
 241                                  NetClientInfo *info,
 242                                  NetClientState *peer,
 243                                  const char *model,
 244                                  const char *name,
 245                                  NetClientDestructor *destructor)
 246{
 247    nc->info = info;
 248    nc->model = g_strdup(model);
 249    if (name) {
 250        nc->name = g_strdup(name);
 251    } else {
 252        nc->name = assign_name(nc, model);
 253    }
 254
 255    if (peer) {
 256        assert(!peer->peer);
 257        nc->peer = peer;
 258        peer->peer = nc;
 259    }
 260    QTAILQ_INSERT_TAIL(&net_clients, nc, next);
 261
 262    nc->incoming_queue = qemu_new_net_queue(qemu_deliver_packet_iov, nc);
 263    nc->destructor = destructor;
 264    QTAILQ_INIT(&nc->filters);
 265}
 266
 267NetClientState *qemu_new_net_client(NetClientInfo *info,
 268                                    NetClientState *peer,
 269                                    const char *model,
 270                                    const char *name)
 271{
 272    NetClientState *nc;
 273
 274    assert(info->size >= sizeof(NetClientState));
 275
 276    nc = g_malloc0(info->size);
 277    qemu_net_client_setup(nc, info, peer, model, name,
 278                          qemu_net_client_destructor);
 279
 280    return nc;
 281}
 282
 283NICState *qemu_new_nic(NetClientInfo *info,
 284                       NICConf *conf,
 285                       const char *model,
 286                       const char *name,
 287                       void *opaque)
 288{
 289    NetClientState **peers = conf->peers.ncs;
 290    NICState *nic;
 291    int i, queues = MAX(1, conf->peers.queues);
 292
 293    assert(info->type == NET_CLIENT_DRIVER_NIC);
 294    assert(info->size >= sizeof(NICState));
 295
 296    nic = g_malloc0(info->size + sizeof(NetClientState) * queues);
 297    nic->ncs = (void *)nic + info->size;
 298    nic->conf = conf;
 299    nic->opaque = opaque;
 300
 301    for (i = 0; i < queues; i++) {
 302        qemu_net_client_setup(&nic->ncs[i], info, peers[i], model, name,
 303                              NULL);
 304        nic->ncs[i].queue_index = i;
 305    }
 306
 307    return nic;
 308}
 309
 310NetClientState *qemu_get_subqueue(NICState *nic, int queue_index)
 311{
 312    return nic->ncs + queue_index;
 313}
 314
 315NetClientState *qemu_get_queue(NICState *nic)
 316{
 317    return qemu_get_subqueue(nic, 0);
 318}
 319
 320NICState *qemu_get_nic(NetClientState *nc)
 321{
 322    NetClientState *nc0 = nc - nc->queue_index;
 323
 324    return (NICState *)((void *)nc0 - nc->info->size);
 325}
 326
 327void *qemu_get_nic_opaque(NetClientState *nc)
 328{
 329    NICState *nic = qemu_get_nic(nc);
 330
 331    return nic->opaque;
 332}
 333
 334static void qemu_cleanup_net_client(NetClientState *nc)
 335{
 336    QTAILQ_REMOVE(&net_clients, nc, next);
 337
 338    if (nc->info->cleanup) {
 339        nc->info->cleanup(nc);
 340    }
 341}
 342
 343static void qemu_free_net_client(NetClientState *nc)
 344{
 345    if (nc->incoming_queue) {
 346        qemu_del_net_queue(nc->incoming_queue);
 347    }
 348    if (nc->peer) {
 349        nc->peer->peer = NULL;
 350    }
 351    g_free(nc->name);
 352    g_free(nc->model);
 353    if (nc->destructor) {
 354        nc->destructor(nc);
 355    }
 356}
 357
 358void qemu_del_net_client(NetClientState *nc)
 359{
 360    NetClientState *ncs[MAX_QUEUE_NUM];
 361    int queues, i;
 362    NetFilterState *nf, *next;
 363
 364    assert(nc->info->type != NET_CLIENT_DRIVER_NIC);
 365
 366    /* If the NetClientState belongs to a multiqueue backend, we will change all
 367     * other NetClientStates also.
 368     */
 369    queues = qemu_find_net_clients_except(nc->name, ncs,
 370                                          NET_CLIENT_DRIVER_NIC,
 371                                          MAX_QUEUE_NUM);
 372    assert(queues != 0);
 373
 374    QTAILQ_FOREACH_SAFE(nf, &nc->filters, next, next) {
 375        object_unparent(OBJECT(nf));
 376    }
 377
 378    /* If there is a peer NIC, delete and cleanup client, but do not free. */
 379    if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
 380        NICState *nic = qemu_get_nic(nc->peer);
 381        if (nic->peer_deleted) {
 382            return;
 383        }
 384        nic->peer_deleted = true;
 385
 386        for (i = 0; i < queues; i++) {
 387            ncs[i]->peer->link_down = true;
 388        }
 389
 390        if (nc->peer->info->link_status_changed) {
 391            nc->peer->info->link_status_changed(nc->peer);
 392        }
 393
 394        for (i = 0; i < queues; i++) {
 395            qemu_cleanup_net_client(ncs[i]);
 396        }
 397
 398        return;
 399    }
 400
 401    for (i = 0; i < queues; i++) {
 402        qemu_cleanup_net_client(ncs[i]);
 403        qemu_free_net_client(ncs[i]);
 404    }
 405}
 406
 407void qemu_del_nic(NICState *nic)
 408{
 409    int i, queues = MAX(nic->conf->peers.queues, 1);
 410
 411    qemu_macaddr_set_free(&nic->conf->macaddr);
 412
 413    /* If this is a peer NIC and peer has already been deleted, free it now. */
 414    if (nic->peer_deleted) {
 415        for (i = 0; i < queues; i++) {
 416            qemu_free_net_client(qemu_get_subqueue(nic, i)->peer);
 417        }
 418    }
 419
 420    for (i = queues - 1; i >= 0; i--) {
 421        NetClientState *nc = qemu_get_subqueue(nic, i);
 422
 423        qemu_cleanup_net_client(nc);
 424        qemu_free_net_client(nc);
 425    }
 426
 427    g_free(nic);
 428}
 429
 430void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
 431{
 432    NetClientState *nc;
 433
 434    QTAILQ_FOREACH(nc, &net_clients, next) {
 435        if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
 436            if (nc->queue_index == 0) {
 437                func(qemu_get_nic(nc), opaque);
 438            }
 439        }
 440    }
 441}
 442
 443bool qemu_has_ufo(NetClientState *nc)
 444{
 445    if (!nc || !nc->info->has_ufo) {
 446        return false;
 447    }
 448
 449    return nc->info->has_ufo(nc);
 450}
 451
 452bool qemu_has_vnet_hdr(NetClientState *nc)
 453{
 454    if (!nc || !nc->info->has_vnet_hdr) {
 455        return false;
 456    }
 457
 458    return nc->info->has_vnet_hdr(nc);
 459}
 460
 461bool qemu_has_vnet_hdr_len(NetClientState *nc, int len)
 462{
 463    if (!nc || !nc->info->has_vnet_hdr_len) {
 464        return false;
 465    }
 466
 467    return nc->info->has_vnet_hdr_len(nc, len);
 468}
 469
 470void qemu_using_vnet_hdr(NetClientState *nc, bool enable)
 471{
 472    if (!nc || !nc->info->using_vnet_hdr) {
 473        return;
 474    }
 475
 476    nc->info->using_vnet_hdr(nc, enable);
 477}
 478
 479void qemu_set_offload(NetClientState *nc, int csum, int tso4, int tso6,
 480                          int ecn, int ufo)
 481{
 482    if (!nc || !nc->info->set_offload) {
 483        return;
 484    }
 485
 486    nc->info->set_offload(nc, csum, tso4, tso6, ecn, ufo);
 487}
 488
 489void qemu_set_vnet_hdr_len(NetClientState *nc, int len)
 490{
 491    if (!nc || !nc->info->set_vnet_hdr_len) {
 492        return;
 493    }
 494
 495    nc->vnet_hdr_len = len;
 496    nc->info->set_vnet_hdr_len(nc, len);
 497}
 498
 499int qemu_set_vnet_le(NetClientState *nc, bool is_le)
 500{
 501#ifdef HOST_WORDS_BIGENDIAN
 502    if (!nc || !nc->info->set_vnet_le) {
 503        return -ENOSYS;
 504    }
 505
 506    return nc->info->set_vnet_le(nc, is_le);
 507#else
 508    return 0;
 509#endif
 510}
 511
 512int qemu_set_vnet_be(NetClientState *nc, bool is_be)
 513{
 514#ifdef HOST_WORDS_BIGENDIAN
 515    return 0;
 516#else
 517    if (!nc || !nc->info->set_vnet_be) {
 518        return -ENOSYS;
 519    }
 520
 521    return nc->info->set_vnet_be(nc, is_be);
 522#endif
 523}
 524
 525int qemu_can_send_packet(NetClientState *sender)
 526{
 527    int vm_running = runstate_is_running();
 528
 529    if (!vm_running) {
 530        return 0;
 531    }
 532
 533    if (!sender->peer) {
 534        return 1;
 535    }
 536
 537    if (sender->peer->receive_disabled) {
 538        return 0;
 539    } else if (sender->peer->info->can_receive &&
 540               !sender->peer->info->can_receive(sender->peer)) {
 541        return 0;
 542    }
 543    return 1;
 544}
 545
 546static ssize_t filter_receive_iov(NetClientState *nc,
 547                                  NetFilterDirection direction,
 548                                  NetClientState *sender,
 549                                  unsigned flags,
 550                                  const struct iovec *iov,
 551                                  int iovcnt,
 552                                  NetPacketSent *sent_cb)
 553{
 554    ssize_t ret = 0;
 555    NetFilterState *nf = NULL;
 556
 557    if (direction == NET_FILTER_DIRECTION_TX) {
 558        QTAILQ_FOREACH(nf, &nc->filters, next) {
 559            ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
 560                                         iovcnt, sent_cb);
 561            if (ret) {
 562                return ret;
 563            }
 564        }
 565    } else {
 566        QTAILQ_FOREACH_REVERSE(nf, &nc->filters, NetFilterHead, next) {
 567            ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
 568                                         iovcnt, sent_cb);
 569            if (ret) {
 570                return ret;
 571            }
 572        }
 573    }
 574
 575    return ret;
 576}
 577
 578static ssize_t filter_receive(NetClientState *nc,
 579                              NetFilterDirection direction,
 580                              NetClientState *sender,
 581                              unsigned flags,
 582                              const uint8_t *data,
 583                              size_t size,
 584                              NetPacketSent *sent_cb)
 585{
 586    struct iovec iov = {
 587        .iov_base = (void *)data,
 588        .iov_len = size
 589    };
 590
 591    return filter_receive_iov(nc, direction, sender, flags, &iov, 1, sent_cb);
 592}
 593
 594void qemu_purge_queued_packets(NetClientState *nc)
 595{
 596    if (!nc->peer) {
 597        return;
 598    }
 599
 600    qemu_net_queue_purge(nc->peer->incoming_queue, nc);
 601}
 602
 603void qemu_flush_or_purge_queued_packets(NetClientState *nc, bool purge)
 604{
 605    nc->receive_disabled = 0;
 606
 607    if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_HUBPORT) {
 608        if (net_hub_flush(nc->peer)) {
 609            qemu_notify_event();
 610        }
 611    }
 612    if (qemu_net_queue_flush(nc->incoming_queue)) {
 613        /* We emptied the queue successfully, signal to the IO thread to repoll
 614         * the file descriptor (for tap, for example).
 615         */
 616        qemu_notify_event();
 617    } else if (purge) {
 618        /* Unable to empty the queue, purge remaining packets */
 619        qemu_net_queue_purge(nc->incoming_queue, nc);
 620    }
 621}
 622
 623void qemu_flush_queued_packets(NetClientState *nc)
 624{
 625    qemu_flush_or_purge_queued_packets(nc, false);
 626}
 627
 628static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
 629                                                 unsigned flags,
 630                                                 const uint8_t *buf, int size,
 631                                                 NetPacketSent *sent_cb)
 632{
 633    NetQueue *queue;
 634    int ret;
 635
 636#ifdef DEBUG_NET
 637    printf("qemu_send_packet_async:\n");
 638    qemu_hexdump((const char *)buf, stdout, "net", size);
 639#endif
 640
 641    if (sender->link_down || !sender->peer) {
 642        return size;
 643    }
 644
 645    /* Let filters handle the packet first */
 646    ret = filter_receive(sender, NET_FILTER_DIRECTION_TX,
 647                         sender, flags, buf, size, sent_cb);
 648    if (ret) {
 649        return ret;
 650    }
 651
 652    ret = filter_receive(sender->peer, NET_FILTER_DIRECTION_RX,
 653                         sender, flags, buf, size, sent_cb);
 654    if (ret) {
 655        return ret;
 656    }
 657
 658    queue = sender->peer->incoming_queue;
 659
 660    return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
 661}
 662
 663ssize_t qemu_send_packet_async(NetClientState *sender,
 664                               const uint8_t *buf, int size,
 665                               NetPacketSent *sent_cb)
 666{
 667    return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
 668                                             buf, size, sent_cb);
 669}
 670
 671void qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size)
 672{
 673    qemu_send_packet_async(nc, buf, size, NULL);
 674}
 675
 676ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size)
 677{
 678    return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW,
 679                                             buf, size, NULL);
 680}
 681
 682static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
 683                               int iovcnt, unsigned flags)
 684{
 685    uint8_t *buf = NULL;
 686    uint8_t *buffer;
 687    size_t offset;
 688    ssize_t ret;
 689
 690    if (iovcnt == 1) {
 691        buffer = iov[0].iov_base;
 692        offset = iov[0].iov_len;
 693    } else {
 694        offset = iov_size(iov, iovcnt);
 695        if (offset > NET_BUFSIZE) {
 696            return -1;
 697        }
 698        buf = g_malloc(offset);
 699        buffer = buf;
 700        offset = iov_to_buf(iov, iovcnt, 0, buf, offset);
 701    }
 702
 703    if (flags & QEMU_NET_PACKET_FLAG_RAW && nc->info->receive_raw) {
 704        ret = nc->info->receive_raw(nc, buffer, offset);
 705    } else {
 706        ret = nc->info->receive(nc, buffer, offset);
 707    }
 708
 709    g_free(buf);
 710    return ret;
 711}
 712
 713static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
 714                                       unsigned flags,
 715                                       const struct iovec *iov,
 716                                       int iovcnt,
 717                                       void *opaque)
 718{
 719    NetClientState *nc = opaque;
 720    int ret;
 721
 722
 723    if (nc->link_down) {
 724        return iov_size(iov, iovcnt);
 725    }
 726
 727    if (nc->receive_disabled) {
 728        return 0;
 729    }
 730
 731    if (nc->info->receive_iov && !(flags & QEMU_NET_PACKET_FLAG_RAW)) {
 732        ret = nc->info->receive_iov(nc, iov, iovcnt);
 733    } else {
 734        ret = nc_sendv_compat(nc, iov, iovcnt, flags);
 735    }
 736
 737    if (ret == 0) {
 738        nc->receive_disabled = 1;
 739    }
 740
 741    return ret;
 742}
 743
 744ssize_t qemu_sendv_packet_async(NetClientState *sender,
 745                                const struct iovec *iov, int iovcnt,
 746                                NetPacketSent *sent_cb)
 747{
 748    NetQueue *queue;
 749    size_t size = iov_size(iov, iovcnt);
 750    int ret;
 751
 752    if (size > NET_BUFSIZE) {
 753        return size;
 754    }
 755
 756    if (sender->link_down || !sender->peer) {
 757        return size;
 758    }
 759
 760    /* Let filters handle the packet first */
 761    ret = filter_receive_iov(sender, NET_FILTER_DIRECTION_TX, sender,
 762                             QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
 763    if (ret) {
 764        return ret;
 765    }
 766
 767    ret = filter_receive_iov(sender->peer, NET_FILTER_DIRECTION_RX, sender,
 768                             QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
 769    if (ret) {
 770        return ret;
 771    }
 772
 773    queue = sender->peer->incoming_queue;
 774
 775    return qemu_net_queue_send_iov(queue, sender,
 776                                   QEMU_NET_PACKET_FLAG_NONE,
 777                                   iov, iovcnt, sent_cb);
 778}
 779
 780ssize_t
 781qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt)
 782{
 783    return qemu_sendv_packet_async(nc, iov, iovcnt, NULL);
 784}
 785
 786NetClientState *qemu_find_netdev(const char *id)
 787{
 788    NetClientState *nc;
 789
 790    QTAILQ_FOREACH(nc, &net_clients, next) {
 791        if (nc->info->type == NET_CLIENT_DRIVER_NIC)
 792            continue;
 793        if (!strcmp(nc->name, id)) {
 794            return nc;
 795        }
 796    }
 797
 798    return NULL;
 799}
 800
 801int qemu_find_net_clients_except(const char *id, NetClientState **ncs,
 802                                 NetClientDriver type, int max)
 803{
 804    NetClientState *nc;
 805    int ret = 0;
 806
 807    QTAILQ_FOREACH(nc, &net_clients, next) {
 808        if (nc->info->type == type) {
 809            continue;
 810        }
 811        if (!id || !strcmp(nc->name, id)) {
 812            if (ret < max) {
 813                ncs[ret] = nc;
 814            }
 815            ret++;
 816        }
 817    }
 818
 819    return ret;
 820}
 821
 822static int nic_get_free_idx(void)
 823{
 824    int index;
 825
 826    for (index = 0; index < MAX_NICS; index++)
 827        if (!nd_table[index].used)
 828            return index;
 829    return -1;
 830}
 831
 832int qemu_show_nic_models(const char *arg, const char *const *models)
 833{
 834    int i;
 835
 836    if (!arg || !is_help_option(arg)) {
 837        return 0;
 838    }
 839
 840    fprintf(stderr, "qemu: Supported NIC models: ");
 841    for (i = 0 ; models[i]; i++)
 842        fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
 843    return 1;
 844}
 845
 846void qemu_check_nic_model(NICInfo *nd, const char *model)
 847{
 848    const char *models[2];
 849
 850    models[0] = model;
 851    models[1] = NULL;
 852
 853    if (qemu_show_nic_models(nd->model, models))
 854        exit(0);
 855    if (qemu_find_nic_model(nd, models, model) < 0)
 856        exit(1);
 857}
 858
 859int qemu_find_nic_model(NICInfo *nd, const char * const *models,
 860                        const char *default_model)
 861{
 862    int i;
 863
 864    if (!nd->model)
 865        nd->model = g_strdup(default_model);
 866
 867    for (i = 0 ; models[i]; i++) {
 868        if (strcmp(nd->model, models[i]) == 0)
 869            return i;
 870    }
 871
 872    error_report("Unsupported NIC model: %s", nd->model);
 873    return -1;
 874}
 875
 876static int net_init_nic(const Netdev *netdev, const char *name,
 877                        NetClientState *peer, Error **errp)
 878{
 879    int idx;
 880    NICInfo *nd;
 881    const NetLegacyNicOptions *nic;
 882
 883    assert(netdev->type == NET_CLIENT_DRIVER_NIC);
 884    nic = &netdev->u.nic;
 885
 886    idx = nic_get_free_idx();
 887    if (idx == -1 || nb_nics >= MAX_NICS) {
 888        error_setg(errp, "too many NICs");
 889        return -1;
 890    }
 891
 892    nd = &nd_table[idx];
 893
 894    memset(nd, 0, sizeof(*nd));
 895
 896    if (nic->has_netdev) {
 897        nd->netdev = qemu_find_netdev(nic->netdev);
 898        if (!nd->netdev) {
 899            error_setg(errp, "netdev '%s' not found", nic->netdev);
 900            return -1;
 901        }
 902    } else {
 903        assert(peer);
 904        nd->netdev = peer;
 905    }
 906    nd->name = g_strdup(name);
 907    if (nic->has_model) {
 908        nd->model = g_strdup(nic->model);
 909    }
 910    if (nic->has_addr) {
 911        nd->devaddr = g_strdup(nic->addr);
 912    }
 913
 914    if (nic->has_macaddr &&
 915        net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {
 916        error_setg(errp, "invalid syntax for ethernet address");
 917        return -1;
 918    }
 919    if (nic->has_macaddr &&
 920        is_multicast_ether_addr(nd->macaddr.a)) {
 921        error_setg(errp,
 922                   "NIC cannot have multicast MAC address (odd 1st byte)");
 923        return -1;
 924    }
 925    qemu_macaddr_default_if_unset(&nd->macaddr);
 926
 927    if (nic->has_vectors) {
 928        if (nic->vectors > 0x7ffffff) {
 929            error_setg(errp, "invalid # of vectors: %"PRIu32, nic->vectors);
 930            return -1;
 931        }
 932        nd->nvectors = nic->vectors;
 933    } else {
 934        nd->nvectors = DEV_NVECTORS_UNSPECIFIED;
 935    }
 936
 937    nd->used = 1;
 938    nb_nics++;
 939
 940    return idx;
 941}
 942
 943
 944static int (* const net_client_init_fun[NET_CLIENT_DRIVER__MAX])(
 945    const Netdev *netdev,
 946    const char *name,
 947    NetClientState *peer, Error **errp) = {
 948        [NET_CLIENT_DRIVER_NIC]       = net_init_nic,
 949#ifdef CONFIG_SLIRP
 950        [NET_CLIENT_DRIVER_USER]      = net_init_slirp,
 951#endif
 952        [NET_CLIENT_DRIVER_TAP]       = net_init_tap,
 953        [NET_CLIENT_DRIVER_SOCKET]    = net_init_socket,
 954#ifdef CONFIG_VDE
 955        [NET_CLIENT_DRIVER_VDE]       = net_init_vde,
 956#endif
 957#ifdef CONFIG_NETMAP
 958        [NET_CLIENT_DRIVER_NETMAP]    = net_init_netmap,
 959#endif
 960#ifdef CONFIG_NET_BRIDGE
 961        [NET_CLIENT_DRIVER_BRIDGE]    = net_init_bridge,
 962#endif
 963        [NET_CLIENT_DRIVER_HUBPORT]   = net_init_hubport,
 964#ifdef CONFIG_VHOST_NET_USED
 965        [NET_CLIENT_DRIVER_VHOST_USER] = net_init_vhost_user,
 966#endif
 967#ifdef CONFIG_L2TPV3
 968        [NET_CLIENT_DRIVER_L2TPV3]    = net_init_l2tpv3,
 969#endif
 970};
 971
 972
 973static int net_client_init1(const void *object, bool is_netdev, Error **errp)
 974{
 975    Netdev legacy = {0};
 976    const Netdev *netdev;
 977    const char *name;
 978    NetClientState *peer = NULL;
 979
 980    if (is_netdev) {
 981        netdev = object;
 982        name = netdev->id;
 983
 984        if (netdev->type == NET_CLIENT_DRIVER_NIC ||
 985            !net_client_init_fun[netdev->type]) {
 986            error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
 987                       "a netdev backend type");
 988            return -1;
 989        }
 990    } else {
 991        const NetLegacy *net = object;
 992        const NetLegacyOptions *opts = net->opts;
 993        legacy.id = net->id;
 994        netdev = &legacy;
 995        /* missing optional values have been initialized to "all bits zero" */
 996        name = net->has_id ? net->id : net->name;
 997
 998        /* Map the old options to the new flat type */
 999        switch (opts->type) {
1000        case NET_LEGACY_OPTIONS_TYPE_NONE:
1001            return 0; /* nothing to do */
1002        case NET_LEGACY_OPTIONS_TYPE_NIC:
1003            legacy.type = NET_CLIENT_DRIVER_NIC;
1004            legacy.u.nic = opts->u.nic;
1005            break;
1006        case NET_LEGACY_OPTIONS_TYPE_USER:
1007            legacy.type = NET_CLIENT_DRIVER_USER;
1008            legacy.u.user = opts->u.user;
1009            break;
1010        case NET_LEGACY_OPTIONS_TYPE_TAP:
1011            legacy.type = NET_CLIENT_DRIVER_TAP;
1012            legacy.u.tap = opts->u.tap;
1013            break;
1014        case NET_LEGACY_OPTIONS_TYPE_L2TPV3:
1015            legacy.type = NET_CLIENT_DRIVER_L2TPV3;
1016            legacy.u.l2tpv3 = opts->u.l2tpv3;
1017            break;
1018        case NET_LEGACY_OPTIONS_TYPE_SOCKET:
1019            legacy.type = NET_CLIENT_DRIVER_SOCKET;
1020            legacy.u.socket = opts->u.socket;
1021            break;
1022        case NET_LEGACY_OPTIONS_TYPE_VDE:
1023            legacy.type = NET_CLIENT_DRIVER_VDE;
1024            legacy.u.vde = opts->u.vde;
1025            break;
1026        case NET_LEGACY_OPTIONS_TYPE_BRIDGE:
1027            legacy.type = NET_CLIENT_DRIVER_BRIDGE;
1028            legacy.u.bridge = opts->u.bridge;
1029            break;
1030        case NET_LEGACY_OPTIONS_TYPE_NETMAP:
1031            legacy.type = NET_CLIENT_DRIVER_NETMAP;
1032            legacy.u.netmap = opts->u.netmap;
1033            break;
1034        case NET_LEGACY_OPTIONS_TYPE_VHOST_USER:
1035            legacy.type = NET_CLIENT_DRIVER_VHOST_USER;
1036            legacy.u.vhost_user = opts->u.vhost_user;
1037            break;
1038        default:
1039            abort();
1040        }
1041
1042        if (!net_client_init_fun[netdev->type]) {
1043            error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
1044                       "a net backend type (maybe it is not compiled "
1045                       "into this binary)");
1046            return -1;
1047        }
1048
1049        /* Do not add to a hub if it's a nic with a netdev= parameter. */
1050        if (netdev->type != NET_CLIENT_DRIVER_NIC ||
1051            !opts->u.nic.has_netdev) {
1052            peer = net_hub_add_port(0, NULL, NULL);
1053        }
1054    }
1055
1056    if (net_client_init_fun[netdev->type](netdev, name, peer, errp) < 0) {
1057        /* FIXME drop when all init functions store an Error */
1058        if (errp && !*errp) {
1059            error_setg(errp, QERR_DEVICE_INIT_FAILED,
1060                       NetClientDriver_str(netdev->type));
1061        }
1062        return -1;
1063    }
1064    return 0;
1065}
1066
1067static void show_netdevs(void)
1068{
1069    int idx;
1070    const char *available_netdevs[] = {
1071        "socket",
1072        "hubport",
1073        "tap",
1074#ifdef CONFIG_SLIRP
1075        "user",
1076#endif
1077#ifdef CONFIG_L2TPV3
1078        "l2tpv3",
1079#endif
1080#ifdef CONFIG_VDE
1081        "vde",
1082#endif
1083#ifdef CONFIG_NET_BRIDGE
1084        "bridge",
1085#endif
1086#ifdef CONFIG_NETMAP
1087        "netmap",
1088#endif
1089#ifdef CONFIG_POSIX
1090        "vhost-user",
1091#endif
1092    };
1093
1094    printf("Available netdev backend types:\n");
1095    for (idx = 0; idx < ARRAY_SIZE(available_netdevs); idx++) {
1096        puts(available_netdevs[idx]);
1097    }
1098}
1099
1100static int net_client_init(QemuOpts *opts, bool is_netdev, Error **errp)
1101{
1102    void *object = NULL;
1103    Error *err = NULL;
1104    int ret = -1;
1105    Visitor *v = opts_visitor_new(opts);
1106
1107    const char *type = qemu_opt_get(opts, "type");
1108
1109    if (is_netdev && type && is_help_option(type)) {
1110        show_netdevs();
1111        exit(0);
1112    } else {
1113        /* Parse convenience option format ip6-net=fec0::0[/64] */
1114        const char *ip6_net = qemu_opt_get(opts, "ipv6-net");
1115
1116        if (ip6_net) {
1117            char buf[strlen(ip6_net) + 1];
1118
1119            if (get_str_sep(buf, sizeof(buf), &ip6_net, '/') < 0) {
1120                /* Default 64bit prefix length.  */
1121                qemu_opt_set(opts, "ipv6-prefix", ip6_net, &error_abort);
1122                qemu_opt_set_number(opts, "ipv6-prefixlen", 64, &error_abort);
1123            } else {
1124                /* User-specified prefix length.  */
1125                unsigned long len;
1126                int err;
1127
1128                qemu_opt_set(opts, "ipv6-prefix", buf, &error_abort);
1129                err = qemu_strtoul(ip6_net, NULL, 10, &len);
1130
1131                if (err) {
1132                    error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1133                              "ipv6-prefix", "a number");
1134                } else {
1135                    qemu_opt_set_number(opts, "ipv6-prefixlen", len,
1136                                        &error_abort);
1137                }
1138            }
1139            qemu_opt_unset(opts, "ipv6-net");
1140        }
1141    }
1142
1143    if (is_netdev) {
1144        visit_type_Netdev(v, NULL, (Netdev **)&object, &err);
1145    } else {
1146        visit_type_NetLegacy(v, NULL, (NetLegacy **)&object, &err);
1147    }
1148
1149    if (!err) {
1150        ret = net_client_init1(object, is_netdev, &err);
1151    }
1152
1153    if (is_netdev) {
1154        qapi_free_Netdev(object);
1155    } else {
1156        qapi_free_NetLegacy(object);
1157    }
1158
1159    error_propagate(errp, err);
1160    visit_free(v);
1161    return ret;
1162}
1163
1164void netdev_add(QemuOpts *opts, Error **errp)
1165{
1166    net_client_init(opts, true, errp);
1167}
1168
1169void qmp_netdev_add(QDict *qdict, QObject **ret, Error **errp)
1170{
1171    Error *local_err = NULL;
1172    QemuOptsList *opts_list;
1173    QemuOpts *opts;
1174
1175    opts_list = qemu_find_opts_err("netdev", &local_err);
1176    if (local_err) {
1177        goto out;
1178    }
1179
1180    opts = qemu_opts_from_qdict(opts_list, qdict, &local_err);
1181    if (local_err) {
1182        goto out;
1183    }
1184
1185    netdev_add(opts, &local_err);
1186    if (local_err) {
1187        qemu_opts_del(opts);
1188        goto out;
1189    }
1190
1191out:
1192    error_propagate(errp, local_err);
1193}
1194
1195void qmp_netdev_del(const char *id, Error **errp)
1196{
1197    NetClientState *nc;
1198    QemuOpts *opts;
1199
1200    nc = qemu_find_netdev(id);
1201    if (!nc) {
1202        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1203                  "Device '%s' not found", id);
1204        return;
1205    }
1206
1207    opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), id);
1208    if (!opts) {
1209        error_setg(errp, "Device '%s' is not a netdev", id);
1210        return;
1211    }
1212
1213    qemu_del_net_client(nc);
1214    qemu_opts_del(opts);
1215}
1216
1217static void netfilter_print_info(Monitor *mon, NetFilterState *nf)
1218{
1219    char *str;
1220    ObjectProperty *prop;
1221    ObjectPropertyIterator iter;
1222    Visitor *v;
1223
1224    /* generate info str */
1225    object_property_iter_init(&iter, OBJECT(nf));
1226    while ((prop = object_property_iter_next(&iter))) {
1227        if (!strcmp(prop->name, "type")) {
1228            continue;
1229        }
1230        v = string_output_visitor_new(false, &str);
1231        object_property_get(OBJECT(nf), v, prop->name, NULL);
1232        visit_complete(v, &str);
1233        visit_free(v);
1234        monitor_printf(mon, ",%s=%s", prop->name, str);
1235        g_free(str);
1236    }
1237    monitor_printf(mon, "\n");
1238}
1239
1240void print_net_client(Monitor *mon, NetClientState *nc)
1241{
1242    NetFilterState *nf;
1243
1244    monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
1245                   nc->queue_index,
1246                   NetClientDriver_str(nc->info->type),
1247                   nc->info_str);
1248    if (!QTAILQ_EMPTY(&nc->filters)) {
1249        monitor_printf(mon, "filters:\n");
1250    }
1251    QTAILQ_FOREACH(nf, &nc->filters, next) {
1252        char *path = object_get_canonical_path_component(OBJECT(nf));
1253
1254        monitor_printf(mon, "  - %s: type=%s", path,
1255                       object_get_typename(OBJECT(nf)));
1256        netfilter_print_info(mon, nf);
1257        g_free(path);
1258    }
1259}
1260
1261RxFilterInfoList *qmp_query_rx_filter(bool has_name, const char *name,
1262                                      Error **errp)
1263{
1264    NetClientState *nc;
1265    RxFilterInfoList *filter_list = NULL, *last_entry = NULL;
1266
1267    QTAILQ_FOREACH(nc, &net_clients, next) {
1268        RxFilterInfoList *entry;
1269        RxFilterInfo *info;
1270
1271        if (has_name && strcmp(nc->name, name) != 0) {
1272            continue;
1273        }
1274
1275        /* only query rx-filter information of NIC */
1276        if (nc->info->type != NET_CLIENT_DRIVER_NIC) {
1277            if (has_name) {
1278                error_setg(errp, "net client(%s) isn't a NIC", name);
1279                return NULL;
1280            }
1281            continue;
1282        }
1283
1284        /* only query information on queue 0 since the info is per nic,
1285         * not per queue
1286         */
1287        if (nc->queue_index != 0)
1288            continue;
1289
1290        if (nc->info->query_rx_filter) {
1291            info = nc->info->query_rx_filter(nc);
1292            entry = g_malloc0(sizeof(*entry));
1293            entry->value = info;
1294
1295            if (!filter_list) {
1296                filter_list = entry;
1297            } else {
1298                last_entry->next = entry;
1299            }
1300            last_entry = entry;
1301        } else if (has_name) {
1302            error_setg(errp, "net client(%s) doesn't support"
1303                       " rx-filter querying", name);
1304            return NULL;
1305        }
1306
1307        if (has_name) {
1308            break;
1309        }
1310    }
1311
1312    if (filter_list == NULL && has_name) {
1313        error_setg(errp, "invalid net client name: %s", name);
1314    }
1315
1316    return filter_list;
1317}
1318
1319void hmp_info_network(Monitor *mon, const QDict *qdict)
1320{
1321    NetClientState *nc, *peer;
1322    NetClientDriver type;
1323
1324    net_hub_info(mon);
1325
1326    QTAILQ_FOREACH(nc, &net_clients, next) {
1327        peer = nc->peer;
1328        type = nc->info->type;
1329
1330        /* Skip if already printed in hub info */
1331        if (net_hub_id_for_client(nc, NULL) == 0) {
1332            continue;
1333        }
1334
1335        if (!peer || type == NET_CLIENT_DRIVER_NIC) {
1336            print_net_client(mon, nc);
1337        } /* else it's a netdev connected to a NIC, printed with the NIC */
1338        if (peer && type == NET_CLIENT_DRIVER_NIC) {
1339            monitor_printf(mon, " \\ ");
1340            print_net_client(mon, peer);
1341        }
1342    }
1343}
1344
1345void qmp_set_link(const char *name, bool up, Error **errp)
1346{
1347    NetClientState *ncs[MAX_QUEUE_NUM];
1348    NetClientState *nc;
1349    int queues, i;
1350
1351    queues = qemu_find_net_clients_except(name, ncs,
1352                                          NET_CLIENT_DRIVER__MAX,
1353                                          MAX_QUEUE_NUM);
1354
1355    if (queues == 0) {
1356        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1357                  "Device '%s' not found", name);
1358        return;
1359    }
1360    nc = ncs[0];
1361
1362    for (i = 0; i < queues; i++) {
1363        ncs[i]->link_down = !up;
1364    }
1365
1366    if (nc->info->link_status_changed) {
1367        nc->info->link_status_changed(nc);
1368    }
1369
1370    if (nc->peer) {
1371        /* Change peer link only if the peer is NIC and then notify peer.
1372         * If the peer is a HUBPORT or a backend, we do not change the
1373         * link status.
1374         *
1375         * This behavior is compatible with qemu hubs where there could be
1376         * multiple clients that can still communicate with each other in
1377         * disconnected mode. For now maintain this compatibility.
1378         */
1379        if (nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
1380            for (i = 0; i < queues; i++) {
1381                ncs[i]->peer->link_down = !up;
1382            }
1383        }
1384        if (nc->peer->info->link_status_changed) {
1385            nc->peer->info->link_status_changed(nc->peer);
1386        }
1387    }
1388}
1389
1390static void net_vm_change_state_handler(void *opaque, int running,
1391                                        RunState state)
1392{
1393    NetClientState *nc;
1394    NetClientState *tmp;
1395
1396    QTAILQ_FOREACH_SAFE(nc, &net_clients, next, tmp) {
1397        if (running) {
1398            /* Flush queued packets and wake up backends. */
1399            if (nc->peer && qemu_can_send_packet(nc)) {
1400                qemu_flush_queued_packets(nc->peer);
1401            }
1402        } else {
1403            /* Complete all queued packets, to guarantee we don't modify
1404             * state later when VM is not running.
1405             */
1406            qemu_flush_or_purge_queued_packets(nc, true);
1407        }
1408    }
1409}
1410
1411void net_cleanup(void)
1412{
1413    NetClientState *nc;
1414
1415    /* We may del multiple entries during qemu_del_net_client(),
1416     * so QTAILQ_FOREACH_SAFE() is also not safe here.
1417     */
1418    while (!QTAILQ_EMPTY(&net_clients)) {
1419        nc = QTAILQ_FIRST(&net_clients);
1420        if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
1421            qemu_del_nic(qemu_get_nic(nc));
1422        } else {
1423            qemu_del_net_client(nc);
1424        }
1425    }
1426
1427    qemu_del_vm_change_state_handler(net_change_state_entry);
1428}
1429
1430void net_check_clients(void)
1431{
1432    NetClientState *nc;
1433    int i;
1434
1435    net_hub_check_clients();
1436
1437    QTAILQ_FOREACH(nc, &net_clients, next) {
1438        if (!nc->peer) {
1439            warn_report("%s %s has no peer",
1440                        nc->info->type == NET_CLIENT_DRIVER_NIC
1441                        ? "nic" : "netdev",
1442                        nc->name);
1443        }
1444    }
1445
1446    /* Check that all NICs requested via -net nic actually got created.
1447     * NICs created via -device don't need to be checked here because
1448     * they are always instantiated.
1449     */
1450    for (i = 0; i < MAX_NICS; i++) {
1451        NICInfo *nd = &nd_table[i];
1452        if (nd->used && !nd->instantiated) {
1453            warn_report("requested NIC (%s, model %s) "
1454                        "was not created (not supported by this machine?)",
1455                        nd->name ? nd->name : "anonymous",
1456                        nd->model ? nd->model : "unspecified");
1457        }
1458    }
1459}
1460
1461static int net_init_client(void *dummy, QemuOpts *opts, Error **errp)
1462{
1463    return net_client_init(opts, false, errp);
1464}
1465
1466static int net_init_netdev(void *dummy, QemuOpts *opts, Error **errp)
1467{
1468    return net_client_init(opts, true, errp);
1469}
1470
1471/* For the convenience "--nic" parameter */
1472static int net_param_nic(void *dummy, QemuOpts *opts, Error **errp)
1473{
1474    char *mac, *nd_id;
1475    int idx, ret;
1476    NICInfo *ni;
1477    const char *type;
1478
1479    type = qemu_opt_get(opts, "type");
1480    if (type && g_str_equal(type, "none")) {
1481        return 0;    /* Nothing to do, default_net is cleared in vl.c */
1482    }
1483
1484    idx = nic_get_free_idx();
1485    if (idx == -1 || nb_nics >= MAX_NICS) {
1486        error_setg(errp, "no more on-board/default NIC slots available");
1487        return -1;
1488    }
1489
1490    if (!type) {
1491        qemu_opt_set(opts, "type", "user", &error_abort);
1492    }
1493
1494    ni = &nd_table[idx];
1495    memset(ni, 0, sizeof(*ni));
1496    ni->model = qemu_opt_get_del(opts, "model");
1497
1498    /* Create an ID if the user did not specify one */
1499    nd_id = g_strdup(qemu_opts_id(opts));
1500    if (!nd_id) {
1501        nd_id = g_strdup_printf("__org.qemu.nic%i\n", idx);
1502        qemu_opts_set_id(opts, nd_id);
1503    }
1504
1505    /* Handle MAC address */
1506    mac = qemu_opt_get_del(opts, "mac");
1507    if (mac) {
1508        ret = net_parse_macaddr(ni->macaddr.a, mac);
1509        g_free(mac);
1510        if (ret) {
1511            error_setg(errp, "invalid syntax for ethernet address");
1512            goto out;
1513        }
1514        if (is_multicast_ether_addr(ni->macaddr.a)) {
1515            error_setg(errp, "NIC cannot have multicast MAC address");
1516            ret = -1;
1517            goto out;
1518        }
1519    }
1520    qemu_macaddr_default_if_unset(&ni->macaddr);
1521
1522    ret = net_client_init(opts, true, errp);
1523    if (ret == 0) {
1524        ni->netdev = qemu_find_netdev(nd_id);
1525        ni->used = true;
1526        nb_nics++;
1527    }
1528
1529out:
1530    g_free(nd_id);
1531    return ret;
1532}
1533
1534int net_init_clients(Error **errp)
1535{
1536    net_change_state_entry =
1537        qemu_add_vm_change_state_handler(net_vm_change_state_handler, NULL);
1538
1539    QTAILQ_INIT(&net_clients);
1540
1541    if (qemu_opts_foreach(qemu_find_opts("netdev"),
1542                          net_init_netdev, NULL, errp)) {
1543        return -1;
1544    }
1545
1546    if (qemu_opts_foreach(qemu_find_opts("nic"), net_param_nic, NULL, errp)) {
1547        return -1;
1548    }
1549
1550    if (qemu_opts_foreach(qemu_find_opts("net"), net_init_client, NULL, errp)) {
1551        return -1;
1552    }
1553
1554    return 0;
1555}
1556
1557int net_client_parse(QemuOptsList *opts_list, const char *optarg)
1558{
1559    if (!qemu_opts_parse_noisily(opts_list, optarg, true)) {
1560        return -1;
1561    }
1562
1563    return 0;
1564}
1565
1566/* From FreeBSD */
1567/* XXX: optimize */
1568uint32_t net_crc32(const uint8_t *p, int len)
1569{
1570    uint32_t crc;
1571    int carry, i, j;
1572    uint8_t b;
1573
1574    crc = 0xffffffff;
1575    for (i = 0; i < len; i++) {
1576        b = *p++;
1577        for (j = 0; j < 8; j++) {
1578            carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
1579            crc <<= 1;
1580            b >>= 1;
1581            if (carry) {
1582                crc = ((crc ^ POLYNOMIAL_BE) | carry);
1583            }
1584        }
1585    }
1586
1587    return crc;
1588}
1589
1590uint32_t net_crc32_le(const uint8_t *p, int len)
1591{
1592    uint32_t crc;
1593    int carry, i, j;
1594    uint8_t b;
1595
1596    crc = 0xffffffff;
1597    for (i = 0; i < len; i++) {
1598        b = *p++;
1599        for (j = 0; j < 8; j++) {
1600            carry = (crc & 0x1) ^ (b & 0x01);
1601            crc >>= 1;
1602            b >>= 1;
1603            if (carry) {
1604                crc ^= POLYNOMIAL_LE;
1605            }
1606        }
1607    }
1608
1609    return crc;
1610}
1611
1612QemuOptsList qemu_netdev_opts = {
1613    .name = "netdev",
1614    .implied_opt_name = "type",
1615    .head = QTAILQ_HEAD_INITIALIZER(qemu_netdev_opts.head),
1616    .desc = {
1617        /*
1618         * no elements => accept any params
1619         * validation will happen later
1620         */
1621        { /* end of list */ }
1622    },
1623};
1624
1625QemuOptsList qemu_nic_opts = {
1626    .name = "nic",
1627    .implied_opt_name = "type",
1628    .head = QTAILQ_HEAD_INITIALIZER(qemu_nic_opts.head),
1629    .desc = {
1630        /*
1631         * no elements => accept any params
1632         * validation will happen later
1633         */
1634        { /* end of list */ }
1635    },
1636};
1637
1638QemuOptsList qemu_net_opts = {
1639    .name = "net",
1640    .implied_opt_name = "type",
1641    .head = QTAILQ_HEAD_INITIALIZER(qemu_net_opts.head),
1642    .desc = {
1643        /*
1644         * no elements => accept any params
1645         * validation will happen later
1646         */
1647        { /* end of list */ }
1648    },
1649};
1650
1651void net_socket_rs_init(SocketReadState *rs,
1652                        SocketReadStateFinalize *finalize,
1653                        bool vnet_hdr)
1654{
1655    rs->state = 0;
1656    rs->vnet_hdr = vnet_hdr;
1657    rs->index = 0;
1658    rs->packet_len = 0;
1659    rs->vnet_hdr_len = 0;
1660    memset(rs->buf, 0, sizeof(rs->buf));
1661    rs->finalize = finalize;
1662}
1663
1664/*
1665 * Returns
1666 * 0: success
1667 * -1: error occurs
1668 */
1669int net_fill_rstate(SocketReadState *rs, const uint8_t *buf, int size)
1670{
1671    unsigned int l;
1672
1673    while (size > 0) {
1674        /* Reassemble a packet from the network.
1675         * 0 = getting length.
1676         * 1 = getting vnet header length.
1677         * 2 = getting data.
1678         */
1679        switch (rs->state) {
1680        case 0:
1681            l = 4 - rs->index;
1682            if (l > size) {
1683                l = size;
1684            }
1685            memcpy(rs->buf + rs->index, buf, l);
1686            buf += l;
1687            size -= l;
1688            rs->index += l;
1689            if (rs->index == 4) {
1690                /* got length */
1691                rs->packet_len = ntohl(*(uint32_t *)rs->buf);
1692                rs->index = 0;
1693                if (rs->vnet_hdr) {
1694                    rs->state = 1;
1695                } else {
1696                    rs->state = 2;
1697                    rs->vnet_hdr_len = 0;
1698                }
1699            }
1700            break;
1701        case 1:
1702            l = 4 - rs->index;
1703            if (l > size) {
1704                l = size;
1705            }
1706            memcpy(rs->buf + rs->index, buf, l);
1707            buf += l;
1708            size -= l;
1709            rs->index += l;
1710            if (rs->index == 4) {
1711                /* got vnet header length */
1712                rs->vnet_hdr_len = ntohl(*(uint32_t *)rs->buf);
1713                rs->index = 0;
1714                rs->state = 2;
1715            }
1716            break;
1717        case 2:
1718            l = rs->packet_len - rs->index;
1719            if (l > size) {
1720                l = size;
1721            }
1722            if (rs->index + l <= sizeof(rs->buf)) {
1723                memcpy(rs->buf + rs->index, buf, l);
1724            } else {
1725                fprintf(stderr, "serious error: oversized packet received,"
1726                    "connection terminated.\n");
1727                rs->index = rs->state = 0;
1728                return -1;
1729            }
1730
1731            rs->index += l;
1732            buf += l;
1733            size -= l;
1734            if (rs->index >= rs->packet_len) {
1735                rs->index = 0;
1736                rs->state = 0;
1737                assert(rs->finalize);
1738                rs->finalize(rs);
1739            }
1740            break;
1741        }
1742    }
1743
1744    assert(size == 0);
1745    return 0;
1746}
1747