x86: Add AMX XTILECFG and XTILEDATA components
[qemu/armbru.git] / net / net.c
blobf0d14dbfc1f0f929eb93da9e789dcb4560366054
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.
25 #include "qemu/osdep.h"
26 #include "qemu-common.h"
28 #include "net/net.h"
29 #include "clients.h"
30 #include "hub.h"
31 #include "hw/qdev-properties.h"
32 #include "net/slirp.h"
33 #include "net/eth.h"
34 #include "util.h"
36 #include "monitor/monitor.h"
37 #include "qemu/help_option.h"
38 #include "qapi/qapi-commands-net.h"
39 #include "qapi/qapi-visit-net.h"
40 #include "qapi/qmp/qdict.h"
41 #include "qapi/qmp/qerror.h"
42 #include "qemu/error-report.h"
43 #include "qemu/sockets.h"
44 #include "qemu/cutils.h"
45 #include "qemu/config-file.h"
46 #include "qemu/ctype.h"
47 #include "qemu/id.h"
48 #include "qemu/iov.h"
49 #include "qemu/qemu-print.h"
50 #include "qemu/main-loop.h"
51 #include "qemu/option.h"
52 #include "qapi/error.h"
53 #include "qapi/opts-visitor.h"
54 #include "sysemu/runstate.h"
55 #include "net/colo-compare.h"
56 #include "net/filter.h"
57 #include "qapi/string-output-visitor.h"
59 /* Net bridge is currently not supported for W32. */
60 #if !defined(_WIN32)
61 # define CONFIG_NET_BRIDGE
62 #endif
64 static VMChangeStateEntry *net_change_state_entry;
65 static QTAILQ_HEAD(, NetClientState) net_clients;
67 /***********************************************************/
68 /* network device redirectors */
70 int parse_host_port(struct sockaddr_in *saddr, const char *str,
71 Error **errp)
73 gchar **substrings;
74 struct hostent *he;
75 const char *addr, *p, *r;
76 int port, ret = 0;
78 memset(saddr, 0, sizeof(*saddr));
80 substrings = g_strsplit(str, ":", 2);
81 if (!substrings || !substrings[0] || !substrings[1]) {
82 error_setg(errp, "host address '%s' doesn't contain ':' "
83 "separating host from port", str);
84 ret = -1;
85 goto out;
88 addr = substrings[0];
89 p = substrings[1];
91 saddr->sin_family = AF_INET;
92 if (addr[0] == '\0') {
93 saddr->sin_addr.s_addr = 0;
94 } else {
95 if (qemu_isdigit(addr[0])) {
96 if (!inet_aton(addr, &saddr->sin_addr)) {
97 error_setg(errp, "host address '%s' is not a valid "
98 "IPv4 address", addr);
99 ret = -1;
100 goto out;
102 } else {
103 he = gethostbyname(addr);
104 if (he == NULL) {
105 error_setg(errp, "can't resolve host address '%s'", addr);
106 ret = -1;
107 goto out;
109 saddr->sin_addr = *(struct in_addr *)he->h_addr;
112 port = strtol(p, (char **)&r, 0);
113 if (r == p) {
114 error_setg(errp, "port number '%s' is invalid", p);
115 ret = -1;
116 goto out;
118 saddr->sin_port = htons(port);
120 out:
121 g_strfreev(substrings);
122 return ret;
125 char *qemu_mac_strdup_printf(const uint8_t *macaddr)
127 return g_strdup_printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
128 macaddr[0], macaddr[1], macaddr[2],
129 macaddr[3], macaddr[4], macaddr[5]);
132 void qemu_format_nic_info_str(NetClientState *nc, uint8_t macaddr[6])
134 snprintf(nc->info_str, sizeof(nc->info_str),
135 "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
136 nc->model,
137 macaddr[0], macaddr[1], macaddr[2],
138 macaddr[3], macaddr[4], macaddr[5]);
141 static int mac_table[256] = {0};
143 static void qemu_macaddr_set_used(MACAddr *macaddr)
145 int index;
147 for (index = 0x56; index < 0xFF; index++) {
148 if (macaddr->a[5] == index) {
149 mac_table[index]++;
154 static void qemu_macaddr_set_free(MACAddr *macaddr)
156 int index;
157 static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
159 if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
160 return;
162 for (index = 0x56; index < 0xFF; index++) {
163 if (macaddr->a[5] == index) {
164 mac_table[index]--;
169 static int qemu_macaddr_get_free(void)
171 int index;
173 for (index = 0x56; index < 0xFF; index++) {
174 if (mac_table[index] == 0) {
175 return index;
179 return -1;
182 void qemu_macaddr_default_if_unset(MACAddr *macaddr)
184 static const MACAddr zero = { .a = { 0,0,0,0,0,0 } };
185 static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
187 if (memcmp(macaddr, &zero, sizeof(zero)) != 0) {
188 if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
189 return;
190 } else {
191 qemu_macaddr_set_used(macaddr);
192 return;
196 macaddr->a[0] = 0x52;
197 macaddr->a[1] = 0x54;
198 macaddr->a[2] = 0x00;
199 macaddr->a[3] = 0x12;
200 macaddr->a[4] = 0x34;
201 macaddr->a[5] = qemu_macaddr_get_free();
202 qemu_macaddr_set_used(macaddr);
206 * Generate a name for net client
208 * Only net clients created with the legacy -net option and NICs need this.
210 static char *assign_name(NetClientState *nc1, const char *model)
212 NetClientState *nc;
213 int id = 0;
215 QTAILQ_FOREACH(nc, &net_clients, next) {
216 if (nc == nc1) {
217 continue;
219 if (strcmp(nc->model, model) == 0) {
220 id++;
224 return g_strdup_printf("%s.%d", model, id);
227 static void qemu_net_client_destructor(NetClientState *nc)
229 g_free(nc);
231 static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
232 unsigned flags,
233 const struct iovec *iov,
234 int iovcnt,
235 void *opaque);
237 static void qemu_net_client_setup(NetClientState *nc,
238 NetClientInfo *info,
239 NetClientState *peer,
240 const char *model,
241 const char *name,
242 NetClientDestructor *destructor,
243 bool is_datapath)
245 nc->info = info;
246 nc->model = g_strdup(model);
247 if (name) {
248 nc->name = g_strdup(name);
249 } else {
250 nc->name = assign_name(nc, model);
253 if (peer) {
254 assert(!peer->peer);
255 nc->peer = peer;
256 peer->peer = nc;
258 QTAILQ_INSERT_TAIL(&net_clients, nc, next);
260 nc->incoming_queue = qemu_new_net_queue(qemu_deliver_packet_iov, nc);
261 nc->destructor = destructor;
262 nc->is_datapath = is_datapath;
263 QTAILQ_INIT(&nc->filters);
266 NetClientState *qemu_new_net_client(NetClientInfo *info,
267 NetClientState *peer,
268 const char *model,
269 const char *name)
271 NetClientState *nc;
273 assert(info->size >= sizeof(NetClientState));
275 nc = g_malloc0(info->size);
276 qemu_net_client_setup(nc, info, peer, model, name,
277 qemu_net_client_destructor, true);
279 return nc;
282 NetClientState *qemu_new_net_control_client(NetClientInfo *info,
283 NetClientState *peer,
284 const char *model,
285 const char *name)
287 NetClientState *nc;
289 assert(info->size >= sizeof(NetClientState));
291 nc = g_malloc0(info->size);
292 qemu_net_client_setup(nc, info, peer, model, name,
293 qemu_net_client_destructor, false);
295 return nc;
298 NICState *qemu_new_nic(NetClientInfo *info,
299 NICConf *conf,
300 const char *model,
301 const char *name,
302 void *opaque)
304 NetClientState **peers = conf->peers.ncs;
305 NICState *nic;
306 int i, queues = MAX(1, conf->peers.queues);
308 assert(info->type == NET_CLIENT_DRIVER_NIC);
309 assert(info->size >= sizeof(NICState));
311 nic = g_malloc0(info->size + sizeof(NetClientState) * queues);
312 nic->ncs = (void *)nic + info->size;
313 nic->conf = conf;
314 nic->opaque = opaque;
316 for (i = 0; i < queues; i++) {
317 qemu_net_client_setup(&nic->ncs[i], info, peers[i], model, name,
318 NULL, true);
319 nic->ncs[i].queue_index = i;
322 return nic;
325 NetClientState *qemu_get_subqueue(NICState *nic, int queue_index)
327 return nic->ncs + queue_index;
330 NetClientState *qemu_get_queue(NICState *nic)
332 return qemu_get_subqueue(nic, 0);
335 NICState *qemu_get_nic(NetClientState *nc)
337 NetClientState *nc0 = nc - nc->queue_index;
339 return (NICState *)((void *)nc0 - nc->info->size);
342 void *qemu_get_nic_opaque(NetClientState *nc)
344 NICState *nic = qemu_get_nic(nc);
346 return nic->opaque;
349 NetClientState *qemu_get_peer(NetClientState *nc, int queue_index)
351 assert(nc != NULL);
352 NetClientState *ncs = nc + queue_index;
353 return ncs->peer;
356 static void qemu_cleanup_net_client(NetClientState *nc)
358 QTAILQ_REMOVE(&net_clients, nc, next);
360 if (nc->info->cleanup) {
361 nc->info->cleanup(nc);
365 static void qemu_free_net_client(NetClientState *nc)
367 if (nc->incoming_queue) {
368 qemu_del_net_queue(nc->incoming_queue);
370 if (nc->peer) {
371 nc->peer->peer = NULL;
373 g_free(nc->name);
374 g_free(nc->model);
375 if (nc->destructor) {
376 nc->destructor(nc);
380 void qemu_del_net_client(NetClientState *nc)
382 NetClientState *ncs[MAX_QUEUE_NUM];
383 int queues, i;
384 NetFilterState *nf, *next;
386 assert(nc->info->type != NET_CLIENT_DRIVER_NIC);
388 /* If the NetClientState belongs to a multiqueue backend, we will change all
389 * other NetClientStates also.
391 queues = qemu_find_net_clients_except(nc->name, ncs,
392 NET_CLIENT_DRIVER_NIC,
393 MAX_QUEUE_NUM);
394 assert(queues != 0);
396 QTAILQ_FOREACH_SAFE(nf, &nc->filters, next, next) {
397 object_unparent(OBJECT(nf));
400 /* If there is a peer NIC, delete and cleanup client, but do not free. */
401 if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
402 NICState *nic = qemu_get_nic(nc->peer);
403 if (nic->peer_deleted) {
404 return;
406 nic->peer_deleted = true;
408 for (i = 0; i < queues; i++) {
409 ncs[i]->peer->link_down = true;
412 if (nc->peer->info->link_status_changed) {
413 nc->peer->info->link_status_changed(nc->peer);
416 for (i = 0; i < queues; i++) {
417 qemu_cleanup_net_client(ncs[i]);
420 return;
423 for (i = 0; i < queues; i++) {
424 qemu_cleanup_net_client(ncs[i]);
425 qemu_free_net_client(ncs[i]);
429 void qemu_del_nic(NICState *nic)
431 int i, queues = MAX(nic->conf->peers.queues, 1);
433 qemu_macaddr_set_free(&nic->conf->macaddr);
435 for (i = 0; i < queues; i++) {
436 NetClientState *nc = qemu_get_subqueue(nic, i);
437 /* If this is a peer NIC and peer has already been deleted, free it now. */
438 if (nic->peer_deleted) {
439 qemu_free_net_client(nc->peer);
440 } else if (nc->peer) {
441 /* if there are RX packets pending, complete them */
442 qemu_purge_queued_packets(nc->peer);
446 for (i = queues - 1; i >= 0; i--) {
447 NetClientState *nc = qemu_get_subqueue(nic, i);
449 qemu_cleanup_net_client(nc);
450 qemu_free_net_client(nc);
453 g_free(nic);
456 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
458 NetClientState *nc;
460 QTAILQ_FOREACH(nc, &net_clients, next) {
461 if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
462 if (nc->queue_index == 0) {
463 func(qemu_get_nic(nc), opaque);
469 bool qemu_has_ufo(NetClientState *nc)
471 if (!nc || !nc->info->has_ufo) {
472 return false;
475 return nc->info->has_ufo(nc);
478 bool qemu_has_vnet_hdr(NetClientState *nc)
480 if (!nc || !nc->info->has_vnet_hdr) {
481 return false;
484 return nc->info->has_vnet_hdr(nc);
487 bool qemu_has_vnet_hdr_len(NetClientState *nc, int len)
489 if (!nc || !nc->info->has_vnet_hdr_len) {
490 return false;
493 return nc->info->has_vnet_hdr_len(nc, len);
496 void qemu_using_vnet_hdr(NetClientState *nc, bool enable)
498 if (!nc || !nc->info->using_vnet_hdr) {
499 return;
502 nc->info->using_vnet_hdr(nc, enable);
505 void qemu_set_offload(NetClientState *nc, int csum, int tso4, int tso6,
506 int ecn, int ufo)
508 if (!nc || !nc->info->set_offload) {
509 return;
512 nc->info->set_offload(nc, csum, tso4, tso6, ecn, ufo);
515 void qemu_set_vnet_hdr_len(NetClientState *nc, int len)
517 if (!nc || !nc->info->set_vnet_hdr_len) {
518 return;
521 nc->vnet_hdr_len = len;
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_receive_packet(NetClientState *nc)
553 if (nc->receive_disabled) {
554 return 0;
555 } else if (nc->info->can_receive &&
556 !nc->info->can_receive(nc)) {
557 return 0;
559 return 1;
562 int qemu_can_send_packet(NetClientState *sender)
564 int vm_running = runstate_is_running();
566 if (!vm_running) {
567 return 0;
570 if (!sender->peer) {
571 return 1;
574 return qemu_can_receive_packet(sender->peer);
577 static ssize_t filter_receive_iov(NetClientState *nc,
578 NetFilterDirection direction,
579 NetClientState *sender,
580 unsigned flags,
581 const struct iovec *iov,
582 int iovcnt,
583 NetPacketSent *sent_cb)
585 ssize_t ret = 0;
586 NetFilterState *nf = NULL;
588 if (direction == NET_FILTER_DIRECTION_TX) {
589 QTAILQ_FOREACH(nf, &nc->filters, next) {
590 ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
591 iovcnt, sent_cb);
592 if (ret) {
593 return ret;
596 } else {
597 QTAILQ_FOREACH_REVERSE(nf, &nc->filters, next) {
598 ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
599 iovcnt, sent_cb);
600 if (ret) {
601 return ret;
606 return ret;
609 static ssize_t filter_receive(NetClientState *nc,
610 NetFilterDirection direction,
611 NetClientState *sender,
612 unsigned flags,
613 const uint8_t *data,
614 size_t size,
615 NetPacketSent *sent_cb)
617 struct iovec iov = {
618 .iov_base = (void *)data,
619 .iov_len = size
622 return filter_receive_iov(nc, direction, sender, flags, &iov, 1, sent_cb);
625 void qemu_purge_queued_packets(NetClientState *nc)
627 if (!nc->peer) {
628 return;
631 qemu_net_queue_purge(nc->peer->incoming_queue, nc);
634 void qemu_flush_or_purge_queued_packets(NetClientState *nc, bool purge)
636 nc->receive_disabled = 0;
638 if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_HUBPORT) {
639 if (net_hub_flush(nc->peer)) {
640 qemu_notify_event();
643 if (qemu_net_queue_flush(nc->incoming_queue)) {
644 /* We emptied the queue successfully, signal to the IO thread to repoll
645 * the file descriptor (for tap, for example).
647 qemu_notify_event();
648 } else if (purge) {
649 /* Unable to empty the queue, purge remaining packets */
650 qemu_net_queue_purge(nc->incoming_queue, nc->peer);
654 void qemu_flush_queued_packets(NetClientState *nc)
656 qemu_flush_or_purge_queued_packets(nc, false);
659 static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
660 unsigned flags,
661 const uint8_t *buf, int size,
662 NetPacketSent *sent_cb)
664 NetQueue *queue;
665 int ret;
667 #ifdef DEBUG_NET
668 printf("qemu_send_packet_async:\n");
669 qemu_hexdump(stdout, "net", buf, size);
670 #endif
672 if (sender->link_down || !sender->peer) {
673 return size;
676 /* Let filters handle the packet first */
677 ret = filter_receive(sender, NET_FILTER_DIRECTION_TX,
678 sender, flags, buf, size, sent_cb);
679 if (ret) {
680 return ret;
683 ret = filter_receive(sender->peer, NET_FILTER_DIRECTION_RX,
684 sender, flags, buf, size, sent_cb);
685 if (ret) {
686 return ret;
689 queue = sender->peer->incoming_queue;
691 return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
694 ssize_t qemu_send_packet_async(NetClientState *sender,
695 const uint8_t *buf, int size,
696 NetPacketSent *sent_cb)
698 return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
699 buf, size, sent_cb);
702 ssize_t qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size)
704 return qemu_send_packet_async(nc, buf, size, NULL);
707 ssize_t qemu_receive_packet(NetClientState *nc, const uint8_t *buf, int size)
709 if (!qemu_can_receive_packet(nc)) {
710 return 0;
713 return qemu_net_queue_receive(nc->incoming_queue, buf, size);
716 ssize_t qemu_receive_packet_iov(NetClientState *nc, const struct iovec *iov,
717 int iovcnt)
719 if (!qemu_can_receive_packet(nc)) {
720 return 0;
723 return qemu_net_queue_receive_iov(nc->incoming_queue, iov, iovcnt);
726 ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size)
728 return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW,
729 buf, size, NULL);
732 static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
733 int iovcnt, unsigned flags)
735 uint8_t *buf = NULL;
736 uint8_t *buffer;
737 size_t offset;
738 ssize_t ret;
740 if (iovcnt == 1) {
741 buffer = iov[0].iov_base;
742 offset = iov[0].iov_len;
743 } else {
744 offset = iov_size(iov, iovcnt);
745 if (offset > NET_BUFSIZE) {
746 return -1;
748 buf = g_malloc(offset);
749 buffer = buf;
750 offset = iov_to_buf(iov, iovcnt, 0, buf, offset);
753 if (flags & QEMU_NET_PACKET_FLAG_RAW && nc->info->receive_raw) {
754 ret = nc->info->receive_raw(nc, buffer, offset);
755 } else {
756 ret = nc->info->receive(nc, buffer, offset);
759 g_free(buf);
760 return ret;
763 static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
764 unsigned flags,
765 const struct iovec *iov,
766 int iovcnt,
767 void *opaque)
769 NetClientState *nc = opaque;
770 int ret;
773 if (nc->link_down) {
774 return iov_size(iov, iovcnt);
777 if (nc->receive_disabled) {
778 return 0;
781 if (nc->info->receive_iov && !(flags & QEMU_NET_PACKET_FLAG_RAW)) {
782 ret = nc->info->receive_iov(nc, iov, iovcnt);
783 } else {
784 ret = nc_sendv_compat(nc, iov, iovcnt, flags);
787 if (ret == 0) {
788 nc->receive_disabled = 1;
791 return ret;
794 ssize_t qemu_sendv_packet_async(NetClientState *sender,
795 const struct iovec *iov, int iovcnt,
796 NetPacketSent *sent_cb)
798 NetQueue *queue;
799 size_t size = iov_size(iov, iovcnt);
800 int ret;
802 if (size > NET_BUFSIZE) {
803 return size;
806 if (sender->link_down || !sender->peer) {
807 return size;
810 /* Let filters handle the packet first */
811 ret = filter_receive_iov(sender, NET_FILTER_DIRECTION_TX, sender,
812 QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
813 if (ret) {
814 return ret;
817 ret = filter_receive_iov(sender->peer, NET_FILTER_DIRECTION_RX, sender,
818 QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
819 if (ret) {
820 return ret;
823 queue = sender->peer->incoming_queue;
825 return qemu_net_queue_send_iov(queue, sender,
826 QEMU_NET_PACKET_FLAG_NONE,
827 iov, iovcnt, sent_cb);
830 ssize_t
831 qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt)
833 return qemu_sendv_packet_async(nc, iov, iovcnt, NULL);
836 NetClientState *qemu_find_netdev(const char *id)
838 NetClientState *nc;
840 QTAILQ_FOREACH(nc, &net_clients, next) {
841 if (nc->info->type == NET_CLIENT_DRIVER_NIC)
842 continue;
843 if (!strcmp(nc->name, id)) {
844 return nc;
848 return NULL;
851 int qemu_find_net_clients_except(const char *id, NetClientState **ncs,
852 NetClientDriver type, int max)
854 NetClientState *nc;
855 int ret = 0;
857 QTAILQ_FOREACH(nc, &net_clients, next) {
858 if (nc->info->type == type) {
859 continue;
861 if (!id || !strcmp(nc->name, id)) {
862 if (ret < max) {
863 ncs[ret] = nc;
865 ret++;
869 return ret;
872 static int nic_get_free_idx(void)
874 int index;
876 for (index = 0; index < MAX_NICS; index++)
877 if (!nd_table[index].used)
878 return index;
879 return -1;
882 int qemu_show_nic_models(const char *arg, const char *const *models)
884 int i;
886 if (!arg || !is_help_option(arg)) {
887 return 0;
890 printf("Supported NIC models:\n");
891 for (i = 0 ; models[i]; i++) {
892 printf("%s\n", models[i]);
894 return 1;
897 void qemu_check_nic_model(NICInfo *nd, const char *model)
899 const char *models[2];
901 models[0] = model;
902 models[1] = NULL;
904 if (qemu_show_nic_models(nd->model, models))
905 exit(0);
906 if (qemu_find_nic_model(nd, models, model) < 0)
907 exit(1);
910 int qemu_find_nic_model(NICInfo *nd, const char * const *models,
911 const char *default_model)
913 int i;
915 if (!nd->model)
916 nd->model = g_strdup(default_model);
918 for (i = 0 ; models[i]; i++) {
919 if (strcmp(nd->model, models[i]) == 0)
920 return i;
923 error_report("Unsupported NIC model: %s", nd->model);
924 return -1;
927 static int net_init_nic(const Netdev *netdev, const char *name,
928 NetClientState *peer, Error **errp)
930 int idx;
931 NICInfo *nd;
932 const NetLegacyNicOptions *nic;
934 assert(netdev->type == NET_CLIENT_DRIVER_NIC);
935 nic = &netdev->u.nic;
937 idx = nic_get_free_idx();
938 if (idx == -1 || nb_nics >= MAX_NICS) {
939 error_setg(errp, "too many NICs");
940 return -1;
943 nd = &nd_table[idx];
945 memset(nd, 0, sizeof(*nd));
947 if (nic->has_netdev) {
948 nd->netdev = qemu_find_netdev(nic->netdev);
949 if (!nd->netdev) {
950 error_setg(errp, "netdev '%s' not found", nic->netdev);
951 return -1;
953 } else {
954 assert(peer);
955 nd->netdev = peer;
957 nd->name = g_strdup(name);
958 if (nic->has_model) {
959 nd->model = g_strdup(nic->model);
961 if (nic->has_addr) {
962 nd->devaddr = g_strdup(nic->addr);
965 if (nic->has_macaddr &&
966 net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {
967 error_setg(errp, "invalid syntax for ethernet address");
968 return -1;
970 if (nic->has_macaddr &&
971 is_multicast_ether_addr(nd->macaddr.a)) {
972 error_setg(errp,
973 "NIC cannot have multicast MAC address (odd 1st byte)");
974 return -1;
976 qemu_macaddr_default_if_unset(&nd->macaddr);
978 if (nic->has_vectors) {
979 if (nic->vectors > 0x7ffffff) {
980 error_setg(errp, "invalid # of vectors: %"PRIu32, nic->vectors);
981 return -1;
983 nd->nvectors = nic->vectors;
984 } else {
985 nd->nvectors = DEV_NVECTORS_UNSPECIFIED;
988 nd->used = 1;
989 nb_nics++;
991 return idx;
995 static int (* const net_client_init_fun[NET_CLIENT_DRIVER__MAX])(
996 const Netdev *netdev,
997 const char *name,
998 NetClientState *peer, Error **errp) = {
999 [NET_CLIENT_DRIVER_NIC] = net_init_nic,
1000 #ifdef CONFIG_SLIRP
1001 [NET_CLIENT_DRIVER_USER] = net_init_slirp,
1002 #endif
1003 [NET_CLIENT_DRIVER_TAP] = net_init_tap,
1004 [NET_CLIENT_DRIVER_SOCKET] = net_init_socket,
1005 #ifdef CONFIG_VDE
1006 [NET_CLIENT_DRIVER_VDE] = net_init_vde,
1007 #endif
1008 #ifdef CONFIG_NETMAP
1009 [NET_CLIENT_DRIVER_NETMAP] = net_init_netmap,
1010 #endif
1011 #ifdef CONFIG_NET_BRIDGE
1012 [NET_CLIENT_DRIVER_BRIDGE] = net_init_bridge,
1013 #endif
1014 [NET_CLIENT_DRIVER_HUBPORT] = net_init_hubport,
1015 #ifdef CONFIG_VHOST_NET_USER
1016 [NET_CLIENT_DRIVER_VHOST_USER] = net_init_vhost_user,
1017 #endif
1018 #ifdef CONFIG_VHOST_NET_VDPA
1019 [NET_CLIENT_DRIVER_VHOST_VDPA] = net_init_vhost_vdpa,
1020 #endif
1021 #ifdef CONFIG_L2TPV3
1022 [NET_CLIENT_DRIVER_L2TPV3] = net_init_l2tpv3,
1023 #endif
1027 static int net_client_init1(const Netdev *netdev, bool is_netdev, Error **errp)
1029 NetClientState *peer = NULL;
1030 NetClientState *nc;
1032 if (is_netdev) {
1033 if (netdev->type == NET_CLIENT_DRIVER_NIC ||
1034 !net_client_init_fun[netdev->type]) {
1035 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
1036 "a netdev backend type");
1037 return -1;
1039 } else {
1040 if (netdev->type == NET_CLIENT_DRIVER_NONE) {
1041 return 0; /* nothing to do */
1043 if (netdev->type == NET_CLIENT_DRIVER_HUBPORT ||
1044 !net_client_init_fun[netdev->type]) {
1045 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
1046 "a net backend type (maybe it is not compiled "
1047 "into this binary)");
1048 return -1;
1051 /* Do not add to a hub if it's a nic with a netdev= parameter. */
1052 if (netdev->type != NET_CLIENT_DRIVER_NIC ||
1053 !netdev->u.nic.has_netdev) {
1054 peer = net_hub_add_port(0, NULL, NULL);
1058 nc = qemu_find_netdev(netdev->id);
1059 if (nc) {
1060 error_setg(errp, "Duplicate ID '%s'", netdev->id);
1061 return -1;
1064 if (net_client_init_fun[netdev->type](netdev, netdev->id, peer, errp) < 0) {
1065 /* FIXME drop when all init functions store an Error */
1066 if (errp && !*errp) {
1067 error_setg(errp, "Device '%s' could not be initialized",
1068 NetClientDriver_str(netdev->type));
1070 return -1;
1073 if (is_netdev) {
1074 nc = qemu_find_netdev(netdev->id);
1075 assert(nc);
1076 nc->is_netdev = true;
1079 return 0;
1082 void show_netdevs(void)
1084 int idx;
1085 const char *available_netdevs[] = {
1086 "socket",
1087 "hubport",
1088 "tap",
1089 #ifdef CONFIG_SLIRP
1090 "user",
1091 #endif
1092 #ifdef CONFIG_L2TPV3
1093 "l2tpv3",
1094 #endif
1095 #ifdef CONFIG_VDE
1096 "vde",
1097 #endif
1098 #ifdef CONFIG_NET_BRIDGE
1099 "bridge",
1100 #endif
1101 #ifdef CONFIG_NETMAP
1102 "netmap",
1103 #endif
1104 #ifdef CONFIG_POSIX
1105 "vhost-user",
1106 #endif
1107 #ifdef CONFIG_VHOST_VDPA
1108 "vhost-vdpa",
1109 #endif
1112 qemu_printf("Available netdev backend types:\n");
1113 for (idx = 0; idx < ARRAY_SIZE(available_netdevs); idx++) {
1114 qemu_printf("%s\n", available_netdevs[idx]);
1118 static int net_client_init(QemuOpts *opts, bool is_netdev, Error **errp)
1120 gchar **substrings = NULL;
1121 Netdev *object = NULL;
1122 int ret = -1;
1123 Visitor *v = opts_visitor_new(opts);
1125 /* Parse convenience option format ip6-net=fec0::0[/64] */
1126 const char *ip6_net = qemu_opt_get(opts, "ipv6-net");
1128 if (ip6_net) {
1129 char *prefix_addr;
1130 unsigned long prefix_len = 64; /* Default 64bit prefix length. */
1132 substrings = g_strsplit(ip6_net, "/", 2);
1133 if (!substrings || !substrings[0]) {
1134 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "ipv6-net",
1135 "a valid IPv6 prefix");
1136 goto out;
1139 prefix_addr = substrings[0];
1141 /* Handle user-specified prefix length. */
1142 if (substrings[1] &&
1143 qemu_strtoul(substrings[1], NULL, 10, &prefix_len))
1145 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1146 "ipv6-prefixlen", "a number");
1147 goto out;
1150 qemu_opt_set(opts, "ipv6-prefix", prefix_addr, &error_abort);
1151 qemu_opt_set_number(opts, "ipv6-prefixlen", prefix_len,
1152 &error_abort);
1153 qemu_opt_unset(opts, "ipv6-net");
1156 /* Create an ID for -net if the user did not specify one */
1157 if (!is_netdev && !qemu_opts_id(opts)) {
1158 qemu_opts_set_id(opts, id_generate(ID_NET));
1161 if (visit_type_Netdev(v, NULL, &object, errp)) {
1162 ret = net_client_init1(object, is_netdev, errp);
1165 qapi_free_Netdev(object);
1167 out:
1168 g_strfreev(substrings);
1169 visit_free(v);
1170 return ret;
1173 void netdev_add(QemuOpts *opts, Error **errp)
1175 net_client_init(opts, true, errp);
1178 void qmp_netdev_add(Netdev *netdev, Error **errp)
1180 if (!id_wellformed(netdev->id)) {
1181 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "id", "an identifier");
1182 return;
1185 net_client_init1(netdev, true, errp);
1188 void qmp_netdev_del(const char *id, Error **errp)
1190 NetClientState *nc;
1191 QemuOpts *opts;
1193 nc = qemu_find_netdev(id);
1194 if (!nc) {
1195 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1196 "Device '%s' not found", id);
1197 return;
1200 if (!nc->is_netdev) {
1201 error_setg(errp, "Device '%s' is not a netdev", id);
1202 return;
1205 qemu_del_net_client(nc);
1208 * Wart: we need to delete the QemuOpts associated with netdevs
1209 * created via CLI or HMP, to avoid bogus "Duplicate ID" errors in
1210 * HMP netdev_add.
1212 opts = qemu_opts_find(qemu_find_opts("netdev"), id);
1213 if (opts) {
1214 qemu_opts_del(opts);
1218 static void netfilter_print_info(Monitor *mon, NetFilterState *nf)
1220 char *str;
1221 ObjectProperty *prop;
1222 ObjectPropertyIterator iter;
1223 Visitor *v;
1225 /* generate info str */
1226 object_property_iter_init(&iter, OBJECT(nf));
1227 while ((prop = object_property_iter_next(&iter))) {
1228 if (!strcmp(prop->name, "type")) {
1229 continue;
1231 v = string_output_visitor_new(false, &str);
1232 object_property_get(OBJECT(nf), prop->name, v, NULL);
1233 visit_complete(v, &str);
1234 visit_free(v);
1235 monitor_printf(mon, ",%s=%s", prop->name, str);
1236 g_free(str);
1238 monitor_printf(mon, "\n");
1241 void print_net_client(Monitor *mon, NetClientState *nc)
1243 NetFilterState *nf;
1245 monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
1246 nc->queue_index,
1247 NetClientDriver_str(nc->info->type),
1248 nc->info_str);
1249 if (!QTAILQ_EMPTY(&nc->filters)) {
1250 monitor_printf(mon, "filters:\n");
1252 QTAILQ_FOREACH(nf, &nc->filters, next) {
1253 monitor_printf(mon, " - %s: type=%s",
1254 object_get_canonical_path_component(OBJECT(nf)),
1255 object_get_typename(OBJECT(nf)));
1256 netfilter_print_info(mon, nf);
1260 RxFilterInfoList *qmp_query_rx_filter(bool has_name, const char *name,
1261 Error **errp)
1263 NetClientState *nc;
1264 RxFilterInfoList *filter_list = NULL, **tail = &filter_list;
1266 QTAILQ_FOREACH(nc, &net_clients, next) {
1267 RxFilterInfo *info;
1269 if (has_name && strcmp(nc->name, name) != 0) {
1270 continue;
1273 /* only query rx-filter information of NIC */
1274 if (nc->info->type != NET_CLIENT_DRIVER_NIC) {
1275 if (has_name) {
1276 error_setg(errp, "net client(%s) isn't a NIC", name);
1277 assert(!filter_list);
1278 return NULL;
1280 continue;
1283 /* only query information on queue 0 since the info is per nic,
1284 * not per queue
1286 if (nc->queue_index != 0)
1287 continue;
1289 if (nc->info->query_rx_filter) {
1290 info = nc->info->query_rx_filter(nc);
1291 QAPI_LIST_APPEND(tail, info);
1292 } else if (has_name) {
1293 error_setg(errp, "net client(%s) doesn't support"
1294 " rx-filter querying", name);
1295 assert(!filter_list);
1296 return NULL;
1299 if (has_name) {
1300 break;
1304 if (filter_list == NULL && has_name) {
1305 error_setg(errp, "invalid net client name: %s", name);
1308 return filter_list;
1311 void hmp_info_network(Monitor *mon, const QDict *qdict)
1313 NetClientState *nc, *peer;
1314 NetClientDriver type;
1316 net_hub_info(mon);
1318 QTAILQ_FOREACH(nc, &net_clients, next) {
1319 peer = nc->peer;
1320 type = nc->info->type;
1322 /* Skip if already printed in hub info */
1323 if (net_hub_id_for_client(nc, NULL) == 0) {
1324 continue;
1327 if (!peer || type == NET_CLIENT_DRIVER_NIC) {
1328 print_net_client(mon, nc);
1329 } /* else it's a netdev connected to a NIC, printed with the NIC */
1330 if (peer && type == NET_CLIENT_DRIVER_NIC) {
1331 monitor_printf(mon, " \\ ");
1332 print_net_client(mon, peer);
1337 void colo_notify_filters_event(int event, Error **errp)
1339 NetClientState *nc;
1340 NetFilterState *nf;
1341 NetFilterClass *nfc = NULL;
1342 Error *local_err = NULL;
1344 QTAILQ_FOREACH(nc, &net_clients, next) {
1345 QTAILQ_FOREACH(nf, &nc->filters, next) {
1346 nfc = NETFILTER_GET_CLASS(OBJECT(nf));
1347 nfc->handle_event(nf, event, &local_err);
1348 if (local_err) {
1349 error_propagate(errp, local_err);
1350 return;
1356 void qmp_set_link(const char *name, bool up, Error **errp)
1358 NetClientState *ncs[MAX_QUEUE_NUM];
1359 NetClientState *nc;
1360 int queues, i;
1362 queues = qemu_find_net_clients_except(name, ncs,
1363 NET_CLIENT_DRIVER__MAX,
1364 MAX_QUEUE_NUM);
1366 if (queues == 0) {
1367 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1368 "Device '%s' not found", name);
1369 return;
1371 nc = ncs[0];
1373 for (i = 0; i < queues; i++) {
1374 ncs[i]->link_down = !up;
1377 if (nc->info->link_status_changed) {
1378 nc->info->link_status_changed(nc);
1381 if (nc->peer) {
1382 /* Change peer link only if the peer is NIC and then notify peer.
1383 * If the peer is a HUBPORT or a backend, we do not change the
1384 * link status.
1386 * This behavior is compatible with qemu hubs where there could be
1387 * multiple clients that can still communicate with each other in
1388 * disconnected mode. For now maintain this compatibility.
1390 if (nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
1391 for (i = 0; i < queues; i++) {
1392 ncs[i]->peer->link_down = !up;
1395 if (nc->peer->info->link_status_changed) {
1396 nc->peer->info->link_status_changed(nc->peer);
1401 static void net_vm_change_state_handler(void *opaque, bool running,
1402 RunState state)
1404 NetClientState *nc;
1405 NetClientState *tmp;
1407 QTAILQ_FOREACH_SAFE(nc, &net_clients, next, tmp) {
1408 if (running) {
1409 /* Flush queued packets and wake up backends. */
1410 if (nc->peer && qemu_can_send_packet(nc)) {
1411 qemu_flush_queued_packets(nc->peer);
1413 } else {
1414 /* Complete all queued packets, to guarantee we don't modify
1415 * state later when VM is not running.
1417 qemu_flush_or_purge_queued_packets(nc, true);
1422 void net_cleanup(void)
1424 NetClientState *nc;
1426 /*cleanup colo compare module for COLO*/
1427 colo_compare_cleanup();
1429 /* We may del multiple entries during qemu_del_net_client(),
1430 * so QTAILQ_FOREACH_SAFE() is also not safe here.
1432 while (!QTAILQ_EMPTY(&net_clients)) {
1433 nc = QTAILQ_FIRST(&net_clients);
1434 if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
1435 qemu_del_nic(qemu_get_nic(nc));
1436 } else {
1437 qemu_del_net_client(nc);
1441 qemu_del_vm_change_state_handler(net_change_state_entry);
1444 void net_check_clients(void)
1446 NetClientState *nc;
1447 int i;
1449 net_hub_check_clients();
1451 QTAILQ_FOREACH(nc, &net_clients, next) {
1452 if (!nc->peer) {
1453 warn_report("%s %s has no peer",
1454 nc->info->type == NET_CLIENT_DRIVER_NIC
1455 ? "nic" : "netdev",
1456 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 warn_report("requested NIC (%s, model %s) "
1468 "was not created (not supported by this machine?)",
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 return net_client_init(opts, false, errp);
1480 static int net_init_netdev(void *dummy, QemuOpts *opts, Error **errp)
1482 const char *type = qemu_opt_get(opts, "type");
1484 if (type && is_help_option(type)) {
1485 show_netdevs();
1486 exit(0);
1488 return net_client_init(opts, true, errp);
1491 /* For the convenience "--nic" parameter */
1492 static int net_param_nic(void *dummy, QemuOpts *opts, Error **errp)
1494 char *mac, *nd_id;
1495 int idx, ret;
1496 NICInfo *ni;
1497 const char *type;
1499 type = qemu_opt_get(opts, "type");
1500 if (type && g_str_equal(type, "none")) {
1501 return 0; /* Nothing to do, default_net is cleared in vl.c */
1504 idx = nic_get_free_idx();
1505 if (idx == -1 || nb_nics >= MAX_NICS) {
1506 error_setg(errp, "no more on-board/default NIC slots available");
1507 return -1;
1510 if (!type) {
1511 qemu_opt_set(opts, "type", "user", &error_abort);
1514 ni = &nd_table[idx];
1515 memset(ni, 0, sizeof(*ni));
1516 ni->model = qemu_opt_get_del(opts, "model");
1518 /* Create an ID if the user did not specify one */
1519 nd_id = g_strdup(qemu_opts_id(opts));
1520 if (!nd_id) {
1521 nd_id = id_generate(ID_NET);
1522 qemu_opts_set_id(opts, nd_id);
1525 /* Handle MAC address */
1526 mac = qemu_opt_get_del(opts, "mac");
1527 if (mac) {
1528 ret = net_parse_macaddr(ni->macaddr.a, mac);
1529 g_free(mac);
1530 if (ret) {
1531 error_setg(errp, "invalid syntax for ethernet address");
1532 goto out;
1534 if (is_multicast_ether_addr(ni->macaddr.a)) {
1535 error_setg(errp, "NIC cannot have multicast MAC address");
1536 ret = -1;
1537 goto out;
1540 qemu_macaddr_default_if_unset(&ni->macaddr);
1542 ret = net_client_init(opts, true, errp);
1543 if (ret == 0) {
1544 ni->netdev = qemu_find_netdev(nd_id);
1545 ni->used = true;
1546 nb_nics++;
1549 out:
1550 g_free(nd_id);
1551 return ret;
1554 int net_init_clients(Error **errp)
1556 net_change_state_entry =
1557 qemu_add_vm_change_state_handler(net_vm_change_state_handler, NULL);
1559 QTAILQ_INIT(&net_clients);
1561 if (qemu_opts_foreach(qemu_find_opts("netdev"),
1562 net_init_netdev, NULL, errp)) {
1563 return -1;
1566 if (qemu_opts_foreach(qemu_find_opts("nic"), net_param_nic, NULL, errp)) {
1567 return -1;
1570 if (qemu_opts_foreach(qemu_find_opts("net"), net_init_client, NULL, errp)) {
1571 return -1;
1574 return 0;
1577 int net_client_parse(QemuOptsList *opts_list, const char *optarg)
1579 if (!qemu_opts_parse_noisily(opts_list, optarg, true)) {
1580 return -1;
1583 return 0;
1586 /* From FreeBSD */
1587 /* XXX: optimize */
1588 uint32_t net_crc32(const uint8_t *p, int len)
1590 uint32_t crc;
1591 int carry, i, j;
1592 uint8_t b;
1594 crc = 0xffffffff;
1595 for (i = 0; i < len; i++) {
1596 b = *p++;
1597 for (j = 0; j < 8; j++) {
1598 carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
1599 crc <<= 1;
1600 b >>= 1;
1601 if (carry) {
1602 crc = ((crc ^ POLYNOMIAL_BE) | carry);
1607 return crc;
1610 uint32_t net_crc32_le(const uint8_t *p, int len)
1612 uint32_t crc;
1613 int carry, i, j;
1614 uint8_t b;
1616 crc = 0xffffffff;
1617 for (i = 0; i < len; i++) {
1618 b = *p++;
1619 for (j = 0; j < 8; j++) {
1620 carry = (crc & 0x1) ^ (b & 0x01);
1621 crc >>= 1;
1622 b >>= 1;
1623 if (carry) {
1624 crc ^= POLYNOMIAL_LE;
1629 return crc;
1632 QemuOptsList qemu_netdev_opts = {
1633 .name = "netdev",
1634 .implied_opt_name = "type",
1635 .head = QTAILQ_HEAD_INITIALIZER(qemu_netdev_opts.head),
1636 .desc = {
1638 * no elements => accept any params
1639 * validation will happen later
1641 { /* end of list */ }
1645 QemuOptsList qemu_nic_opts = {
1646 .name = "nic",
1647 .implied_opt_name = "type",
1648 .head = QTAILQ_HEAD_INITIALIZER(qemu_nic_opts.head),
1649 .desc = {
1651 * no elements => accept any params
1652 * validation will happen later
1654 { /* end of list */ }
1658 QemuOptsList qemu_net_opts = {
1659 .name = "net",
1660 .implied_opt_name = "type",
1661 .head = QTAILQ_HEAD_INITIALIZER(qemu_net_opts.head),
1662 .desc = {
1664 * no elements => accept any params
1665 * validation will happen later
1667 { /* end of list */ }
1671 void net_socket_rs_init(SocketReadState *rs,
1672 SocketReadStateFinalize *finalize,
1673 bool vnet_hdr)
1675 rs->state = 0;
1676 rs->vnet_hdr = vnet_hdr;
1677 rs->index = 0;
1678 rs->packet_len = 0;
1679 rs->vnet_hdr_len = 0;
1680 memset(rs->buf, 0, sizeof(rs->buf));
1681 rs->finalize = finalize;
1685 * Returns
1686 * 0: success
1687 * -1: error occurs
1689 int net_fill_rstate(SocketReadState *rs, const uint8_t *buf, int size)
1691 unsigned int l;
1693 while (size > 0) {
1694 /* Reassemble a packet from the network.
1695 * 0 = getting length.
1696 * 1 = getting vnet header length.
1697 * 2 = getting data.
1699 switch (rs->state) {
1700 case 0:
1701 l = 4 - rs->index;
1702 if (l > size) {
1703 l = size;
1705 memcpy(rs->buf + rs->index, buf, l);
1706 buf += l;
1707 size -= l;
1708 rs->index += l;
1709 if (rs->index == 4) {
1710 /* got length */
1711 rs->packet_len = ntohl(*(uint32_t *)rs->buf);
1712 rs->index = 0;
1713 if (rs->vnet_hdr) {
1714 rs->state = 1;
1715 } else {
1716 rs->state = 2;
1717 rs->vnet_hdr_len = 0;
1720 break;
1721 case 1:
1722 l = 4 - rs->index;
1723 if (l > size) {
1724 l = size;
1726 memcpy(rs->buf + rs->index, buf, l);
1727 buf += l;
1728 size -= l;
1729 rs->index += l;
1730 if (rs->index == 4) {
1731 /* got vnet header length */
1732 rs->vnet_hdr_len = ntohl(*(uint32_t *)rs->buf);
1733 rs->index = 0;
1734 rs->state = 2;
1736 break;
1737 case 2:
1738 l = rs->packet_len - rs->index;
1739 if (l > size) {
1740 l = size;
1742 if (rs->index + l <= sizeof(rs->buf)) {
1743 memcpy(rs->buf + rs->index, buf, l);
1744 } else {
1745 fprintf(stderr, "serious error: oversized packet received,"
1746 "connection terminated.\n");
1747 rs->index = rs->state = 0;
1748 return -1;
1751 rs->index += l;
1752 buf += l;
1753 size -= l;
1754 if (rs->index >= rs->packet_len) {
1755 rs->index = 0;
1756 rs->state = 0;
1757 assert(rs->finalize);
1758 rs->finalize(rs);
1760 break;
1764 assert(size == 0);
1765 return 0;