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