crypto: add compat cast5_set_key with nettle < 3.0.0
[qemu/ar7.git] / net / net.c
blob1a78edf751646b45fe8721a8961d490aac2a8b7d
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
24 #include "qemu/osdep.h"
26 #include "net/net.h"
27 #include "clients.h"
28 #include "hub.h"
29 #include "net/slirp.h"
30 #include "net/eth.h"
31 #include "util.h"
33 #include "monitor/monitor.h"
34 #include "qemu-common.h"
35 #include "qapi/qmp/qerror.h"
36 #include "qemu/error-report.h"
37 #include "qemu/sockets.h"
38 #include "qemu/config-file.h"
39 #include "qmp-commands.h"
40 #include "hw/qdev.h"
41 #include "qemu/iov.h"
42 #include "qemu/main-loop.h"
43 #include "qapi-visit.h"
44 #include "qapi/opts-visitor.h"
45 #include "sysemu/sysemu.h"
46 #include "net/filter.h"
47 #include "qapi/string-output-visitor.h"
49 /* Net bridge is currently not supported for W32. */
50 #if !defined(_WIN32)
51 # define CONFIG_NET_BRIDGE
52 #endif
54 static VMChangeStateEntry *net_change_state_entry;
55 static QTAILQ_HEAD(, NetClientState) net_clients;
57 const char *host_net_devices[] = {
58 "tap",
59 "socket",
60 "dump",
61 #ifdef CONFIG_NET_BRIDGE
62 "bridge",
63 #endif
64 #ifdef CONFIG_NETMAP
65 "netmap",
66 #endif
67 #ifdef CONFIG_SLIRP
68 "user",
69 #endif
70 #ifdef CONFIG_VDE
71 "vde",
72 #endif
73 "vhost-user",
74 NULL,
77 int default_net = 1;
79 /***********************************************************/
80 /* network device redirectors */
82 #if defined(DEBUG_NET)
83 static void hex_dump(FILE *f, const uint8_t *buf, int size)
85 int len, i, j, c;
87 for(i=0;i<size;i+=16) {
88 len = size - i;
89 if (len > 16)
90 len = 16;
91 fprintf(f, "%08x ", i);
92 for(j=0;j<16;j++) {
93 if (j < len)
94 fprintf(f, " %02x", buf[i+j]);
95 else
96 fprintf(f, " ");
98 fprintf(f, " ");
99 for(j=0;j<len;j++) {
100 c = buf[i+j];
101 if (c < ' ' || c > '~')
102 c = '.';
103 fprintf(f, "%c", c);
105 fprintf(f, "\n");
108 #endif
110 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
112 const char *p, *p1;
113 int len;
114 p = *pp;
115 p1 = strchr(p, sep);
116 if (!p1)
117 return -1;
118 len = p1 - p;
119 p1++;
120 if (buf_size > 0) {
121 if (len > buf_size - 1)
122 len = buf_size - 1;
123 memcpy(buf, p, len);
124 buf[len] = '\0';
126 *pp = p1;
127 return 0;
130 int parse_host_port(struct sockaddr_in *saddr, const char *str)
132 char buf[512];
133 struct hostent *he;
134 const char *p, *r;
135 int port;
137 p = str;
138 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
139 return -1;
140 saddr->sin_family = AF_INET;
141 if (buf[0] == '\0') {
142 saddr->sin_addr.s_addr = 0;
143 } else {
144 if (qemu_isdigit(buf[0])) {
145 if (!inet_aton(buf, &saddr->sin_addr))
146 return -1;
147 } else {
148 if ((he = gethostbyname(buf)) == NULL)
149 return - 1;
150 saddr->sin_addr = *(struct in_addr *)he->h_addr;
153 port = strtol(p, (char **)&r, 0);
154 if (r == p)
155 return -1;
156 saddr->sin_port = htons(port);
157 return 0;
160 char *qemu_mac_strdup_printf(const uint8_t *macaddr)
162 return g_strdup_printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
163 macaddr[0], macaddr[1], macaddr[2],
164 macaddr[3], macaddr[4], macaddr[5]);
167 void qemu_format_nic_info_str(NetClientState *nc, uint8_t macaddr[6])
169 snprintf(nc->info_str, sizeof(nc->info_str),
170 "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
171 nc->model,
172 macaddr[0], macaddr[1], macaddr[2],
173 macaddr[3], macaddr[4], macaddr[5]);
176 static int mac_table[256] = {0};
178 static void qemu_macaddr_set_used(MACAddr *macaddr)
180 int index;
182 for (index = 0x56; index < 0xFF; index++) {
183 if (macaddr->a[5] == index) {
184 mac_table[index]++;
189 static void qemu_macaddr_set_free(MACAddr *macaddr)
191 int index;
192 static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
194 if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
195 return;
197 for (index = 0x56; index < 0xFF; index++) {
198 if (macaddr->a[5] == index) {
199 mac_table[index]--;
204 static int qemu_macaddr_get_free(void)
206 int index;
208 for (index = 0x56; index < 0xFF; index++) {
209 if (mac_table[index] == 0) {
210 return index;
214 return -1;
217 void qemu_macaddr_default_if_unset(MACAddr *macaddr)
219 static const MACAddr zero = { .a = { 0,0,0,0,0,0 } };
220 static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
222 if (memcmp(macaddr, &zero, sizeof(zero)) != 0) {
223 if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
224 return;
225 } else {
226 qemu_macaddr_set_used(macaddr);
227 return;
231 macaddr->a[0] = 0x52;
232 macaddr->a[1] = 0x54;
233 macaddr->a[2] = 0x00;
234 macaddr->a[3] = 0x12;
235 macaddr->a[4] = 0x34;
236 macaddr->a[5] = qemu_macaddr_get_free();
237 qemu_macaddr_set_used(macaddr);
241 * Generate a name for net client
243 * Only net clients created with the legacy -net option and NICs need this.
245 static char *assign_name(NetClientState *nc1, const char *model)
247 NetClientState *nc;
248 int id = 0;
250 QTAILQ_FOREACH(nc, &net_clients, next) {
251 if (nc == nc1) {
252 continue;
254 if (strcmp(nc->model, model) == 0) {
255 id++;
259 return g_strdup_printf("%s.%d", model, id);
262 static void qemu_net_client_destructor(NetClientState *nc)
264 g_free(nc);
267 static void qemu_net_client_setup(NetClientState *nc,
268 NetClientInfo *info,
269 NetClientState *peer,
270 const char *model,
271 const char *name,
272 NetClientDestructor *destructor)
274 nc->info = info;
275 nc->model = g_strdup(model);
276 if (name) {
277 nc->name = g_strdup(name);
278 } else {
279 nc->name = assign_name(nc, model);
282 if (peer) {
283 assert(!peer->peer);
284 nc->peer = peer;
285 peer->peer = nc;
287 QTAILQ_INSERT_TAIL(&net_clients, nc, next);
289 nc->incoming_queue = qemu_new_net_queue(qemu_deliver_packet_iov, nc);
290 nc->destructor = destructor;
291 QTAILQ_INIT(&nc->filters);
294 NetClientState *qemu_new_net_client(NetClientInfo *info,
295 NetClientState *peer,
296 const char *model,
297 const char *name)
299 NetClientState *nc;
301 assert(info->size >= sizeof(NetClientState));
303 nc = g_malloc0(info->size);
304 qemu_net_client_setup(nc, info, peer, model, name,
305 qemu_net_client_destructor);
307 return nc;
310 NICState *qemu_new_nic(NetClientInfo *info,
311 NICConf *conf,
312 const char *model,
313 const char *name,
314 void *opaque)
316 NetClientState **peers = conf->peers.ncs;
317 NICState *nic;
318 int i, queues = MAX(1, conf->peers.queues);
320 assert(info->type == NET_CLIENT_OPTIONS_KIND_NIC);
321 assert(info->size >= sizeof(NICState));
323 nic = g_malloc0(info->size + sizeof(NetClientState) * queues);
324 nic->ncs = (void *)nic + info->size;
325 nic->conf = conf;
326 nic->opaque = opaque;
328 for (i = 0; i < queues; i++) {
329 qemu_net_client_setup(&nic->ncs[i], info, peers[i], model, name,
330 NULL);
331 nic->ncs[i].queue_index = i;
334 return nic;
337 NetClientState *qemu_get_subqueue(NICState *nic, int queue_index)
339 return nic->ncs + queue_index;
342 NetClientState *qemu_get_queue(NICState *nic)
344 return qemu_get_subqueue(nic, 0);
347 NICState *qemu_get_nic(NetClientState *nc)
349 NetClientState *nc0 = nc - nc->queue_index;
351 return (NICState *)((void *)nc0 - nc->info->size);
354 void *qemu_get_nic_opaque(NetClientState *nc)
356 NICState *nic = qemu_get_nic(nc);
358 return nic->opaque;
361 static void qemu_cleanup_net_client(NetClientState *nc)
363 QTAILQ_REMOVE(&net_clients, nc, next);
365 if (nc->info->cleanup) {
366 nc->info->cleanup(nc);
370 static void qemu_free_net_client(NetClientState *nc)
372 if (nc->incoming_queue) {
373 qemu_del_net_queue(nc->incoming_queue);
375 if (nc->peer) {
376 nc->peer->peer = NULL;
378 g_free(nc->name);
379 g_free(nc->model);
380 if (nc->destructor) {
381 nc->destructor(nc);
385 void qemu_del_net_client(NetClientState *nc)
387 NetClientState *ncs[MAX_QUEUE_NUM];
388 int queues, i;
389 NetFilterState *nf, *next;
391 assert(nc->info->type != NET_CLIENT_OPTIONS_KIND_NIC);
393 /* If the NetClientState belongs to a multiqueue backend, we will change all
394 * other NetClientStates also.
396 queues = qemu_find_net_clients_except(nc->name, ncs,
397 NET_CLIENT_OPTIONS_KIND_NIC,
398 MAX_QUEUE_NUM);
399 assert(queues != 0);
401 QTAILQ_FOREACH_SAFE(nf, &nc->filters, next, next) {
402 object_unparent(OBJECT(nf));
405 /* If there is a peer NIC, delete and cleanup client, but do not free. */
406 if (nc->peer && nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
407 NICState *nic = qemu_get_nic(nc->peer);
408 if (nic->peer_deleted) {
409 return;
411 nic->peer_deleted = true;
413 for (i = 0; i < queues; i++) {
414 ncs[i]->peer->link_down = true;
417 if (nc->peer->info->link_status_changed) {
418 nc->peer->info->link_status_changed(nc->peer);
421 for (i = 0; i < queues; i++) {
422 qemu_cleanup_net_client(ncs[i]);
425 return;
428 for (i = 0; i < queues; i++) {
429 qemu_cleanup_net_client(ncs[i]);
430 qemu_free_net_client(ncs[i]);
434 void qemu_del_nic(NICState *nic)
436 int i, queues = MAX(nic->conf->peers.queues, 1);
438 qemu_macaddr_set_free(&nic->conf->macaddr);
440 /* If this is a peer NIC and peer has already been deleted, free it now. */
441 if (nic->peer_deleted) {
442 for (i = 0; i < queues; i++) {
443 qemu_free_net_client(qemu_get_subqueue(nic, i)->peer);
447 for (i = queues - 1; i >= 0; i--) {
448 NetClientState *nc = qemu_get_subqueue(nic, i);
450 qemu_cleanup_net_client(nc);
451 qemu_free_net_client(nc);
454 g_free(nic);
457 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
459 NetClientState *nc;
461 QTAILQ_FOREACH(nc, &net_clients, next) {
462 if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
463 if (nc->queue_index == 0) {
464 func(qemu_get_nic(nc), opaque);
470 bool qemu_has_ufo(NetClientState *nc)
472 if (!nc || !nc->info->has_ufo) {
473 return false;
476 return nc->info->has_ufo(nc);
479 bool qemu_has_vnet_hdr(NetClientState *nc)
481 if (!nc || !nc->info->has_vnet_hdr) {
482 return false;
485 return nc->info->has_vnet_hdr(nc);
488 bool qemu_has_vnet_hdr_len(NetClientState *nc, int len)
490 if (!nc || !nc->info->has_vnet_hdr_len) {
491 return false;
494 return nc->info->has_vnet_hdr_len(nc, len);
497 void qemu_using_vnet_hdr(NetClientState *nc, bool enable)
499 if (!nc || !nc->info->using_vnet_hdr) {
500 return;
503 nc->info->using_vnet_hdr(nc, enable);
506 void qemu_set_offload(NetClientState *nc, int csum, int tso4, int tso6,
507 int ecn, int ufo)
509 if (!nc || !nc->info->set_offload) {
510 return;
513 nc->info->set_offload(nc, csum, tso4, tso6, ecn, ufo);
516 void qemu_set_vnet_hdr_len(NetClientState *nc, int len)
518 if (!nc || !nc->info->set_vnet_hdr_len) {
519 return;
522 nc->info->set_vnet_hdr_len(nc, len);
525 int qemu_set_vnet_le(NetClientState *nc, bool is_le)
527 #ifdef HOST_WORDS_BIGENDIAN
528 if (!nc || !nc->info->set_vnet_le) {
529 return -ENOSYS;
532 return nc->info->set_vnet_le(nc, is_le);
533 #else
534 return 0;
535 #endif
538 int qemu_set_vnet_be(NetClientState *nc, bool is_be)
540 #ifdef HOST_WORDS_BIGENDIAN
541 return 0;
542 #else
543 if (!nc || !nc->info->set_vnet_be) {
544 return -ENOSYS;
547 return nc->info->set_vnet_be(nc, is_be);
548 #endif
551 int qemu_can_send_packet(NetClientState *sender)
553 int vm_running = runstate_is_running();
555 if (!vm_running) {
556 return 0;
559 if (!sender->peer) {
560 return 1;
563 if (sender->peer->receive_disabled) {
564 return 0;
565 } else if (sender->peer->info->can_receive &&
566 !sender->peer->info->can_receive(sender->peer)) {
567 return 0;
569 return 1;
572 static ssize_t filter_receive_iov(NetClientState *nc,
573 NetFilterDirection direction,
574 NetClientState *sender,
575 unsigned flags,
576 const struct iovec *iov,
577 int iovcnt,
578 NetPacketSent *sent_cb)
580 ssize_t ret = 0;
581 NetFilterState *nf = NULL;
583 if (direction == NET_FILTER_DIRECTION_TX) {
584 QTAILQ_FOREACH(nf, &nc->filters, next) {
585 ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
586 iovcnt, sent_cb);
587 if (ret) {
588 return ret;
591 } else {
592 QTAILQ_FOREACH_REVERSE(nf, &nc->filters, NetFilterHead, next) {
593 ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
594 iovcnt, sent_cb);
595 if (ret) {
596 return ret;
601 return ret;
604 static ssize_t filter_receive(NetClientState *nc,
605 NetFilterDirection direction,
606 NetClientState *sender,
607 unsigned flags,
608 const uint8_t *data,
609 size_t size,
610 NetPacketSent *sent_cb)
612 struct iovec iov = {
613 .iov_base = (void *)data,
614 .iov_len = size
617 return filter_receive_iov(nc, direction, sender, flags, &iov, 1, sent_cb);
620 void qemu_purge_queued_packets(NetClientState *nc)
622 if (!nc->peer) {
623 return;
626 qemu_net_queue_purge(nc->peer->incoming_queue, nc);
629 static
630 void qemu_flush_or_purge_queued_packets(NetClientState *nc, bool purge)
632 nc->receive_disabled = 0;
634 if (nc->peer && nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_HUBPORT) {
635 if (net_hub_flush(nc->peer)) {
636 qemu_notify_event();
639 if (qemu_net_queue_flush(nc->incoming_queue)) {
640 /* We emptied the queue successfully, signal to the IO thread to repoll
641 * the file descriptor (for tap, for example).
643 qemu_notify_event();
644 } else if (purge) {
645 /* Unable to empty the queue, purge remaining packets */
646 qemu_net_queue_purge(nc->incoming_queue, nc);
650 void qemu_flush_queued_packets(NetClientState *nc)
652 qemu_flush_or_purge_queued_packets(nc, false);
655 static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
656 unsigned flags,
657 const uint8_t *buf, int size,
658 NetPacketSent *sent_cb)
660 NetQueue *queue;
661 int ret;
663 #ifdef DEBUG_NET
664 printf("qemu_send_packet_async:\n");
665 hex_dump(stdout, buf, size);
666 #endif
668 if (sender->link_down || !sender->peer) {
669 return size;
672 /* Let filters handle the packet first */
673 ret = filter_receive(sender, NET_FILTER_DIRECTION_TX,
674 sender, flags, buf, size, sent_cb);
675 if (ret) {
676 return ret;
679 ret = filter_receive(sender->peer, NET_FILTER_DIRECTION_RX,
680 sender, flags, buf, size, sent_cb);
681 if (ret) {
682 return ret;
685 queue = sender->peer->incoming_queue;
687 return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
690 ssize_t qemu_send_packet_async(NetClientState *sender,
691 const uint8_t *buf, int size,
692 NetPacketSent *sent_cb)
694 return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
695 buf, size, sent_cb);
698 void qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size)
700 qemu_send_packet_async(nc, buf, size, NULL);
703 ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size)
705 return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW,
706 buf, size, NULL);
709 static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
710 int iovcnt, unsigned flags)
712 uint8_t buf[NET_BUFSIZE];
713 uint8_t *buffer;
714 size_t offset;
716 if (iovcnt == 1) {
717 buffer = iov[0].iov_base;
718 offset = iov[0].iov_len;
719 } else {
720 buffer = buf;
721 offset = iov_to_buf(iov, iovcnt, 0, buf, sizeof(buf));
724 if (flags & QEMU_NET_PACKET_FLAG_RAW && nc->info->receive_raw) {
725 return nc->info->receive_raw(nc, buffer, offset);
726 } else {
727 return nc->info->receive(nc, buffer, offset);
731 ssize_t qemu_deliver_packet_iov(NetClientState *sender,
732 unsigned flags,
733 const struct iovec *iov,
734 int iovcnt,
735 void *opaque)
737 NetClientState *nc = opaque;
738 int ret;
740 if (nc->link_down) {
741 return iov_size(iov, iovcnt);
744 if (nc->receive_disabled) {
745 return 0;
748 if (nc->info->receive_iov) {
749 ret = nc->info->receive_iov(nc, iov, iovcnt);
750 } else {
751 ret = nc_sendv_compat(nc, iov, iovcnt, flags);
754 if (ret == 0) {
755 nc->receive_disabled = 1;
758 return ret;
761 ssize_t qemu_sendv_packet_async(NetClientState *sender,
762 const struct iovec *iov, int iovcnt,
763 NetPacketSent *sent_cb)
765 NetQueue *queue;
766 int ret;
768 if (sender->link_down || !sender->peer) {
769 return iov_size(iov, iovcnt);
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;
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;
785 queue = sender->peer->incoming_queue;
787 return qemu_net_queue_send_iov(queue, sender,
788 QEMU_NET_PACKET_FLAG_NONE,
789 iov, iovcnt, sent_cb);
792 ssize_t
793 qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt)
795 return qemu_sendv_packet_async(nc, iov, iovcnt, NULL);
798 NetClientState *qemu_find_netdev(const char *id)
800 NetClientState *nc;
802 QTAILQ_FOREACH(nc, &net_clients, next) {
803 if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC)
804 continue;
805 if (!strcmp(nc->name, id)) {
806 return nc;
810 return NULL;
813 int qemu_find_net_clients_except(const char *id, NetClientState **ncs,
814 NetClientOptionsKind type, int max)
816 NetClientState *nc;
817 int ret = 0;
819 QTAILQ_FOREACH(nc, &net_clients, next) {
820 if (nc->info->type == type) {
821 continue;
823 if (!id || !strcmp(nc->name, id)) {
824 if (ret < max) {
825 ncs[ret] = nc;
827 ret++;
831 return ret;
834 static int nic_get_free_idx(void)
836 int index;
838 for (index = 0; index < MAX_NICS; index++)
839 if (!nd_table[index].used)
840 return index;
841 return -1;
844 int qemu_show_nic_models(const char *arg, const char *const *models)
846 int i;
848 if (!arg || !is_help_option(arg)) {
849 return 0;
852 fprintf(stderr, "qemu: Supported NIC models: ");
853 for (i = 0 ; models[i]; i++)
854 fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
855 return 1;
858 void qemu_check_nic_model(NICInfo *nd, const char *model)
860 const char *models[2];
862 models[0] = model;
863 models[1] = NULL;
865 if (qemu_show_nic_models(nd->model, models))
866 exit(0);
867 if (qemu_find_nic_model(nd, models, model) < 0)
868 exit(1);
871 int qemu_find_nic_model(NICInfo *nd, const char * const *models,
872 const char *default_model)
874 int i;
876 if (!nd->model)
877 nd->model = g_strdup(default_model);
879 for (i = 0 ; models[i]; i++) {
880 if (strcmp(nd->model, models[i]) == 0)
881 return i;
884 error_report("Unsupported NIC model: %s", nd->model);
885 return -1;
888 static int net_init_nic(const NetClientOptions *opts, const char *name,
889 NetClientState *peer, Error **errp)
891 int idx;
892 NICInfo *nd;
893 const NetLegacyNicOptions *nic;
895 assert(opts->type == NET_CLIENT_OPTIONS_KIND_NIC);
896 nic = opts->u.nic.data;
898 idx = nic_get_free_idx();
899 if (idx == -1 || nb_nics >= MAX_NICS) {
900 error_setg(errp, "too many NICs");
901 return -1;
904 nd = &nd_table[idx];
906 memset(nd, 0, sizeof(*nd));
908 if (nic->has_netdev) {
909 nd->netdev = qemu_find_netdev(nic->netdev);
910 if (!nd->netdev) {
911 error_setg(errp, "netdev '%s' not found", nic->netdev);
912 return -1;
914 } else {
915 assert(peer);
916 nd->netdev = peer;
918 nd->name = g_strdup(name);
919 if (nic->has_model) {
920 nd->model = g_strdup(nic->model);
922 if (nic->has_addr) {
923 nd->devaddr = g_strdup(nic->addr);
926 if (nic->has_macaddr &&
927 net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {
928 error_setg(errp, "invalid syntax for ethernet address");
929 return -1;
931 if (nic->has_macaddr &&
932 is_multicast_ether_addr(nd->macaddr.a)) {
933 error_setg(errp,
934 "NIC cannot have multicast MAC address (odd 1st byte)");
935 return -1;
937 qemu_macaddr_default_if_unset(&nd->macaddr);
939 if (nic->has_vectors) {
940 if (nic->vectors > 0x7ffffff) {
941 error_setg(errp, "invalid # of vectors: %"PRIu32, nic->vectors);
942 return -1;
944 nd->nvectors = nic->vectors;
945 } else {
946 nd->nvectors = DEV_NVECTORS_UNSPECIFIED;
949 nd->used = 1;
950 nb_nics++;
952 return idx;
956 static int (* const net_client_init_fun[NET_CLIENT_OPTIONS_KIND__MAX])(
957 const NetClientOptions *opts,
958 const char *name,
959 NetClientState *peer, Error **errp) = {
960 [NET_CLIENT_OPTIONS_KIND_NIC] = net_init_nic,
961 #ifdef CONFIG_SLIRP
962 [NET_CLIENT_OPTIONS_KIND_USER] = net_init_slirp,
963 #endif
964 [NET_CLIENT_OPTIONS_KIND_TAP] = net_init_tap,
965 [NET_CLIENT_OPTIONS_KIND_SOCKET] = net_init_socket,
966 #ifdef CONFIG_VDE
967 [NET_CLIENT_OPTIONS_KIND_VDE] = net_init_vde,
968 #endif
969 #ifdef CONFIG_NETMAP
970 [NET_CLIENT_OPTIONS_KIND_NETMAP] = net_init_netmap,
971 #endif
972 [NET_CLIENT_OPTIONS_KIND_DUMP] = net_init_dump,
973 #ifdef CONFIG_NET_BRIDGE
974 [NET_CLIENT_OPTIONS_KIND_BRIDGE] = net_init_bridge,
975 #endif
976 [NET_CLIENT_OPTIONS_KIND_HUBPORT] = net_init_hubport,
977 #ifdef CONFIG_VHOST_NET_USED
978 [NET_CLIENT_OPTIONS_KIND_VHOST_USER] = net_init_vhost_user,
979 #endif
980 #ifdef CONFIG_L2TPV3
981 [NET_CLIENT_OPTIONS_KIND_L2TPV3] = net_init_l2tpv3,
982 #endif
986 static int net_client_init1(const void *object, int is_netdev, Error **errp)
988 const NetClientOptions *opts;
989 const char *name;
990 NetClientState *peer = NULL;
992 if (is_netdev) {
993 const Netdev *netdev = object;
994 opts = netdev->opts;
995 name = netdev->id;
997 if (opts->type == NET_CLIENT_OPTIONS_KIND_DUMP ||
998 opts->type == NET_CLIENT_OPTIONS_KIND_NIC ||
999 !net_client_init_fun[opts->type]) {
1000 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
1001 "a netdev backend type");
1002 return -1;
1004 } else {
1005 const NetLegacy *net = object;
1006 opts = net->opts;
1007 /* missing optional values have been initialized to "all bits zero" */
1008 name = net->has_id ? net->id : net->name;
1010 if (opts->type == NET_CLIENT_OPTIONS_KIND_NONE) {
1011 return 0; /* nothing to do */
1013 if (opts->type == NET_CLIENT_OPTIONS_KIND_HUBPORT) {
1014 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
1015 "a net type");
1016 return -1;
1019 if (!net_client_init_fun[opts->type]) {
1020 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
1021 "a net backend type (maybe it is not compiled "
1022 "into this binary)");
1023 return -1;
1026 /* Do not add to a vlan if it's a nic with a netdev= parameter. */
1027 if (opts->type != NET_CLIENT_OPTIONS_KIND_NIC ||
1028 !opts->u.nic.data->has_netdev) {
1029 peer = net_hub_add_port(net->has_vlan ? net->vlan : 0, NULL);
1033 if (net_client_init_fun[opts->type](opts, name, peer, errp) < 0) {
1034 /* FIXME drop when all init functions store an Error */
1035 if (errp && !*errp) {
1036 error_setg(errp, QERR_DEVICE_INIT_FAILED,
1037 NetClientOptionsKind_lookup[opts->type]);
1039 return -1;
1041 return 0;
1045 int net_client_init(QemuOpts *opts, int is_netdev, Error **errp)
1047 void *object = NULL;
1048 Error *err = NULL;
1049 int ret = -1;
1050 OptsVisitor *ov = opts_visitor_new(opts);
1051 Visitor *v = opts_get_visitor(ov);
1054 /* Parse convenience option format ip6-net=fec0::0[/64] */
1055 const char *ip6_net = qemu_opt_get(opts, "ip6-net");
1057 if (ip6_net) {
1058 char buf[strlen(ip6_net) + 1];
1060 if (get_str_sep(buf, sizeof(buf), &ip6_net, '/') < 0) {
1061 /* Default 64bit prefix length. */
1062 qemu_opt_set(opts, "ip6-prefix", ip6_net, &error_abort);
1063 qemu_opt_set_number(opts, "ip6-prefixlen", 64, &error_abort);
1064 } else {
1065 /* User-specified prefix length. */
1066 unsigned long len;
1067 int err;
1069 qemu_opt_set(opts, "ip6-prefix", buf, &error_abort);
1070 err = qemu_strtoul(ip6_net, NULL, 10, &len);
1072 if (err) {
1073 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1074 "ip6-prefix", "a number");
1075 } else {
1076 qemu_opt_set_number(opts, "ip6-prefixlen", len,
1077 &error_abort);
1080 qemu_opt_unset(opts, "ip6-net");
1084 if (is_netdev) {
1085 visit_type_Netdev(v, NULL, (Netdev **)&object, &err);
1086 } else {
1087 visit_type_NetLegacy(v, NULL, (NetLegacy **)&object, &err);
1090 if (!err) {
1091 ret = net_client_init1(object, is_netdev, &err);
1094 if (is_netdev) {
1095 qapi_free_Netdev(object);
1096 } else {
1097 qapi_free_NetLegacy(object);
1100 error_propagate(errp, err);
1101 return ret;
1105 static int net_host_check_device(const char *device)
1107 int i;
1108 for (i = 0; host_net_devices[i]; i++) {
1109 if (!strncmp(host_net_devices[i], device,
1110 strlen(host_net_devices[i]))) {
1111 return 1;
1115 return 0;
1118 void hmp_host_net_add(Monitor *mon, const QDict *qdict)
1120 const char *device = qdict_get_str(qdict, "device");
1121 const char *opts_str = qdict_get_try_str(qdict, "opts");
1122 Error *local_err = NULL;
1123 QemuOpts *opts;
1125 if (!net_host_check_device(device)) {
1126 monitor_printf(mon, "invalid host network device %s\n", device);
1127 return;
1130 opts = qemu_opts_parse_noisily(qemu_find_opts("net"),
1131 opts_str ? opts_str : "", false);
1132 if (!opts) {
1133 return;
1136 qemu_opt_set(opts, "type", device, &error_abort);
1138 net_client_init(opts, 0, &local_err);
1139 if (local_err) {
1140 error_report_err(local_err);
1141 monitor_printf(mon, "adding host network device %s failed\n", device);
1145 void hmp_host_net_remove(Monitor *mon, const QDict *qdict)
1147 NetClientState *nc;
1148 int vlan_id = qdict_get_int(qdict, "vlan_id");
1149 const char *device = qdict_get_str(qdict, "device");
1151 nc = net_hub_find_client_by_name(vlan_id, device);
1152 if (!nc) {
1153 error_report("Host network device '%s' on hub '%d' not found",
1154 device, vlan_id);
1155 return;
1157 if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
1158 error_report("invalid host network device '%s'", device);
1159 return;
1162 qemu_del_net_client(nc->peer);
1163 qemu_del_net_client(nc);
1166 void netdev_add(QemuOpts *opts, Error **errp)
1168 net_client_init(opts, 1, errp);
1171 void qmp_netdev_add(QDict *qdict, QObject **ret, Error **errp)
1173 Error *local_err = NULL;
1174 QemuOptsList *opts_list;
1175 QemuOpts *opts;
1177 opts_list = qemu_find_opts_err("netdev", &local_err);
1178 if (local_err) {
1179 goto out;
1182 opts = qemu_opts_from_qdict(opts_list, qdict, &local_err);
1183 if (local_err) {
1184 goto out;
1187 netdev_add(opts, &local_err);
1188 if (local_err) {
1189 qemu_opts_del(opts);
1190 goto out;
1193 out:
1194 error_propagate(errp, local_err);
1197 void qmp_netdev_del(const char *id, Error **errp)
1199 NetClientState *nc;
1200 QemuOpts *opts;
1202 nc = qemu_find_netdev(id);
1203 if (!nc) {
1204 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1205 "Device '%s' not found", id);
1206 return;
1209 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), id);
1210 if (!opts) {
1211 error_setg(errp, "Device '%s' is not a netdev", id);
1212 return;
1215 qemu_del_net_client(nc);
1216 qemu_opts_del(opts);
1219 static void netfilter_print_info(Monitor *mon, NetFilterState *nf)
1221 char *str;
1222 ObjectProperty *prop;
1223 ObjectPropertyIterator iter;
1224 StringOutputVisitor *ov;
1226 /* generate info str */
1227 object_property_iter_init(&iter, OBJECT(nf));
1228 while ((prop = object_property_iter_next(&iter))) {
1229 if (!strcmp(prop->name, "type")) {
1230 continue;
1232 ov = string_output_visitor_new(false);
1233 object_property_get(OBJECT(nf), string_output_get_visitor(ov),
1234 prop->name, NULL);
1235 str = string_output_get_string(ov);
1236 string_output_visitor_cleanup(ov);
1237 monitor_printf(mon, ",%s=%s", prop->name, str);
1238 g_free(str);
1240 monitor_printf(mon, "\n");
1243 void print_net_client(Monitor *mon, NetClientState *nc)
1245 NetFilterState *nf;
1247 monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
1248 nc->queue_index,
1249 NetClientOptionsKind_lookup[nc->info->type],
1250 nc->info_str);
1251 if (!QTAILQ_EMPTY(&nc->filters)) {
1252 monitor_printf(mon, "filters:\n");
1254 QTAILQ_FOREACH(nf, &nc->filters, next) {
1255 char *path = object_get_canonical_path_component(OBJECT(nf));
1257 monitor_printf(mon, " - %s: type=%s", path,
1258 object_get_typename(OBJECT(nf)));
1259 netfilter_print_info(mon, nf);
1260 g_free(path);
1264 RxFilterInfoList *qmp_query_rx_filter(bool has_name, const char *name,
1265 Error **errp)
1267 NetClientState *nc;
1268 RxFilterInfoList *filter_list = NULL, *last_entry = NULL;
1270 QTAILQ_FOREACH(nc, &net_clients, next) {
1271 RxFilterInfoList *entry;
1272 RxFilterInfo *info;
1274 if (has_name && strcmp(nc->name, name) != 0) {
1275 continue;
1278 /* only query rx-filter information of NIC */
1279 if (nc->info->type != NET_CLIENT_OPTIONS_KIND_NIC) {
1280 if (has_name) {
1281 error_setg(errp, "net client(%s) isn't a NIC", name);
1282 return NULL;
1284 continue;
1287 /* only query information on queue 0 since the info is per nic,
1288 * not per queue
1290 if (nc->queue_index != 0)
1291 continue;
1293 if (nc->info->query_rx_filter) {
1294 info = nc->info->query_rx_filter(nc);
1295 entry = g_malloc0(sizeof(*entry));
1296 entry->value = info;
1298 if (!filter_list) {
1299 filter_list = entry;
1300 } else {
1301 last_entry->next = entry;
1303 last_entry = entry;
1304 } else if (has_name) {
1305 error_setg(errp, "net client(%s) doesn't support"
1306 " rx-filter querying", name);
1307 return NULL;
1310 if (has_name) {
1311 break;
1315 if (filter_list == NULL && has_name) {
1316 error_setg(errp, "invalid net client name: %s", name);
1319 return filter_list;
1322 void hmp_info_network(Monitor *mon, const QDict *qdict)
1324 NetClientState *nc, *peer;
1325 NetClientOptionsKind type;
1327 net_hub_info(mon);
1329 QTAILQ_FOREACH(nc, &net_clients, next) {
1330 peer = nc->peer;
1331 type = nc->info->type;
1333 /* Skip if already printed in hub info */
1334 if (net_hub_id_for_client(nc, NULL) == 0) {
1335 continue;
1338 if (!peer || type == NET_CLIENT_OPTIONS_KIND_NIC) {
1339 print_net_client(mon, nc);
1340 } /* else it's a netdev connected to a NIC, printed with the NIC */
1341 if (peer && type == NET_CLIENT_OPTIONS_KIND_NIC) {
1342 monitor_printf(mon, " \\ ");
1343 print_net_client(mon, peer);
1348 void qmp_set_link(const char *name, bool up, Error **errp)
1350 NetClientState *ncs[MAX_QUEUE_NUM];
1351 NetClientState *nc;
1352 int queues, i;
1354 queues = qemu_find_net_clients_except(name, ncs,
1355 NET_CLIENT_OPTIONS_KIND__MAX,
1356 MAX_QUEUE_NUM);
1358 if (queues == 0) {
1359 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1360 "Device '%s' not found", name);
1361 return;
1363 nc = ncs[0];
1365 for (i = 0; i < queues; i++) {
1366 ncs[i]->link_down = !up;
1369 if (nc->info->link_status_changed) {
1370 nc->info->link_status_changed(nc);
1373 if (nc->peer) {
1374 /* Change peer link only if the peer is NIC and then notify peer.
1375 * If the peer is a HUBPORT or a backend, we do not change the
1376 * link status.
1378 * This behavior is compatible with qemu vlans where there could be
1379 * multiple clients that can still communicate with each other in
1380 * disconnected mode. For now maintain this compatibility.
1382 if (nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
1383 for (i = 0; i < queues; i++) {
1384 ncs[i]->peer->link_down = !up;
1387 if (nc->peer->info->link_status_changed) {
1388 nc->peer->info->link_status_changed(nc->peer);
1393 static void net_vm_change_state_handler(void *opaque, int running,
1394 RunState state)
1396 NetClientState *nc;
1397 NetClientState *tmp;
1399 QTAILQ_FOREACH_SAFE(nc, &net_clients, next, tmp) {
1400 if (running) {
1401 /* Flush queued packets and wake up backends. */
1402 if (nc->peer && qemu_can_send_packet(nc)) {
1403 qemu_flush_queued_packets(nc->peer);
1405 } else {
1406 /* Complete all queued packets, to guarantee we don't modify
1407 * state later when VM is not running.
1409 qemu_flush_or_purge_queued_packets(nc, true);
1414 void net_cleanup(void)
1416 NetClientState *nc;
1418 /* We may del multiple entries during qemu_del_net_client(),
1419 * so QTAILQ_FOREACH_SAFE() is also not safe here.
1421 while (!QTAILQ_EMPTY(&net_clients)) {
1422 nc = QTAILQ_FIRST(&net_clients);
1423 if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
1424 qemu_del_nic(qemu_get_nic(nc));
1425 } else {
1426 qemu_del_net_client(nc);
1430 qemu_del_vm_change_state_handler(net_change_state_entry);
1433 void net_check_clients(void)
1435 NetClientState *nc;
1436 int i;
1438 /* Don't warn about the default network setup that you get if
1439 * no command line -net or -netdev options are specified. There
1440 * are two cases that we would otherwise complain about:
1441 * (1) board doesn't support a NIC but the implicit "-net nic"
1442 * requested one
1443 * (2) CONFIG_SLIRP not set, in which case the implicit "-net nic"
1444 * sets up a nic that isn't connected to anything.
1446 if (default_net) {
1447 return;
1450 net_hub_check_clients();
1452 QTAILQ_FOREACH(nc, &net_clients, next) {
1453 if (!nc->peer) {
1454 fprintf(stderr, "Warning: %s %s has no peer\n",
1455 nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC ?
1456 "nic" : "netdev", nc->name);
1460 /* Check that all NICs requested via -net nic actually got created.
1461 * NICs created via -device don't need to be checked here because
1462 * they are always instantiated.
1464 for (i = 0; i < MAX_NICS; i++) {
1465 NICInfo *nd = &nd_table[i];
1466 if (nd->used && !nd->instantiated) {
1467 fprintf(stderr, "Warning: requested NIC (%s, model %s) "
1468 "was not created (not supported by this machine?)\n",
1469 nd->name ? nd->name : "anonymous",
1470 nd->model ? nd->model : "unspecified");
1475 static int net_init_client(void *dummy, QemuOpts *opts, Error **errp)
1477 Error *local_err = NULL;
1479 net_client_init(opts, 0, &local_err);
1480 if (local_err) {
1481 error_report_err(local_err);
1482 return -1;
1485 return 0;
1488 static int net_init_netdev(void *dummy, QemuOpts *opts, Error **errp)
1490 Error *local_err = NULL;
1491 int ret;
1493 ret = net_client_init(opts, 1, &local_err);
1494 if (local_err) {
1495 error_report_err(local_err);
1496 return -1;
1499 return ret;
1502 int net_init_clients(void)
1504 QemuOptsList *net = qemu_find_opts("net");
1506 if (default_net) {
1507 /* if no clients, we use a default config */
1508 qemu_opts_set(net, NULL, "type", "nic", &error_abort);
1509 #ifdef CONFIG_SLIRP
1510 qemu_opts_set(net, NULL, "type", "user", &error_abort);
1511 #endif
1514 net_change_state_entry =
1515 qemu_add_vm_change_state_handler(net_vm_change_state_handler, NULL);
1517 QTAILQ_INIT(&net_clients);
1519 if (qemu_opts_foreach(qemu_find_opts("netdev"),
1520 net_init_netdev, NULL, NULL)) {
1521 return -1;
1524 if (qemu_opts_foreach(net, net_init_client, NULL, NULL)) {
1525 return -1;
1528 return 0;
1531 int net_client_parse(QemuOptsList *opts_list, const char *optarg)
1533 #if defined(CONFIG_SLIRP)
1534 int ret;
1535 if (net_slirp_parse_legacy(opts_list, optarg, &ret)) {
1536 return ret;
1538 #endif
1540 if (!qemu_opts_parse_noisily(opts_list, optarg, true)) {
1541 return -1;
1544 default_net = 0;
1545 return 0;
1548 /* From FreeBSD */
1549 /* XXX: optimize */
1550 unsigned compute_mcast_idx(const uint8_t *ep)
1552 uint32_t crc;
1553 int carry, i, j;
1554 uint8_t b;
1556 crc = 0xffffffff;
1557 for (i = 0; i < 6; i++) {
1558 b = *ep++;
1559 for (j = 0; j < 8; j++) {
1560 carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
1561 crc <<= 1;
1562 b >>= 1;
1563 if (carry) {
1564 crc = ((crc ^ POLYNOMIAL) | carry);
1568 return crc >> 26;
1571 QemuOptsList qemu_netdev_opts = {
1572 .name = "netdev",
1573 .implied_opt_name = "type",
1574 .head = QTAILQ_HEAD_INITIALIZER(qemu_netdev_opts.head),
1575 .desc = {
1577 * no elements => accept any params
1578 * validation will happen later
1580 { /* end of list */ }
1584 QemuOptsList qemu_net_opts = {
1585 .name = "net",
1586 .implied_opt_name = "type",
1587 .head = QTAILQ_HEAD_INITIALIZER(qemu_net_opts.head),
1588 .desc = {
1590 * no elements => accept any params
1591 * validation will happen later
1593 { /* end of list */ }