sunhme: flush any queued packets when HME_MAC_RXCFG_ENABLE bit is raised
[qemu/ar7.git] / net / net.c
blob7d4098254fea4b9e8de90bd8b8285a513150c6ce
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"
27 #include "net/net.h"
28 #include "clients.h"
29 #include "hub.h"
30 #include "net/slirp.h"
31 #include "net/eth.h"
32 #include "util.h"
34 #include "monitor/monitor.h"
35 #include "qemu/help_option.h"
36 #include "qapi/qapi-commands-net.h"
37 #include "qapi/qapi-visit-net.h"
38 #include "qapi/qmp/qdict.h"
39 #include "qapi/qmp/qerror.h"
40 #include "qemu/error-report.h"
41 #include "qemu/sockets.h"
42 #include "qemu/cutils.h"
43 #include "qemu/config-file.h"
44 #include "qemu/ctype.h"
45 #include "hw/qdev.h"
46 #include "qemu/iov.h"
47 #include "qemu/main-loop.h"
48 #include "qemu/option.h"
49 #include "qapi/error.h"
50 #include "qapi/opts-visitor.h"
51 #include "sysemu/sysemu.h"
52 #include "sysemu/qtest.h"
53 #include "net/filter.h"
54 #include "qapi/string-output-visitor.h"
56 /* Net bridge is currently not supported for W32. */
57 #if !defined(_WIN32)
58 # define CONFIG_NET_BRIDGE
59 #endif
61 static VMChangeStateEntry *net_change_state_entry;
62 static QTAILQ_HEAD(, NetClientState) net_clients;
64 /***********************************************************/
65 /* network device redirectors */
67 int parse_host_port(struct sockaddr_in *saddr, const char *str,
68 Error **errp)
70 gchar **substrings;
71 struct hostent *he;
72 const char *addr, *p, *r;
73 int port, ret = 0;
75 substrings = g_strsplit(str, ":", 2);
76 if (!substrings || !substrings[0] || !substrings[1]) {
77 error_setg(errp, "host address '%s' doesn't contain ':' "
78 "separating host from port", str);
79 ret = -1;
80 goto out;
83 addr = substrings[0];
84 p = substrings[1];
86 saddr->sin_family = AF_INET;
87 if (addr[0] == '\0') {
88 saddr->sin_addr.s_addr = 0;
89 } else {
90 if (qemu_isdigit(addr[0])) {
91 if (!inet_aton(addr, &saddr->sin_addr)) {
92 error_setg(errp, "host address '%s' is not a valid "
93 "IPv4 address", addr);
94 ret = -1;
95 goto out;
97 } else {
98 he = gethostbyname(addr);
99 if (he == NULL) {
100 error_setg(errp, "can't resolve host address '%s'", addr);
101 ret = -1;
102 goto out;
104 saddr->sin_addr = *(struct in_addr *)he->h_addr;
107 port = strtol(p, (char **)&r, 0);
108 if (r == p) {
109 error_setg(errp, "port number '%s' is invalid", p);
110 ret = -1;
111 goto out;
113 saddr->sin_port = htons(port);
115 out:
116 g_strfreev(substrings);
117 return ret;
120 char *qemu_mac_strdup_printf(const uint8_t *macaddr)
122 return g_strdup_printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
123 macaddr[0], macaddr[1], macaddr[2],
124 macaddr[3], macaddr[4], macaddr[5]);
127 void qemu_format_nic_info_str(NetClientState *nc, uint8_t macaddr[6])
129 snprintf(nc->info_str, sizeof(nc->info_str),
130 "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
131 nc->model,
132 macaddr[0], macaddr[1], macaddr[2],
133 macaddr[3], macaddr[4], macaddr[5]);
136 static int mac_table[256] = {0};
138 static void qemu_macaddr_set_used(MACAddr *macaddr)
140 int index;
142 for (index = 0x56; index < 0xFF; index++) {
143 if (macaddr->a[5] == index) {
144 mac_table[index]++;
149 static void qemu_macaddr_set_free(MACAddr *macaddr)
151 int index;
152 static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
154 if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
155 return;
157 for (index = 0x56; index < 0xFF; index++) {
158 if (macaddr->a[5] == index) {
159 mac_table[index]--;
164 static int qemu_macaddr_get_free(void)
166 int index;
168 for (index = 0x56; index < 0xFF; index++) {
169 if (mac_table[index] == 0) {
170 return index;
174 return -1;
177 void qemu_macaddr_default_if_unset(MACAddr *macaddr)
179 static const MACAddr zero = { .a = { 0,0,0,0,0,0 } };
180 static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
182 if (memcmp(macaddr, &zero, sizeof(zero)) != 0) {
183 if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
184 return;
185 } else {
186 qemu_macaddr_set_used(macaddr);
187 return;
191 macaddr->a[0] = 0x52;
192 macaddr->a[1] = 0x54;
193 macaddr->a[2] = 0x00;
194 macaddr->a[3] = 0x12;
195 macaddr->a[4] = 0x34;
196 macaddr->a[5] = qemu_macaddr_get_free();
197 qemu_macaddr_set_used(macaddr);
201 * Generate a name for net client
203 * Only net clients created with the legacy -net option and NICs need this.
205 static char *assign_name(NetClientState *nc1, const char *model)
207 NetClientState *nc;
208 int id = 0;
210 QTAILQ_FOREACH(nc, &net_clients, next) {
211 if (nc == nc1) {
212 continue;
214 if (strcmp(nc->model, model) == 0) {
215 id++;
219 return g_strdup_printf("%s.%d", model, id);
222 static void qemu_net_client_destructor(NetClientState *nc)
224 g_free(nc);
226 static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
227 unsigned flags,
228 const struct iovec *iov,
229 int iovcnt,
230 void *opaque);
232 static void qemu_net_client_setup(NetClientState *nc,
233 NetClientInfo *info,
234 NetClientState *peer,
235 const char *model,
236 const char *name,
237 NetClientDestructor *destructor)
239 nc->info = info;
240 nc->model = g_strdup(model);
241 if (name) {
242 nc->name = g_strdup(name);
243 } else {
244 nc->name = assign_name(nc, model);
247 if (peer) {
248 assert(!peer->peer);
249 nc->peer = peer;
250 peer->peer = nc;
252 QTAILQ_INSERT_TAIL(&net_clients, nc, next);
254 nc->incoming_queue = qemu_new_net_queue(qemu_deliver_packet_iov, nc);
255 nc->destructor = destructor;
256 QTAILQ_INIT(&nc->filters);
259 NetClientState *qemu_new_net_client(NetClientInfo *info,
260 NetClientState *peer,
261 const char *model,
262 const char *name)
264 NetClientState *nc;
266 assert(info->size >= sizeof(NetClientState));
268 nc = g_malloc0(info->size);
269 qemu_net_client_setup(nc, info, peer, model, name,
270 qemu_net_client_destructor);
272 return nc;
275 NICState *qemu_new_nic(NetClientInfo *info,
276 NICConf *conf,
277 const char *model,
278 const char *name,
279 void *opaque)
281 NetClientState **peers = conf->peers.ncs;
282 NICState *nic;
283 int i, queues = MAX(1, conf->peers.queues);
285 assert(info->type == NET_CLIENT_DRIVER_NIC);
286 assert(info->size >= sizeof(NICState));
288 nic = g_malloc0(info->size + sizeof(NetClientState) * queues);
289 nic->ncs = (void *)nic + info->size;
290 nic->conf = conf;
291 nic->opaque = opaque;
293 for (i = 0; i < queues; i++) {
294 qemu_net_client_setup(&nic->ncs[i], info, peers[i], model, name,
295 NULL);
296 nic->ncs[i].queue_index = i;
299 return nic;
302 NetClientState *qemu_get_subqueue(NICState *nic, int queue_index)
304 return nic->ncs + queue_index;
307 NetClientState *qemu_get_queue(NICState *nic)
309 return qemu_get_subqueue(nic, 0);
312 NICState *qemu_get_nic(NetClientState *nc)
314 NetClientState *nc0 = nc - nc->queue_index;
316 return (NICState *)((void *)nc0 - nc->info->size);
319 void *qemu_get_nic_opaque(NetClientState *nc)
321 NICState *nic = qemu_get_nic(nc);
323 return nic->opaque;
326 static void qemu_cleanup_net_client(NetClientState *nc)
328 QTAILQ_REMOVE(&net_clients, nc, next);
330 if (nc->info->cleanup) {
331 nc->info->cleanup(nc);
335 static void qemu_free_net_client(NetClientState *nc)
337 if (nc->incoming_queue) {
338 qemu_del_net_queue(nc->incoming_queue);
340 if (nc->peer) {
341 nc->peer->peer = NULL;
343 g_free(nc->name);
344 g_free(nc->model);
345 if (nc->destructor) {
346 nc->destructor(nc);
350 void qemu_del_net_client(NetClientState *nc)
352 NetClientState *ncs[MAX_QUEUE_NUM];
353 int queues, i;
354 NetFilterState *nf, *next;
356 assert(nc->info->type != NET_CLIENT_DRIVER_NIC);
358 /* If the NetClientState belongs to a multiqueue backend, we will change all
359 * other NetClientStates also.
361 queues = qemu_find_net_clients_except(nc->name, ncs,
362 NET_CLIENT_DRIVER_NIC,
363 MAX_QUEUE_NUM);
364 assert(queues != 0);
366 QTAILQ_FOREACH_SAFE(nf, &nc->filters, next, next) {
367 object_unparent(OBJECT(nf));
370 /* If there is a peer NIC, delete and cleanup client, but do not free. */
371 if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
372 NICState *nic = qemu_get_nic(nc->peer);
373 if (nic->peer_deleted) {
374 return;
376 nic->peer_deleted = true;
378 for (i = 0; i < queues; i++) {
379 ncs[i]->peer->link_down = true;
382 if (nc->peer->info->link_status_changed) {
383 nc->peer->info->link_status_changed(nc->peer);
386 for (i = 0; i < queues; i++) {
387 qemu_cleanup_net_client(ncs[i]);
390 return;
393 for (i = 0; i < queues; i++) {
394 qemu_cleanup_net_client(ncs[i]);
395 qemu_free_net_client(ncs[i]);
399 void qemu_del_nic(NICState *nic)
401 int i, queues = MAX(nic->conf->peers.queues, 1);
403 qemu_macaddr_set_free(&nic->conf->macaddr);
405 /* If this is a peer NIC and peer has already been deleted, free it now. */
406 if (nic->peer_deleted) {
407 for (i = 0; i < queues; i++) {
408 qemu_free_net_client(qemu_get_subqueue(nic, i)->peer);
412 for (i = queues - 1; i >= 0; i--) {
413 NetClientState *nc = qemu_get_subqueue(nic, i);
415 qemu_cleanup_net_client(nc);
416 qemu_free_net_client(nc);
419 g_free(nic);
422 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
424 NetClientState *nc;
426 QTAILQ_FOREACH(nc, &net_clients, next) {
427 if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
428 if (nc->queue_index == 0) {
429 func(qemu_get_nic(nc), opaque);
435 bool qemu_has_ufo(NetClientState *nc)
437 if (!nc || !nc->info->has_ufo) {
438 return false;
441 return nc->info->has_ufo(nc);
444 bool qemu_has_vnet_hdr(NetClientState *nc)
446 if (!nc || !nc->info->has_vnet_hdr) {
447 return false;
450 return nc->info->has_vnet_hdr(nc);
453 bool qemu_has_vnet_hdr_len(NetClientState *nc, int len)
455 if (!nc || !nc->info->has_vnet_hdr_len) {
456 return false;
459 return nc->info->has_vnet_hdr_len(nc, len);
462 void qemu_using_vnet_hdr(NetClientState *nc, bool enable)
464 if (!nc || !nc->info->using_vnet_hdr) {
465 return;
468 nc->info->using_vnet_hdr(nc, enable);
471 void qemu_set_offload(NetClientState *nc, int csum, int tso4, int tso6,
472 int ecn, int ufo)
474 if (!nc || !nc->info->set_offload) {
475 return;
478 nc->info->set_offload(nc, csum, tso4, tso6, ecn, ufo);
481 void qemu_set_vnet_hdr_len(NetClientState *nc, int len)
483 if (!nc || !nc->info->set_vnet_hdr_len) {
484 return;
487 nc->vnet_hdr_len = len;
488 nc->info->set_vnet_hdr_len(nc, len);
491 int qemu_set_vnet_le(NetClientState *nc, bool is_le)
493 #ifdef HOST_WORDS_BIGENDIAN
494 if (!nc || !nc->info->set_vnet_le) {
495 return -ENOSYS;
498 return nc->info->set_vnet_le(nc, is_le);
499 #else
500 return 0;
501 #endif
504 int qemu_set_vnet_be(NetClientState *nc, bool is_be)
506 #ifdef HOST_WORDS_BIGENDIAN
507 return 0;
508 #else
509 if (!nc || !nc->info->set_vnet_be) {
510 return -ENOSYS;
513 return nc->info->set_vnet_be(nc, is_be);
514 #endif
517 int qemu_can_send_packet(NetClientState *sender)
519 int vm_running = runstate_is_running();
521 if (!vm_running) {
522 return 0;
525 if (!sender->peer) {
526 return 1;
529 if (sender->peer->receive_disabled) {
530 return 0;
531 } else if (sender->peer->info->can_receive &&
532 !sender->peer->info->can_receive(sender->peer)) {
533 return 0;
535 return 1;
538 static ssize_t filter_receive_iov(NetClientState *nc,
539 NetFilterDirection direction,
540 NetClientState *sender,
541 unsigned flags,
542 const struct iovec *iov,
543 int iovcnt,
544 NetPacketSent *sent_cb)
546 ssize_t ret = 0;
547 NetFilterState *nf = NULL;
549 if (direction == NET_FILTER_DIRECTION_TX) {
550 QTAILQ_FOREACH(nf, &nc->filters, next) {
551 ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
552 iovcnt, sent_cb);
553 if (ret) {
554 return ret;
557 } else {
558 QTAILQ_FOREACH_REVERSE(nf, &nc->filters, next) {
559 ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
560 iovcnt, sent_cb);
561 if (ret) {
562 return ret;
567 return ret;
570 static ssize_t filter_receive(NetClientState *nc,
571 NetFilterDirection direction,
572 NetClientState *sender,
573 unsigned flags,
574 const uint8_t *data,
575 size_t size,
576 NetPacketSent *sent_cb)
578 struct iovec iov = {
579 .iov_base = (void *)data,
580 .iov_len = size
583 return filter_receive_iov(nc, direction, sender, flags, &iov, 1, sent_cb);
586 void qemu_purge_queued_packets(NetClientState *nc)
588 if (!nc->peer) {
589 return;
592 qemu_net_queue_purge(nc->peer->incoming_queue, nc);
595 void qemu_flush_or_purge_queued_packets(NetClientState *nc, bool purge)
597 nc->receive_disabled = 0;
599 if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_HUBPORT) {
600 if (net_hub_flush(nc->peer)) {
601 qemu_notify_event();
604 if (qemu_net_queue_flush(nc->incoming_queue)) {
605 /* We emptied the queue successfully, signal to the IO thread to repoll
606 * the file descriptor (for tap, for example).
608 qemu_notify_event();
609 } else if (purge) {
610 /* Unable to empty the queue, purge remaining packets */
611 qemu_net_queue_purge(nc->incoming_queue, nc);
615 void qemu_flush_queued_packets(NetClientState *nc)
617 qemu_flush_or_purge_queued_packets(nc, false);
620 static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
621 unsigned flags,
622 const uint8_t *buf, int size,
623 NetPacketSent *sent_cb)
625 NetQueue *queue;
626 int ret;
628 #ifdef DEBUG_NET
629 printf("qemu_send_packet_async:\n");
630 qemu_hexdump((const char *)buf, stdout, "net", size);
631 #endif
633 if (sender->link_down || !sender->peer) {
634 return size;
637 /* Let filters handle the packet first */
638 ret = filter_receive(sender, NET_FILTER_DIRECTION_TX,
639 sender, flags, buf, size, sent_cb);
640 if (ret) {
641 return ret;
644 ret = filter_receive(sender->peer, NET_FILTER_DIRECTION_RX,
645 sender, flags, buf, size, sent_cb);
646 if (ret) {
647 return ret;
650 queue = sender->peer->incoming_queue;
652 return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
655 ssize_t qemu_send_packet_async(NetClientState *sender,
656 const uint8_t *buf, int size,
657 NetPacketSent *sent_cb)
659 return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
660 buf, size, sent_cb);
663 ssize_t qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size)
665 return qemu_send_packet_async(nc, buf, size, NULL);
668 ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size)
670 return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW,
671 buf, size, NULL);
674 static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
675 int iovcnt, unsigned flags)
677 uint8_t *buf = NULL;
678 uint8_t *buffer;
679 size_t offset;
680 ssize_t ret;
682 if (iovcnt == 1) {
683 buffer = iov[0].iov_base;
684 offset = iov[0].iov_len;
685 } else {
686 offset = iov_size(iov, iovcnt);
687 if (offset > NET_BUFSIZE) {
688 return -1;
690 buf = g_malloc(offset);
691 buffer = buf;
692 offset = iov_to_buf(iov, iovcnt, 0, buf, offset);
695 if (flags & QEMU_NET_PACKET_FLAG_RAW && nc->info->receive_raw) {
696 ret = nc->info->receive_raw(nc, buffer, offset);
697 } else {
698 ret = nc->info->receive(nc, buffer, offset);
701 g_free(buf);
702 return ret;
705 static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
706 unsigned flags,
707 const struct iovec *iov,
708 int iovcnt,
709 void *opaque)
711 NetClientState *nc = opaque;
712 int ret;
715 if (nc->link_down) {
716 return iov_size(iov, iovcnt);
719 if (nc->receive_disabled) {
720 return 0;
723 if (nc->info->receive_iov && !(flags & QEMU_NET_PACKET_FLAG_RAW)) {
724 ret = nc->info->receive_iov(nc, iov, iovcnt);
725 } else {
726 ret = nc_sendv_compat(nc, iov, iovcnt, flags);
729 if (ret == 0) {
730 nc->receive_disabled = 1;
733 return ret;
736 ssize_t qemu_sendv_packet_async(NetClientState *sender,
737 const struct iovec *iov, int iovcnt,
738 NetPacketSent *sent_cb)
740 NetQueue *queue;
741 size_t size = iov_size(iov, iovcnt);
742 int ret;
744 if (size > NET_BUFSIZE) {
745 return size;
748 if (sender->link_down || !sender->peer) {
749 return size;
752 /* Let filters handle the packet first */
753 ret = filter_receive_iov(sender, NET_FILTER_DIRECTION_TX, sender,
754 QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
755 if (ret) {
756 return ret;
759 ret = filter_receive_iov(sender->peer, NET_FILTER_DIRECTION_RX, sender,
760 QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
761 if (ret) {
762 return ret;
765 queue = sender->peer->incoming_queue;
767 return qemu_net_queue_send_iov(queue, sender,
768 QEMU_NET_PACKET_FLAG_NONE,
769 iov, iovcnt, sent_cb);
772 ssize_t
773 qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt)
775 return qemu_sendv_packet_async(nc, iov, iovcnt, NULL);
778 NetClientState *qemu_find_netdev(const char *id)
780 NetClientState *nc;
782 QTAILQ_FOREACH(nc, &net_clients, next) {
783 if (nc->info->type == NET_CLIENT_DRIVER_NIC)
784 continue;
785 if (!strcmp(nc->name, id)) {
786 return nc;
790 return NULL;
793 int qemu_find_net_clients_except(const char *id, NetClientState **ncs,
794 NetClientDriver type, int max)
796 NetClientState *nc;
797 int ret = 0;
799 QTAILQ_FOREACH(nc, &net_clients, next) {
800 if (nc->info->type == type) {
801 continue;
803 if (!id || !strcmp(nc->name, id)) {
804 if (ret < max) {
805 ncs[ret] = nc;
807 ret++;
811 return ret;
814 static int nic_get_free_idx(void)
816 int index;
818 for (index = 0; index < MAX_NICS; index++)
819 if (!nd_table[index].used)
820 return index;
821 return -1;
824 int qemu_show_nic_models(const char *arg, const char *const *models)
826 int i;
828 if (!arg || !is_help_option(arg)) {
829 return 0;
832 printf("Supported NIC models:\n");
833 for (i = 0 ; models[i]; i++) {
834 printf("%s\n", models[i]);
836 return 1;
839 void qemu_check_nic_model(NICInfo *nd, const char *model)
841 const char *models[2];
843 models[0] = model;
844 models[1] = NULL;
846 if (qemu_show_nic_models(nd->model, models))
847 exit(0);
848 if (qemu_find_nic_model(nd, models, model) < 0)
849 exit(1);
852 int qemu_find_nic_model(NICInfo *nd, const char * const *models,
853 const char *default_model)
855 int i;
857 if (!nd->model)
858 nd->model = g_strdup(default_model);
860 for (i = 0 ; models[i]; i++) {
861 if (strcmp(nd->model, models[i]) == 0)
862 return i;
865 error_report("Unsupported NIC model: %s", nd->model);
866 return -1;
869 static int net_init_nic(const Netdev *netdev, const char *name,
870 NetClientState *peer, Error **errp)
872 int idx;
873 NICInfo *nd;
874 const NetLegacyNicOptions *nic;
876 assert(netdev->type == NET_CLIENT_DRIVER_NIC);
877 nic = &netdev->u.nic;
879 idx = nic_get_free_idx();
880 if (idx == -1 || nb_nics >= MAX_NICS) {
881 error_setg(errp, "too many NICs");
882 return -1;
885 nd = &nd_table[idx];
887 memset(nd, 0, sizeof(*nd));
889 if (nic->has_netdev) {
890 nd->netdev = qemu_find_netdev(nic->netdev);
891 if (!nd->netdev) {
892 error_setg(errp, "netdev '%s' not found", nic->netdev);
893 return -1;
895 } else {
896 assert(peer);
897 nd->netdev = peer;
899 nd->name = g_strdup(name);
900 if (nic->has_model) {
901 nd->model = g_strdup(nic->model);
903 if (nic->has_addr) {
904 nd->devaddr = g_strdup(nic->addr);
907 if (nic->has_macaddr &&
908 net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {
909 error_setg(errp, "invalid syntax for ethernet address");
910 return -1;
912 if (nic->has_macaddr &&
913 is_multicast_ether_addr(nd->macaddr.a)) {
914 error_setg(errp,
915 "NIC cannot have multicast MAC address (odd 1st byte)");
916 return -1;
918 qemu_macaddr_default_if_unset(&nd->macaddr);
920 if (nic->has_vectors) {
921 if (nic->vectors > 0x7ffffff) {
922 error_setg(errp, "invalid # of vectors: %"PRIu32, nic->vectors);
923 return -1;
925 nd->nvectors = nic->vectors;
926 } else {
927 nd->nvectors = DEV_NVECTORS_UNSPECIFIED;
930 nd->used = 1;
931 nb_nics++;
933 return idx;
937 static int (* const net_client_init_fun[NET_CLIENT_DRIVER__MAX])(
938 const Netdev *netdev,
939 const char *name,
940 NetClientState *peer, Error **errp) = {
941 [NET_CLIENT_DRIVER_NIC] = net_init_nic,
942 #ifdef CONFIG_SLIRP
943 [NET_CLIENT_DRIVER_USER] = net_init_slirp,
944 #endif
945 [NET_CLIENT_DRIVER_TAP] = net_init_tap,
946 [NET_CLIENT_DRIVER_SOCKET] = net_init_socket,
947 #ifdef CONFIG_VDE
948 [NET_CLIENT_DRIVER_VDE] = net_init_vde,
949 #endif
950 #ifdef CONFIG_NETMAP
951 [NET_CLIENT_DRIVER_NETMAP] = net_init_netmap,
952 #endif
953 #ifdef CONFIG_NET_BRIDGE
954 [NET_CLIENT_DRIVER_BRIDGE] = net_init_bridge,
955 #endif
956 [NET_CLIENT_DRIVER_HUBPORT] = net_init_hubport,
957 #ifdef CONFIG_VHOST_NET_USER
958 [NET_CLIENT_DRIVER_VHOST_USER] = net_init_vhost_user,
959 #endif
960 #ifdef CONFIG_L2TPV3
961 [NET_CLIENT_DRIVER_L2TPV3] = net_init_l2tpv3,
962 #endif
966 static int net_client_init1(const void *object, bool is_netdev, Error **errp)
968 Netdev legacy = {0};
969 const Netdev *netdev;
970 const char *name;
971 NetClientState *peer = NULL;
973 if (is_netdev) {
974 netdev = object;
975 name = netdev->id;
977 if (netdev->type == NET_CLIENT_DRIVER_NIC ||
978 !net_client_init_fun[netdev->type]) {
979 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
980 "a netdev backend type");
981 return -1;
983 } else {
984 const NetLegacy *net = object;
985 const NetLegacyOptions *opts = net->opts;
986 legacy.id = net->id;
987 netdev = &legacy;
988 /* missing optional values have been initialized to "all bits zero" */
989 name = net->has_id ? net->id : net->name;
991 if (net->has_name) {
992 warn_report("The 'name' parameter is deprecated, use 'id' instead");
995 /* Map the old options to the new flat type */
996 switch (opts->type) {
997 case NET_LEGACY_OPTIONS_TYPE_NONE:
998 return 0; /* nothing to do */
999 case NET_LEGACY_OPTIONS_TYPE_NIC:
1000 legacy.type = NET_CLIENT_DRIVER_NIC;
1001 legacy.u.nic = opts->u.nic;
1002 break;
1003 case NET_LEGACY_OPTIONS_TYPE_USER:
1004 legacy.type = NET_CLIENT_DRIVER_USER;
1005 legacy.u.user = opts->u.user;
1006 break;
1007 case NET_LEGACY_OPTIONS_TYPE_TAP:
1008 legacy.type = NET_CLIENT_DRIVER_TAP;
1009 legacy.u.tap = opts->u.tap;
1010 break;
1011 case NET_LEGACY_OPTIONS_TYPE_L2TPV3:
1012 legacy.type = NET_CLIENT_DRIVER_L2TPV3;
1013 legacy.u.l2tpv3 = opts->u.l2tpv3;
1014 break;
1015 case NET_LEGACY_OPTIONS_TYPE_SOCKET:
1016 legacy.type = NET_CLIENT_DRIVER_SOCKET;
1017 legacy.u.socket = opts->u.socket;
1018 break;
1019 case NET_LEGACY_OPTIONS_TYPE_VDE:
1020 legacy.type = NET_CLIENT_DRIVER_VDE;
1021 legacy.u.vde = opts->u.vde;
1022 break;
1023 case NET_LEGACY_OPTIONS_TYPE_BRIDGE:
1024 legacy.type = NET_CLIENT_DRIVER_BRIDGE;
1025 legacy.u.bridge = opts->u.bridge;
1026 break;
1027 case NET_LEGACY_OPTIONS_TYPE_NETMAP:
1028 legacy.type = NET_CLIENT_DRIVER_NETMAP;
1029 legacy.u.netmap = opts->u.netmap;
1030 break;
1031 case NET_LEGACY_OPTIONS_TYPE_VHOST_USER:
1032 legacy.type = NET_CLIENT_DRIVER_VHOST_USER;
1033 legacy.u.vhost_user = opts->u.vhost_user;
1034 break;
1035 default:
1036 abort();
1039 if (!net_client_init_fun[netdev->type]) {
1040 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
1041 "a net backend type (maybe it is not compiled "
1042 "into this binary)");
1043 return -1;
1046 /* Do not add to a hub if it's a nic with a netdev= parameter. */
1047 if (netdev->type != NET_CLIENT_DRIVER_NIC ||
1048 !opts->u.nic.has_netdev) {
1049 peer = net_hub_add_port(0, NULL, NULL);
1053 if (net_client_init_fun[netdev->type](netdev, name, peer, errp) < 0) {
1054 /* FIXME drop when all init functions store an Error */
1055 if (errp && !*errp) {
1056 error_setg(errp, QERR_DEVICE_INIT_FAILED,
1057 NetClientDriver_str(netdev->type));
1059 return -1;
1061 return 0;
1064 static void show_netdevs(void)
1066 int idx;
1067 const char *available_netdevs[] = {
1068 "socket",
1069 "hubport",
1070 "tap",
1071 #ifdef CONFIG_SLIRP
1072 "user",
1073 #endif
1074 #ifdef CONFIG_L2TPV3
1075 "l2tpv3",
1076 #endif
1077 #ifdef CONFIG_VDE
1078 "vde",
1079 #endif
1080 #ifdef CONFIG_NET_BRIDGE
1081 "bridge",
1082 #endif
1083 #ifdef CONFIG_NETMAP
1084 "netmap",
1085 #endif
1086 #ifdef CONFIG_POSIX
1087 "vhost-user",
1088 #endif
1091 printf("Available netdev backend types:\n");
1092 for (idx = 0; idx < ARRAY_SIZE(available_netdevs); idx++) {
1093 puts(available_netdevs[idx]);
1097 static int net_client_init(QemuOpts *opts, bool is_netdev, Error **errp)
1099 gchar **substrings = NULL;
1100 void *object = NULL;
1101 Error *err = NULL;
1102 int ret = -1;
1103 Visitor *v = opts_visitor_new(opts);
1105 const char *type = qemu_opt_get(opts, "type");
1107 if (is_netdev && type && is_help_option(type)) {
1108 show_netdevs();
1109 exit(0);
1110 } else {
1111 /* Parse convenience option format ip6-net=fec0::0[/64] */
1112 const char *ip6_net = qemu_opt_get(opts, "ipv6-net");
1114 if (ip6_net) {
1115 char *prefix_addr;
1116 unsigned long prefix_len = 64; /* Default 64bit prefix length. */
1118 substrings = g_strsplit(ip6_net, "/", 2);
1119 if (!substrings || !substrings[0]) {
1120 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "ipv6-net",
1121 "a valid IPv6 prefix");
1122 goto out;
1125 prefix_addr = substrings[0];
1127 if (substrings[1]) {
1128 /* User-specified prefix length. */
1129 int err;
1131 err = qemu_strtoul(substrings[1], NULL, 10, &prefix_len);
1132 if (err) {
1133 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1134 "ipv6-prefixlen", "a number");
1135 goto out;
1139 qemu_opt_set(opts, "ipv6-prefix", prefix_addr, &error_abort);
1140 qemu_opt_set_number(opts, "ipv6-prefixlen", prefix_len,
1141 &error_abort);
1142 qemu_opt_unset(opts, "ipv6-net");
1146 if (is_netdev) {
1147 visit_type_Netdev(v, NULL, (Netdev **)&object, &err);
1148 } else {
1149 visit_type_NetLegacy(v, NULL, (NetLegacy **)&object, &err);
1152 if (!err) {
1153 ret = net_client_init1(object, is_netdev, &err);
1156 if (is_netdev) {
1157 qapi_free_Netdev(object);
1158 } else {
1159 qapi_free_NetLegacy(object);
1162 out:
1163 error_propagate(errp, err);
1164 g_strfreev(substrings);
1165 visit_free(v);
1166 return ret;
1169 void netdev_add(QemuOpts *opts, Error **errp)
1171 net_client_init(opts, true, errp);
1174 void qmp_netdev_add(QDict *qdict, QObject **ret, Error **errp)
1176 Error *local_err = NULL;
1177 QemuOptsList *opts_list;
1178 QemuOpts *opts;
1180 opts_list = qemu_find_opts_err("netdev", &local_err);
1181 if (local_err) {
1182 goto out;
1185 opts = qemu_opts_from_qdict(opts_list, qdict, &local_err);
1186 if (local_err) {
1187 goto out;
1190 netdev_add(opts, &local_err);
1191 if (local_err) {
1192 qemu_opts_del(opts);
1193 goto out;
1196 out:
1197 error_propagate(errp, local_err);
1200 void qmp_netdev_del(const char *id, Error **errp)
1202 NetClientState *nc;
1203 QemuOpts *opts;
1205 nc = qemu_find_netdev(id);
1206 if (!nc) {
1207 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1208 "Device '%s' not found", id);
1209 return;
1212 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), id);
1213 if (!opts) {
1214 error_setg(errp, "Device '%s' is not a netdev", id);
1215 return;
1218 qemu_del_net_client(nc);
1219 qemu_opts_del(opts);
1222 static void netfilter_print_info(Monitor *mon, NetFilterState *nf)
1224 char *str;
1225 ObjectProperty *prop;
1226 ObjectPropertyIterator iter;
1227 Visitor *v;
1229 /* generate info str */
1230 object_property_iter_init(&iter, OBJECT(nf));
1231 while ((prop = object_property_iter_next(&iter))) {
1232 if (!strcmp(prop->name, "type")) {
1233 continue;
1235 v = string_output_visitor_new(false, &str);
1236 object_property_get(OBJECT(nf), v, prop->name, NULL);
1237 visit_complete(v, &str);
1238 visit_free(v);
1239 monitor_printf(mon, ",%s=%s", prop->name, str);
1240 g_free(str);
1242 monitor_printf(mon, "\n");
1245 void print_net_client(Monitor *mon, NetClientState *nc)
1247 NetFilterState *nf;
1249 monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
1250 nc->queue_index,
1251 NetClientDriver_str(nc->info->type),
1252 nc->info_str);
1253 if (!QTAILQ_EMPTY(&nc->filters)) {
1254 monitor_printf(mon, "filters:\n");
1256 QTAILQ_FOREACH(nf, &nc->filters, next) {
1257 char *path = object_get_canonical_path_component(OBJECT(nf));
1259 monitor_printf(mon, " - %s: type=%s", path,
1260 object_get_typename(OBJECT(nf)));
1261 netfilter_print_info(mon, nf);
1262 g_free(path);
1266 RxFilterInfoList *qmp_query_rx_filter(bool has_name, const char *name,
1267 Error **errp)
1269 NetClientState *nc;
1270 RxFilterInfoList *filter_list = NULL, *last_entry = NULL;
1272 QTAILQ_FOREACH(nc, &net_clients, next) {
1273 RxFilterInfoList *entry;
1274 RxFilterInfo *info;
1276 if (has_name && strcmp(nc->name, name) != 0) {
1277 continue;
1280 /* only query rx-filter information of NIC */
1281 if (nc->info->type != NET_CLIENT_DRIVER_NIC) {
1282 if (has_name) {
1283 error_setg(errp, "net client(%s) isn't a NIC", name);
1284 return NULL;
1286 continue;
1289 /* only query information on queue 0 since the info is per nic,
1290 * not per queue
1292 if (nc->queue_index != 0)
1293 continue;
1295 if (nc->info->query_rx_filter) {
1296 info = nc->info->query_rx_filter(nc);
1297 entry = g_malloc0(sizeof(*entry));
1298 entry->value = info;
1300 if (!filter_list) {
1301 filter_list = entry;
1302 } else {
1303 last_entry->next = entry;
1305 last_entry = entry;
1306 } else if (has_name) {
1307 error_setg(errp, "net client(%s) doesn't support"
1308 " rx-filter querying", name);
1309 return NULL;
1312 if (has_name) {
1313 break;
1317 if (filter_list == NULL && has_name) {
1318 error_setg(errp, "invalid net client name: %s", name);
1321 return filter_list;
1324 void hmp_info_network(Monitor *mon, const QDict *qdict)
1326 NetClientState *nc, *peer;
1327 NetClientDriver type;
1329 net_hub_info(mon);
1331 QTAILQ_FOREACH(nc, &net_clients, next) {
1332 peer = nc->peer;
1333 type = nc->info->type;
1335 /* Skip if already printed in hub info */
1336 if (net_hub_id_for_client(nc, NULL) == 0) {
1337 continue;
1340 if (!peer || type == NET_CLIENT_DRIVER_NIC) {
1341 print_net_client(mon, nc);
1342 } /* else it's a netdev connected to a NIC, printed with the NIC */
1343 if (peer && type == NET_CLIENT_DRIVER_NIC) {
1344 monitor_printf(mon, " \\ ");
1345 print_net_client(mon, peer);
1350 void colo_notify_filters_event(int event, Error **errp)
1352 NetClientState *nc;
1353 NetFilterState *nf;
1354 NetFilterClass *nfc = NULL;
1355 Error *local_err = NULL;
1357 QTAILQ_FOREACH(nc, &net_clients, next) {
1358 QTAILQ_FOREACH(nf, &nc->filters, next) {
1359 nfc = NETFILTER_GET_CLASS(OBJECT(nf));
1360 nfc->handle_event(nf, event, &local_err);
1361 if (local_err) {
1362 error_propagate(errp, local_err);
1363 return;
1369 void qmp_set_link(const char *name, bool up, Error **errp)
1371 NetClientState *ncs[MAX_QUEUE_NUM];
1372 NetClientState *nc;
1373 int queues, i;
1375 queues = qemu_find_net_clients_except(name, ncs,
1376 NET_CLIENT_DRIVER__MAX,
1377 MAX_QUEUE_NUM);
1379 if (queues == 0) {
1380 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1381 "Device '%s' not found", name);
1382 return;
1384 nc = ncs[0];
1386 for (i = 0; i < queues; i++) {
1387 ncs[i]->link_down = !up;
1390 if (nc->info->link_status_changed) {
1391 nc->info->link_status_changed(nc);
1394 if (nc->peer) {
1395 /* Change peer link only if the peer is NIC and then notify peer.
1396 * If the peer is a HUBPORT or a backend, we do not change the
1397 * link status.
1399 * This behavior is compatible with qemu hubs where there could be
1400 * multiple clients that can still communicate with each other in
1401 * disconnected mode. For now maintain this compatibility.
1403 if (nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
1404 for (i = 0; i < queues; i++) {
1405 ncs[i]->peer->link_down = !up;
1408 if (nc->peer->info->link_status_changed) {
1409 nc->peer->info->link_status_changed(nc->peer);
1414 static void net_vm_change_state_handler(void *opaque, int running,
1415 RunState state)
1417 NetClientState *nc;
1418 NetClientState *tmp;
1420 QTAILQ_FOREACH_SAFE(nc, &net_clients, next, tmp) {
1421 if (running) {
1422 /* Flush queued packets and wake up backends. */
1423 if (nc->peer && qemu_can_send_packet(nc)) {
1424 qemu_flush_queued_packets(nc->peer);
1426 } else {
1427 /* Complete all queued packets, to guarantee we don't modify
1428 * state later when VM is not running.
1430 qemu_flush_or_purge_queued_packets(nc, true);
1435 void net_cleanup(void)
1437 NetClientState *nc;
1439 /* We may del multiple entries during qemu_del_net_client(),
1440 * so QTAILQ_FOREACH_SAFE() is also not safe here.
1442 while (!QTAILQ_EMPTY(&net_clients)) {
1443 nc = QTAILQ_FIRST(&net_clients);
1444 if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
1445 qemu_del_nic(qemu_get_nic(nc));
1446 } else {
1447 qemu_del_net_client(nc);
1451 qemu_del_vm_change_state_handler(net_change_state_entry);
1454 void net_check_clients(void)
1456 NetClientState *nc;
1457 int i;
1459 net_hub_check_clients();
1461 QTAILQ_FOREACH(nc, &net_clients, next) {
1462 if (!nc->peer) {
1463 warn_report("%s %s has no peer",
1464 nc->info->type == NET_CLIENT_DRIVER_NIC
1465 ? "nic" : "netdev",
1466 nc->name);
1470 /* Check that all NICs requested via -net nic actually got created.
1471 * NICs created via -device don't need to be checked here because
1472 * they are always instantiated.
1474 for (i = 0; i < MAX_NICS; i++) {
1475 NICInfo *nd = &nd_table[i];
1476 if (nd->used && !nd->instantiated) {
1477 warn_report("requested NIC (%s, model %s) "
1478 "was not created (not supported by this machine?)",
1479 nd->name ? nd->name : "anonymous",
1480 nd->model ? nd->model : "unspecified");
1485 static int net_init_client(void *dummy, QemuOpts *opts, Error **errp)
1487 return net_client_init(opts, false, errp);
1490 static int net_init_netdev(void *dummy, QemuOpts *opts, Error **errp)
1492 return net_client_init(opts, true, errp);
1495 /* For the convenience "--nic" parameter */
1496 static int net_param_nic(void *dummy, QemuOpts *opts, Error **errp)
1498 char *mac, *nd_id;
1499 int idx, ret;
1500 NICInfo *ni;
1501 const char *type;
1503 type = qemu_opt_get(opts, "type");
1504 if (type && g_str_equal(type, "none")) {
1505 return 0; /* Nothing to do, default_net is cleared in vl.c */
1508 idx = nic_get_free_idx();
1509 if (idx == -1 || nb_nics >= MAX_NICS) {
1510 error_setg(errp, "no more on-board/default NIC slots available");
1511 return -1;
1514 if (!type) {
1515 qemu_opt_set(opts, "type", "user", &error_abort);
1518 ni = &nd_table[idx];
1519 memset(ni, 0, sizeof(*ni));
1520 ni->model = qemu_opt_get_del(opts, "model");
1522 /* Create an ID if the user did not specify one */
1523 nd_id = g_strdup(qemu_opts_id(opts));
1524 if (!nd_id) {
1525 nd_id = g_strdup_printf("__org.qemu.nic%i\n", idx);
1526 qemu_opts_set_id(opts, nd_id);
1529 /* Handle MAC address */
1530 mac = qemu_opt_get_del(opts, "mac");
1531 if (mac) {
1532 ret = net_parse_macaddr(ni->macaddr.a, mac);
1533 g_free(mac);
1534 if (ret) {
1535 error_setg(errp, "invalid syntax for ethernet address");
1536 goto out;
1538 if (is_multicast_ether_addr(ni->macaddr.a)) {
1539 error_setg(errp, "NIC cannot have multicast MAC address");
1540 ret = -1;
1541 goto out;
1544 qemu_macaddr_default_if_unset(&ni->macaddr);
1546 ret = net_client_init(opts, true, errp);
1547 if (ret == 0) {
1548 ni->netdev = qemu_find_netdev(nd_id);
1549 ni->used = true;
1550 nb_nics++;
1553 out:
1554 g_free(nd_id);
1555 return ret;
1558 int net_init_clients(Error **errp)
1560 net_change_state_entry =
1561 qemu_add_vm_change_state_handler(net_vm_change_state_handler, NULL);
1563 QTAILQ_INIT(&net_clients);
1565 if (qemu_opts_foreach(qemu_find_opts("netdev"),
1566 net_init_netdev, NULL, errp)) {
1567 return -1;
1570 if (qemu_opts_foreach(qemu_find_opts("nic"), net_param_nic, NULL, errp)) {
1571 return -1;
1574 if (qemu_opts_foreach(qemu_find_opts("net"), net_init_client, NULL, errp)) {
1575 return -1;
1578 return 0;
1581 int net_client_parse(QemuOptsList *opts_list, const char *optarg)
1583 if (!qemu_opts_parse_noisily(opts_list, optarg, true)) {
1584 return -1;
1587 return 0;
1590 /* From FreeBSD */
1591 /* XXX: optimize */
1592 uint32_t net_crc32(const uint8_t *p, int len)
1594 uint32_t crc;
1595 int carry, i, j;
1596 uint8_t b;
1598 crc = 0xffffffff;
1599 for (i = 0; i < len; i++) {
1600 b = *p++;
1601 for (j = 0; j < 8; j++) {
1602 carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
1603 crc <<= 1;
1604 b >>= 1;
1605 if (carry) {
1606 crc = ((crc ^ POLYNOMIAL_BE) | carry);
1611 return crc;
1614 uint32_t net_crc32_le(const uint8_t *p, int len)
1616 uint32_t crc;
1617 int carry, i, j;
1618 uint8_t b;
1620 crc = 0xffffffff;
1621 for (i = 0; i < len; i++) {
1622 b = *p++;
1623 for (j = 0; j < 8; j++) {
1624 carry = (crc & 0x1) ^ (b & 0x01);
1625 crc >>= 1;
1626 b >>= 1;
1627 if (carry) {
1628 crc ^= POLYNOMIAL_LE;
1633 return crc;
1636 QemuOptsList qemu_netdev_opts = {
1637 .name = "netdev",
1638 .implied_opt_name = "type",
1639 .head = QTAILQ_HEAD_INITIALIZER(qemu_netdev_opts.head),
1640 .desc = {
1642 * no elements => accept any params
1643 * validation will happen later
1645 { /* end of list */ }
1649 QemuOptsList qemu_nic_opts = {
1650 .name = "nic",
1651 .implied_opt_name = "type",
1652 .head = QTAILQ_HEAD_INITIALIZER(qemu_nic_opts.head),
1653 .desc = {
1655 * no elements => accept any params
1656 * validation will happen later
1658 { /* end of list */ }
1662 QemuOptsList qemu_net_opts = {
1663 .name = "net",
1664 .implied_opt_name = "type",
1665 .head = QTAILQ_HEAD_INITIALIZER(qemu_net_opts.head),
1666 .desc = {
1668 * no elements => accept any params
1669 * validation will happen later
1671 { /* end of list */ }
1675 void net_socket_rs_init(SocketReadState *rs,
1676 SocketReadStateFinalize *finalize,
1677 bool vnet_hdr)
1679 rs->state = 0;
1680 rs->vnet_hdr = vnet_hdr;
1681 rs->index = 0;
1682 rs->packet_len = 0;
1683 rs->vnet_hdr_len = 0;
1684 memset(rs->buf, 0, sizeof(rs->buf));
1685 rs->finalize = finalize;
1689 * Returns
1690 * 0: success
1691 * -1: error occurs
1693 int net_fill_rstate(SocketReadState *rs, const uint8_t *buf, int size)
1695 unsigned int l;
1697 while (size > 0) {
1698 /* Reassemble a packet from the network.
1699 * 0 = getting length.
1700 * 1 = getting vnet header length.
1701 * 2 = getting data.
1703 switch (rs->state) {
1704 case 0:
1705 l = 4 - rs->index;
1706 if (l > size) {
1707 l = size;
1709 memcpy(rs->buf + rs->index, buf, l);
1710 buf += l;
1711 size -= l;
1712 rs->index += l;
1713 if (rs->index == 4) {
1714 /* got length */
1715 rs->packet_len = ntohl(*(uint32_t *)rs->buf);
1716 rs->index = 0;
1717 if (rs->vnet_hdr) {
1718 rs->state = 1;
1719 } else {
1720 rs->state = 2;
1721 rs->vnet_hdr_len = 0;
1724 break;
1725 case 1:
1726 l = 4 - rs->index;
1727 if (l > size) {
1728 l = size;
1730 memcpy(rs->buf + rs->index, buf, l);
1731 buf += l;
1732 size -= l;
1733 rs->index += l;
1734 if (rs->index == 4) {
1735 /* got vnet header length */
1736 rs->vnet_hdr_len = ntohl(*(uint32_t *)rs->buf);
1737 rs->index = 0;
1738 rs->state = 2;
1740 break;
1741 case 2:
1742 l = rs->packet_len - rs->index;
1743 if (l > size) {
1744 l = size;
1746 if (rs->index + l <= sizeof(rs->buf)) {
1747 memcpy(rs->buf + rs->index, buf, l);
1748 } else {
1749 fprintf(stderr, "serious error: oversized packet received,"
1750 "connection terminated.\n");
1751 rs->index = rs->state = 0;
1752 return -1;
1755 rs->index += l;
1756 buf += l;
1757 size -= l;
1758 if (rs->index >= rs->packet_len) {
1759 rs->index = 0;
1760 rs->state = 0;
1761 assert(rs->finalize);
1762 rs->finalize(rs);
1764 break;
1768 assert(size == 0);
1769 return 0;