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