tests/boot-serial: Check the 40p machine, too
[qemu.git] / net / net.c
blob5222e450698c4efef07b8c955e195134cc497581
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 "hw/qdev.h"
45 #include "qemu/iov.h"
46 #include "qemu/main-loop.h"
47 #include "qemu/option.h"
48 #include "qapi/error.h"
49 #include "qapi/opts-visitor.h"
50 #include "sysemu/sysemu.h"
51 #include "sysemu/qtest.h"
52 #include "net/filter.h"
53 #include "qapi/string-output-visitor.h"
55 /* Net bridge is currently not supported for W32. */
56 #if !defined(_WIN32)
57 # define CONFIG_NET_BRIDGE
58 #endif
60 static VMChangeStateEntry *net_change_state_entry;
61 static QTAILQ_HEAD(, NetClientState) net_clients;
63 /***********************************************************/
64 /* network device redirectors */
66 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
68 const char *p, *p1;
69 int len;
70 p = *pp;
71 p1 = strchr(p, sep);
72 if (!p1)
73 return -1;
74 len = p1 - p;
75 p1++;
76 if (buf_size > 0) {
77 if (len > buf_size - 1)
78 len = buf_size - 1;
79 memcpy(buf, p, len);
80 buf[len] = '\0';
82 *pp = p1;
83 return 0;
86 int parse_host_port(struct sockaddr_in *saddr, const char *str,
87 Error **errp)
89 char buf[512];
90 struct hostent *he;
91 const char *p, *r;
92 int port;
94 p = str;
95 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
96 error_setg(errp, "host address '%s' doesn't contain ':' "
97 "separating host from port", str);
98 return -1;
100 saddr->sin_family = AF_INET;
101 if (buf[0] == '\0') {
102 saddr->sin_addr.s_addr = 0;
103 } else {
104 if (qemu_isdigit(buf[0])) {
105 if (!inet_aton(buf, &saddr->sin_addr)) {
106 error_setg(errp, "host address '%s' is not a valid "
107 "IPv4 address", buf);
108 return -1;
110 } else {
111 he = gethostbyname(buf);
112 if (he == NULL) {
113 error_setg(errp, "can't resolve host address '%s'", buf);
114 return - 1;
116 saddr->sin_addr = *(struct in_addr *)he->h_addr;
119 port = strtol(p, (char **)&r, 0);
120 if (r == p) {
121 error_setg(errp, "port number '%s' is invalid", p);
122 return -1;
124 saddr->sin_port = htons(port);
125 return 0;
128 char *qemu_mac_strdup_printf(const uint8_t *macaddr)
130 return g_strdup_printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
131 macaddr[0], macaddr[1], macaddr[2],
132 macaddr[3], macaddr[4], macaddr[5]);
135 void qemu_format_nic_info_str(NetClientState *nc, uint8_t macaddr[6])
137 snprintf(nc->info_str, sizeof(nc->info_str),
138 "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
139 nc->model,
140 macaddr[0], macaddr[1], macaddr[2],
141 macaddr[3], macaddr[4], macaddr[5]);
144 static int mac_table[256] = {0};
146 static void qemu_macaddr_set_used(MACAddr *macaddr)
148 int index;
150 for (index = 0x56; index < 0xFF; index++) {
151 if (macaddr->a[5] == index) {
152 mac_table[index]++;
157 static void qemu_macaddr_set_free(MACAddr *macaddr)
159 int index;
160 static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
162 if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
163 return;
165 for (index = 0x56; index < 0xFF; index++) {
166 if (macaddr->a[5] == index) {
167 mac_table[index]--;
172 static int qemu_macaddr_get_free(void)
174 int index;
176 for (index = 0x56; index < 0xFF; index++) {
177 if (mac_table[index] == 0) {
178 return index;
182 return -1;
185 void qemu_macaddr_default_if_unset(MACAddr *macaddr)
187 static const MACAddr zero = { .a = { 0,0,0,0,0,0 } };
188 static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
190 if (memcmp(macaddr, &zero, sizeof(zero)) != 0) {
191 if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
192 return;
193 } else {
194 qemu_macaddr_set_used(macaddr);
195 return;
199 macaddr->a[0] = 0x52;
200 macaddr->a[1] = 0x54;
201 macaddr->a[2] = 0x00;
202 macaddr->a[3] = 0x12;
203 macaddr->a[4] = 0x34;
204 macaddr->a[5] = qemu_macaddr_get_free();
205 qemu_macaddr_set_used(macaddr);
209 * Generate a name for net client
211 * Only net clients created with the legacy -net option and NICs need this.
213 static char *assign_name(NetClientState *nc1, const char *model)
215 NetClientState *nc;
216 int id = 0;
218 QTAILQ_FOREACH(nc, &net_clients, next) {
219 if (nc == nc1) {
220 continue;
222 if (strcmp(nc->model, model) == 0) {
223 id++;
227 return g_strdup_printf("%s.%d", model, id);
230 static void qemu_net_client_destructor(NetClientState *nc)
232 g_free(nc);
235 static void qemu_net_client_setup(NetClientState *nc,
236 NetClientInfo *info,
237 NetClientState *peer,
238 const char *model,
239 const char *name,
240 NetClientDestructor *destructor)
242 nc->info = info;
243 nc->model = g_strdup(model);
244 if (name) {
245 nc->name = g_strdup(name);
246 } else {
247 nc->name = assign_name(nc, model);
250 if (peer) {
251 assert(!peer->peer);
252 nc->peer = peer;
253 peer->peer = nc;
255 QTAILQ_INSERT_TAIL(&net_clients, nc, next);
257 nc->incoming_queue = qemu_new_net_queue(qemu_deliver_packet_iov, nc);
258 nc->destructor = destructor;
259 QTAILQ_INIT(&nc->filters);
262 NetClientState *qemu_new_net_client(NetClientInfo *info,
263 NetClientState *peer,
264 const char *model,
265 const char *name)
267 NetClientState *nc;
269 assert(info->size >= sizeof(NetClientState));
271 nc = g_malloc0(info->size);
272 qemu_net_client_setup(nc, info, peer, model, name,
273 qemu_net_client_destructor);
275 return nc;
278 NICState *qemu_new_nic(NetClientInfo *info,
279 NICConf *conf,
280 const char *model,
281 const char *name,
282 void *opaque)
284 NetClientState **peers = conf->peers.ncs;
285 NICState *nic;
286 int i, queues = MAX(1, conf->peers.queues);
288 assert(info->type == NET_CLIENT_DRIVER_NIC);
289 assert(info->size >= sizeof(NICState));
291 nic = g_malloc0(info->size + sizeof(NetClientState) * queues);
292 nic->ncs = (void *)nic + info->size;
293 nic->conf = conf;
294 nic->opaque = opaque;
296 for (i = 0; i < queues; i++) {
297 qemu_net_client_setup(&nic->ncs[i], info, peers[i], model, name,
298 NULL);
299 nic->ncs[i].queue_index = i;
302 return nic;
305 NetClientState *qemu_get_subqueue(NICState *nic, int queue_index)
307 return nic->ncs + queue_index;
310 NetClientState *qemu_get_queue(NICState *nic)
312 return qemu_get_subqueue(nic, 0);
315 NICState *qemu_get_nic(NetClientState *nc)
317 NetClientState *nc0 = nc - nc->queue_index;
319 return (NICState *)((void *)nc0 - nc->info->size);
322 void *qemu_get_nic_opaque(NetClientState *nc)
324 NICState *nic = qemu_get_nic(nc);
326 return nic->opaque;
329 static void qemu_cleanup_net_client(NetClientState *nc)
331 QTAILQ_REMOVE(&net_clients, nc, next);
333 if (nc->info->cleanup) {
334 nc->info->cleanup(nc);
338 static void qemu_free_net_client(NetClientState *nc)
340 if (nc->incoming_queue) {
341 qemu_del_net_queue(nc->incoming_queue);
343 if (nc->peer) {
344 nc->peer->peer = NULL;
346 g_free(nc->name);
347 g_free(nc->model);
348 if (nc->destructor) {
349 nc->destructor(nc);
353 void qemu_del_net_client(NetClientState *nc)
355 NetClientState *ncs[MAX_QUEUE_NUM];
356 int queues, i;
357 NetFilterState *nf, *next;
359 assert(nc->info->type != NET_CLIENT_DRIVER_NIC);
361 /* If the NetClientState belongs to a multiqueue backend, we will change all
362 * other NetClientStates also.
364 queues = qemu_find_net_clients_except(nc->name, ncs,
365 NET_CLIENT_DRIVER_NIC,
366 MAX_QUEUE_NUM);
367 assert(queues != 0);
369 QTAILQ_FOREACH_SAFE(nf, &nc->filters, next, next) {
370 object_unparent(OBJECT(nf));
373 /* If there is a peer NIC, delete and cleanup client, but do not free. */
374 if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
375 NICState *nic = qemu_get_nic(nc->peer);
376 if (nic->peer_deleted) {
377 return;
379 nic->peer_deleted = true;
381 for (i = 0; i < queues; i++) {
382 ncs[i]->peer->link_down = true;
385 if (nc->peer->info->link_status_changed) {
386 nc->peer->info->link_status_changed(nc->peer);
389 for (i = 0; i < queues; i++) {
390 qemu_cleanup_net_client(ncs[i]);
393 return;
396 for (i = 0; i < queues; i++) {
397 qemu_cleanup_net_client(ncs[i]);
398 qemu_free_net_client(ncs[i]);
402 void qemu_del_nic(NICState *nic)
404 int i, queues = MAX(nic->conf->peers.queues, 1);
406 qemu_macaddr_set_free(&nic->conf->macaddr);
408 /* If this is a peer NIC and peer has already been deleted, free it now. */
409 if (nic->peer_deleted) {
410 for (i = 0; i < queues; i++) {
411 qemu_free_net_client(qemu_get_subqueue(nic, i)->peer);
415 for (i = queues - 1; i >= 0; i--) {
416 NetClientState *nc = qemu_get_subqueue(nic, i);
418 qemu_cleanup_net_client(nc);
419 qemu_free_net_client(nc);
422 g_free(nic);
425 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
427 NetClientState *nc;
429 QTAILQ_FOREACH(nc, &net_clients, next) {
430 if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
431 if (nc->queue_index == 0) {
432 func(qemu_get_nic(nc), opaque);
438 bool qemu_has_ufo(NetClientState *nc)
440 if (!nc || !nc->info->has_ufo) {
441 return false;
444 return nc->info->has_ufo(nc);
447 bool qemu_has_vnet_hdr(NetClientState *nc)
449 if (!nc || !nc->info->has_vnet_hdr) {
450 return false;
453 return nc->info->has_vnet_hdr(nc);
456 bool qemu_has_vnet_hdr_len(NetClientState *nc, int len)
458 if (!nc || !nc->info->has_vnet_hdr_len) {
459 return false;
462 return nc->info->has_vnet_hdr_len(nc, len);
465 void qemu_using_vnet_hdr(NetClientState *nc, bool enable)
467 if (!nc || !nc->info->using_vnet_hdr) {
468 return;
471 nc->info->using_vnet_hdr(nc, enable);
474 void qemu_set_offload(NetClientState *nc, int csum, int tso4, int tso6,
475 int ecn, int ufo)
477 if (!nc || !nc->info->set_offload) {
478 return;
481 nc->info->set_offload(nc, csum, tso4, tso6, ecn, ufo);
484 void qemu_set_vnet_hdr_len(NetClientState *nc, int len)
486 if (!nc || !nc->info->set_vnet_hdr_len) {
487 return;
490 nc->vnet_hdr_len = len;
491 nc->info->set_vnet_hdr_len(nc, len);
494 int qemu_set_vnet_le(NetClientState *nc, bool is_le)
496 #ifdef HOST_WORDS_BIGENDIAN
497 if (!nc || !nc->info->set_vnet_le) {
498 return -ENOSYS;
501 return nc->info->set_vnet_le(nc, is_le);
502 #else
503 return 0;
504 #endif
507 int qemu_set_vnet_be(NetClientState *nc, bool is_be)
509 #ifdef HOST_WORDS_BIGENDIAN
510 return 0;
511 #else
512 if (!nc || !nc->info->set_vnet_be) {
513 return -ENOSYS;
516 return nc->info->set_vnet_be(nc, is_be);
517 #endif
520 int qemu_can_send_packet(NetClientState *sender)
522 int vm_running = runstate_is_running();
524 if (!vm_running) {
525 return 0;
528 if (!sender->peer) {
529 return 1;
532 if (sender->peer->receive_disabled) {
533 return 0;
534 } else if (sender->peer->info->can_receive &&
535 !sender->peer->info->can_receive(sender->peer)) {
536 return 0;
538 return 1;
541 static ssize_t filter_receive_iov(NetClientState *nc,
542 NetFilterDirection direction,
543 NetClientState *sender,
544 unsigned flags,
545 const struct iovec *iov,
546 int iovcnt,
547 NetPacketSent *sent_cb)
549 ssize_t ret = 0;
550 NetFilterState *nf = NULL;
552 if (direction == NET_FILTER_DIRECTION_TX) {
553 QTAILQ_FOREACH(nf, &nc->filters, next) {
554 ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
555 iovcnt, sent_cb);
556 if (ret) {
557 return ret;
560 } else {
561 QTAILQ_FOREACH_REVERSE(nf, &nc->filters, NetFilterHead, next) {
562 ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
563 iovcnt, sent_cb);
564 if (ret) {
565 return ret;
570 return ret;
573 static ssize_t filter_receive(NetClientState *nc,
574 NetFilterDirection direction,
575 NetClientState *sender,
576 unsigned flags,
577 const uint8_t *data,
578 size_t size,
579 NetPacketSent *sent_cb)
581 struct iovec iov = {
582 .iov_base = (void *)data,
583 .iov_len = size
586 return filter_receive_iov(nc, direction, sender, flags, &iov, 1, sent_cb);
589 void qemu_purge_queued_packets(NetClientState *nc)
591 if (!nc->peer) {
592 return;
595 qemu_net_queue_purge(nc->peer->incoming_queue, nc);
598 static
599 void qemu_flush_or_purge_queued_packets(NetClientState *nc, bool purge)
601 nc->receive_disabled = 0;
603 if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_HUBPORT) {
604 if (net_hub_flush(nc->peer)) {
605 qemu_notify_event();
608 if (qemu_net_queue_flush(nc->incoming_queue)) {
609 /* We emptied the queue successfully, signal to the IO thread to repoll
610 * the file descriptor (for tap, for example).
612 qemu_notify_event();
613 } else if (purge) {
614 /* Unable to empty the queue, purge remaining packets */
615 qemu_net_queue_purge(nc->incoming_queue, nc);
619 void qemu_flush_queued_packets(NetClientState *nc)
621 qemu_flush_or_purge_queued_packets(nc, false);
624 static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
625 unsigned flags,
626 const uint8_t *buf, int size,
627 NetPacketSent *sent_cb)
629 NetQueue *queue;
630 int ret;
632 #ifdef DEBUG_NET
633 printf("qemu_send_packet_async:\n");
634 qemu_hexdump((const char *)buf, stdout, "net", size);
635 #endif
637 if (sender->link_down || !sender->peer) {
638 return size;
641 /* Let filters handle the packet first */
642 ret = filter_receive(sender, NET_FILTER_DIRECTION_TX,
643 sender, flags, buf, size, sent_cb);
644 if (ret) {
645 return ret;
648 ret = filter_receive(sender->peer, NET_FILTER_DIRECTION_RX,
649 sender, flags, buf, size, sent_cb);
650 if (ret) {
651 return ret;
654 queue = sender->peer->incoming_queue;
656 return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
659 ssize_t qemu_send_packet_async(NetClientState *sender,
660 const uint8_t *buf, int size,
661 NetPacketSent *sent_cb)
663 return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
664 buf, size, sent_cb);
667 void qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size)
669 qemu_send_packet_async(nc, buf, size, NULL);
672 ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size)
674 return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW,
675 buf, size, NULL);
678 static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
679 int iovcnt, unsigned flags)
681 uint8_t *buf = NULL;
682 uint8_t *buffer;
683 size_t offset;
684 ssize_t ret;
686 if (iovcnt == 1) {
687 buffer = iov[0].iov_base;
688 offset = iov[0].iov_len;
689 } else {
690 offset = iov_size(iov, iovcnt);
691 if (offset > NET_BUFSIZE) {
692 return -1;
694 buf = g_malloc(offset);
695 buffer = buf;
696 offset = iov_to_buf(iov, iovcnt, 0, buf, offset);
699 if (flags & QEMU_NET_PACKET_FLAG_RAW && nc->info->receive_raw) {
700 ret = nc->info->receive_raw(nc, buffer, offset);
701 } else {
702 ret = nc->info->receive(nc, buffer, offset);
705 g_free(buf);
706 return ret;
709 ssize_t qemu_deliver_packet_iov(NetClientState *sender,
710 unsigned flags,
711 const struct iovec *iov,
712 int iovcnt,
713 void *opaque)
715 NetClientState *nc = opaque;
716 int ret;
718 if (nc->link_down) {
719 return iov_size(iov, iovcnt);
722 if (nc->receive_disabled) {
723 return 0;
726 if (nc->info->receive_iov && !(flags & QEMU_NET_PACKET_FLAG_RAW)) {
727 ret = nc->info->receive_iov(nc, iov, iovcnt);
728 } else {
729 ret = nc_sendv_compat(nc, iov, iovcnt, flags);
732 if (ret == 0) {
733 nc->receive_disabled = 1;
736 return ret;
739 ssize_t qemu_sendv_packet_async(NetClientState *sender,
740 const struct iovec *iov, int iovcnt,
741 NetPacketSent *sent_cb)
743 NetQueue *queue;
744 int ret;
746 if (sender->link_down || !sender->peer) {
747 return iov_size(iov, iovcnt);
750 /* Let filters handle the packet first */
751 ret = filter_receive_iov(sender, NET_FILTER_DIRECTION_TX, sender,
752 QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
753 if (ret) {
754 return ret;
757 ret = filter_receive_iov(sender->peer, NET_FILTER_DIRECTION_RX, sender,
758 QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
759 if (ret) {
760 return ret;
763 queue = sender->peer->incoming_queue;
765 return qemu_net_queue_send_iov(queue, sender,
766 QEMU_NET_PACKET_FLAG_NONE,
767 iov, iovcnt, sent_cb);
770 ssize_t
771 qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt)
773 return qemu_sendv_packet_async(nc, iov, iovcnt, NULL);
776 NetClientState *qemu_find_netdev(const char *id)
778 NetClientState *nc;
780 QTAILQ_FOREACH(nc, &net_clients, next) {
781 if (nc->info->type == NET_CLIENT_DRIVER_NIC)
782 continue;
783 if (!strcmp(nc->name, id)) {
784 return nc;
788 return NULL;
791 int qemu_find_net_clients_except(const char *id, NetClientState **ncs,
792 NetClientDriver type, int max)
794 NetClientState *nc;
795 int ret = 0;
797 QTAILQ_FOREACH(nc, &net_clients, next) {
798 if (nc->info->type == type) {
799 continue;
801 if (!id || !strcmp(nc->name, id)) {
802 if (ret < max) {
803 ncs[ret] = nc;
805 ret++;
809 return ret;
812 static int nic_get_free_idx(void)
814 int index;
816 for (index = 0; index < MAX_NICS; index++)
817 if (!nd_table[index].used)
818 return index;
819 return -1;
822 int qemu_show_nic_models(const char *arg, const char *const *models)
824 int i;
826 if (!arg || !is_help_option(arg)) {
827 return 0;
830 fprintf(stderr, "qemu: Supported NIC models: ");
831 for (i = 0 ; models[i]; i++)
832 fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
833 return 1;
836 void qemu_check_nic_model(NICInfo *nd, const char *model)
838 const char *models[2];
840 models[0] = model;
841 models[1] = NULL;
843 if (qemu_show_nic_models(nd->model, models))
844 exit(0);
845 if (qemu_find_nic_model(nd, models, model) < 0)
846 exit(1);
849 int qemu_find_nic_model(NICInfo *nd, const char * const *models,
850 const char *default_model)
852 int i;
854 if (!nd->model)
855 nd->model = g_strdup(default_model);
857 for (i = 0 ; models[i]; i++) {
858 if (strcmp(nd->model, models[i]) == 0)
859 return i;
862 error_report("Unsupported NIC model: %s", nd->model);
863 return -1;
866 static int net_init_nic(const Netdev *netdev, const char *name,
867 NetClientState *peer, Error **errp)
869 int idx;
870 NICInfo *nd;
871 const NetLegacyNicOptions *nic;
873 assert(netdev->type == NET_CLIENT_DRIVER_NIC);
874 nic = &netdev->u.nic;
876 idx = nic_get_free_idx();
877 if (idx == -1 || nb_nics >= MAX_NICS) {
878 error_setg(errp, "too many NICs");
879 return -1;
882 nd = &nd_table[idx];
884 memset(nd, 0, sizeof(*nd));
886 if (nic->has_netdev) {
887 nd->netdev = qemu_find_netdev(nic->netdev);
888 if (!nd->netdev) {
889 error_setg(errp, "netdev '%s' not found", nic->netdev);
890 return -1;
892 } else {
893 assert(peer);
894 nd->netdev = peer;
896 nd->name = g_strdup(name);
897 if (nic->has_model) {
898 nd->model = g_strdup(nic->model);
900 if (nic->has_addr) {
901 nd->devaddr = g_strdup(nic->addr);
904 if (nic->has_macaddr &&
905 net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {
906 error_setg(errp, "invalid syntax for ethernet address");
907 return -1;
909 if (nic->has_macaddr &&
910 is_multicast_ether_addr(nd->macaddr.a)) {
911 error_setg(errp,
912 "NIC cannot have multicast MAC address (odd 1st byte)");
913 return -1;
915 qemu_macaddr_default_if_unset(&nd->macaddr);
917 if (nic->has_vectors) {
918 if (nic->vectors > 0x7ffffff) {
919 error_setg(errp, "invalid # of vectors: %"PRIu32, nic->vectors);
920 return -1;
922 nd->nvectors = nic->vectors;
923 } else {
924 nd->nvectors = DEV_NVECTORS_UNSPECIFIED;
927 nd->used = 1;
928 nb_nics++;
930 return idx;
934 static int (* const net_client_init_fun[NET_CLIENT_DRIVER__MAX])(
935 const Netdev *netdev,
936 const char *name,
937 NetClientState *peer, Error **errp) = {
938 [NET_CLIENT_DRIVER_NIC] = net_init_nic,
939 #ifdef CONFIG_SLIRP
940 [NET_CLIENT_DRIVER_USER] = net_init_slirp,
941 #endif
942 [NET_CLIENT_DRIVER_TAP] = net_init_tap,
943 [NET_CLIENT_DRIVER_SOCKET] = net_init_socket,
944 #ifdef CONFIG_VDE
945 [NET_CLIENT_DRIVER_VDE] = net_init_vde,
946 #endif
947 #ifdef CONFIG_NETMAP
948 [NET_CLIENT_DRIVER_NETMAP] = net_init_netmap,
949 #endif
950 #ifdef CONFIG_NET_BRIDGE
951 [NET_CLIENT_DRIVER_BRIDGE] = net_init_bridge,
952 #endif
953 [NET_CLIENT_DRIVER_HUBPORT] = net_init_hubport,
954 #ifdef CONFIG_VHOST_NET_USED
955 [NET_CLIENT_DRIVER_VHOST_USER] = net_init_vhost_user,
956 #endif
957 #ifdef CONFIG_L2TPV3
958 [NET_CLIENT_DRIVER_L2TPV3] = net_init_l2tpv3,
959 #endif
963 static int net_client_init1(const void *object, bool is_netdev, Error **errp)
965 Netdev legacy = {0};
966 const Netdev *netdev;
967 const char *name;
968 NetClientState *peer = NULL;
969 static bool vlan_warned;
971 if (is_netdev) {
972 netdev = object;
973 name = netdev->id;
975 if (netdev->type == NET_CLIENT_DRIVER_NIC ||
976 !net_client_init_fun[netdev->type]) {
977 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
978 "a netdev backend type");
979 return -1;
981 } else {
982 const NetLegacy *net = object;
983 const NetLegacyOptions *opts = net->opts;
984 legacy.id = net->id;
985 netdev = &legacy;
986 /* missing optional values have been initialized to "all bits zero" */
987 name = net->has_id ? net->id : net->name;
989 /* Map the old options to the new flat type */
990 switch (opts->type) {
991 case NET_LEGACY_OPTIONS_TYPE_NONE:
992 return 0; /* nothing to do */
993 case NET_LEGACY_OPTIONS_TYPE_NIC:
994 legacy.type = NET_CLIENT_DRIVER_NIC;
995 legacy.u.nic = opts->u.nic;
996 break;
997 case NET_LEGACY_OPTIONS_TYPE_USER:
998 legacy.type = NET_CLIENT_DRIVER_USER;
999 legacy.u.user = opts->u.user;
1000 break;
1001 case NET_LEGACY_OPTIONS_TYPE_TAP:
1002 legacy.type = NET_CLIENT_DRIVER_TAP;
1003 legacy.u.tap = opts->u.tap;
1004 break;
1005 case NET_LEGACY_OPTIONS_TYPE_L2TPV3:
1006 legacy.type = NET_CLIENT_DRIVER_L2TPV3;
1007 legacy.u.l2tpv3 = opts->u.l2tpv3;
1008 break;
1009 case NET_LEGACY_OPTIONS_TYPE_SOCKET:
1010 legacy.type = NET_CLIENT_DRIVER_SOCKET;
1011 legacy.u.socket = opts->u.socket;
1012 break;
1013 case NET_LEGACY_OPTIONS_TYPE_VDE:
1014 legacy.type = NET_CLIENT_DRIVER_VDE;
1015 legacy.u.vde = opts->u.vde;
1016 break;
1017 case NET_LEGACY_OPTIONS_TYPE_BRIDGE:
1018 legacy.type = NET_CLIENT_DRIVER_BRIDGE;
1019 legacy.u.bridge = opts->u.bridge;
1020 break;
1021 case NET_LEGACY_OPTIONS_TYPE_NETMAP:
1022 legacy.type = NET_CLIENT_DRIVER_NETMAP;
1023 legacy.u.netmap = opts->u.netmap;
1024 break;
1025 case NET_LEGACY_OPTIONS_TYPE_VHOST_USER:
1026 legacy.type = NET_CLIENT_DRIVER_VHOST_USER;
1027 legacy.u.vhost_user = opts->u.vhost_user;
1028 break;
1029 default:
1030 abort();
1033 if (!net_client_init_fun[netdev->type]) {
1034 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
1035 "a net backend type (maybe it is not compiled "
1036 "into this binary)");
1037 return -1;
1040 /* Do not add to a vlan if it's a nic with a netdev= parameter. */
1041 if (netdev->type != NET_CLIENT_DRIVER_NIC ||
1042 !opts->u.nic.has_netdev) {
1043 peer = net_hub_add_port(net->has_vlan ? net->vlan : 0, NULL, NULL);
1046 if (net->has_vlan && !vlan_warned) {
1047 error_report("'vlan' is deprecated. Please use 'netdev' instead.");
1048 vlan_warned = true;
1052 if (net_client_init_fun[netdev->type](netdev, name, peer, errp) < 0) {
1053 /* FIXME drop when all init functions store an Error */
1054 if (errp && !*errp) {
1055 error_setg(errp, QERR_DEVICE_INIT_FAILED,
1056 NetClientDriver_str(netdev->type));
1058 return -1;
1060 return 0;
1063 static void show_netdevs(void)
1065 int idx;
1066 const char *available_netdevs[] = {
1067 "socket",
1068 "hubport",
1069 "tap",
1070 #ifdef CONFIG_SLIRP
1071 "user",
1072 #endif
1073 #ifdef CONFIG_L2TPV3
1074 "l2tpv3",
1075 #endif
1076 #ifdef CONFIG_VDE
1077 "vde",
1078 #endif
1079 #ifdef CONFIG_NET_BRIDGE
1080 "bridge",
1081 #endif
1082 #ifdef CONFIG_NETMAP
1083 "netmap",
1084 #endif
1085 #ifdef CONFIG_POSIX
1086 "vhost-user",
1087 #endif
1090 printf("Available netdev backend types:\n");
1091 for (idx = 0; idx < ARRAY_SIZE(available_netdevs); idx++) {
1092 puts(available_netdevs[idx]);
1096 static int net_client_init(QemuOpts *opts, bool is_netdev, Error **errp)
1098 void *object = NULL;
1099 Error *err = NULL;
1100 int ret = -1;
1101 Visitor *v = opts_visitor_new(opts);
1103 if (is_netdev && is_help_option(qemu_opt_get(opts, "type"))) {
1104 show_netdevs();
1105 exit(0);
1106 } else {
1107 /* Parse convenience option format ip6-net=fec0::0[/64] */
1108 const char *ip6_net = qemu_opt_get(opts, "ipv6-net");
1110 if (ip6_net) {
1111 char buf[strlen(ip6_net) + 1];
1113 if (get_str_sep(buf, sizeof(buf), &ip6_net, '/') < 0) {
1114 /* Default 64bit prefix length. */
1115 qemu_opt_set(opts, "ipv6-prefix", ip6_net, &error_abort);
1116 qemu_opt_set_number(opts, "ipv6-prefixlen", 64, &error_abort);
1117 } else {
1118 /* User-specified prefix length. */
1119 unsigned long len;
1120 int err;
1122 qemu_opt_set(opts, "ipv6-prefix", buf, &error_abort);
1123 err = qemu_strtoul(ip6_net, NULL, 10, &len);
1125 if (err) {
1126 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1127 "ipv6-prefix", "a number");
1128 } else {
1129 qemu_opt_set_number(opts, "ipv6-prefixlen", len,
1130 &error_abort);
1133 qemu_opt_unset(opts, "ipv6-net");
1137 if (is_netdev) {
1138 visit_type_Netdev(v, NULL, (Netdev **)&object, &err);
1139 } else {
1140 visit_type_NetLegacy(v, NULL, (NetLegacy **)&object, &err);
1143 if (!err) {
1144 ret = net_client_init1(object, is_netdev, &err);
1147 if (is_netdev) {
1148 qapi_free_Netdev(object);
1149 } else {
1150 qapi_free_NetLegacy(object);
1153 error_propagate(errp, err);
1154 visit_free(v);
1155 return ret;
1158 void netdev_add(QemuOpts *opts, Error **errp)
1160 net_client_init(opts, true, errp);
1163 void qmp_netdev_add(QDict *qdict, QObject **ret, Error **errp)
1165 Error *local_err = NULL;
1166 QemuOptsList *opts_list;
1167 QemuOpts *opts;
1169 opts_list = qemu_find_opts_err("netdev", &local_err);
1170 if (local_err) {
1171 goto out;
1174 opts = qemu_opts_from_qdict(opts_list, qdict, &local_err);
1175 if (local_err) {
1176 goto out;
1179 netdev_add(opts, &local_err);
1180 if (local_err) {
1181 qemu_opts_del(opts);
1182 goto out;
1185 out:
1186 error_propagate(errp, local_err);
1189 void qmp_netdev_del(const char *id, Error **errp)
1191 NetClientState *nc;
1192 QemuOpts *opts;
1194 nc = qemu_find_netdev(id);
1195 if (!nc) {
1196 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1197 "Device '%s' not found", id);
1198 return;
1201 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), id);
1202 if (!opts) {
1203 error_setg(errp, "Device '%s' is not a netdev", id);
1204 return;
1207 qemu_del_net_client(nc);
1208 qemu_opts_del(opts);
1211 static void netfilter_print_info(Monitor *mon, NetFilterState *nf)
1213 char *str;
1214 ObjectProperty *prop;
1215 ObjectPropertyIterator iter;
1216 Visitor *v;
1218 /* generate info str */
1219 object_property_iter_init(&iter, OBJECT(nf));
1220 while ((prop = object_property_iter_next(&iter))) {
1221 if (!strcmp(prop->name, "type")) {
1222 continue;
1224 v = string_output_visitor_new(false, &str);
1225 object_property_get(OBJECT(nf), v, prop->name, NULL);
1226 visit_complete(v, &str);
1227 visit_free(v);
1228 monitor_printf(mon, ",%s=%s", prop->name, str);
1229 g_free(str);
1231 monitor_printf(mon, "\n");
1234 void print_net_client(Monitor *mon, NetClientState *nc)
1236 NetFilterState *nf;
1238 monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
1239 nc->queue_index,
1240 NetClientDriver_str(nc->info->type),
1241 nc->info_str);
1242 if (!QTAILQ_EMPTY(&nc->filters)) {
1243 monitor_printf(mon, "filters:\n");
1245 QTAILQ_FOREACH(nf, &nc->filters, next) {
1246 char *path = object_get_canonical_path_component(OBJECT(nf));
1248 monitor_printf(mon, " - %s: type=%s", path,
1249 object_get_typename(OBJECT(nf)));
1250 netfilter_print_info(mon, nf);
1251 g_free(path);
1255 RxFilterInfoList *qmp_query_rx_filter(bool has_name, const char *name,
1256 Error **errp)
1258 NetClientState *nc;
1259 RxFilterInfoList *filter_list = NULL, *last_entry = NULL;
1261 QTAILQ_FOREACH(nc, &net_clients, next) {
1262 RxFilterInfoList *entry;
1263 RxFilterInfo *info;
1265 if (has_name && strcmp(nc->name, name) != 0) {
1266 continue;
1269 /* only query rx-filter information of NIC */
1270 if (nc->info->type != NET_CLIENT_DRIVER_NIC) {
1271 if (has_name) {
1272 error_setg(errp, "net client(%s) isn't a NIC", name);
1273 return NULL;
1275 continue;
1278 /* only query information on queue 0 since the info is per nic,
1279 * not per queue
1281 if (nc->queue_index != 0)
1282 continue;
1284 if (nc->info->query_rx_filter) {
1285 info = nc->info->query_rx_filter(nc);
1286 entry = g_malloc0(sizeof(*entry));
1287 entry->value = info;
1289 if (!filter_list) {
1290 filter_list = entry;
1291 } else {
1292 last_entry->next = entry;
1294 last_entry = entry;
1295 } else if (has_name) {
1296 error_setg(errp, "net client(%s) doesn't support"
1297 " rx-filter querying", name);
1298 return NULL;
1301 if (has_name) {
1302 break;
1306 if (filter_list == NULL && has_name) {
1307 error_setg(errp, "invalid net client name: %s", name);
1310 return filter_list;
1313 void hmp_info_network(Monitor *mon, const QDict *qdict)
1315 NetClientState *nc, *peer;
1316 NetClientDriver type;
1318 net_hub_info(mon);
1320 QTAILQ_FOREACH(nc, &net_clients, next) {
1321 peer = nc->peer;
1322 type = nc->info->type;
1324 /* Skip if already printed in hub info */
1325 if (net_hub_id_for_client(nc, NULL) == 0) {
1326 continue;
1329 if (!peer || type == NET_CLIENT_DRIVER_NIC) {
1330 print_net_client(mon, nc);
1331 } /* else it's a netdev connected to a NIC, printed with the NIC */
1332 if (peer && type == NET_CLIENT_DRIVER_NIC) {
1333 monitor_printf(mon, " \\ ");
1334 print_net_client(mon, peer);
1339 void qmp_set_link(const char *name, bool up, Error **errp)
1341 NetClientState *ncs[MAX_QUEUE_NUM];
1342 NetClientState *nc;
1343 int queues, i;
1345 queues = qemu_find_net_clients_except(name, ncs,
1346 NET_CLIENT_DRIVER__MAX,
1347 MAX_QUEUE_NUM);
1349 if (queues == 0) {
1350 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1351 "Device '%s' not found", name);
1352 return;
1354 nc = ncs[0];
1356 for (i = 0; i < queues; i++) {
1357 ncs[i]->link_down = !up;
1360 if (nc->info->link_status_changed) {
1361 nc->info->link_status_changed(nc);
1364 if (nc->peer) {
1365 /* Change peer link only if the peer is NIC and then notify peer.
1366 * If the peer is a HUBPORT or a backend, we do not change the
1367 * link status.
1369 * This behavior is compatible with qemu vlans where there could be
1370 * multiple clients that can still communicate with each other in
1371 * disconnected mode. For now maintain this compatibility.
1373 if (nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
1374 for (i = 0; i < queues; i++) {
1375 ncs[i]->peer->link_down = !up;
1378 if (nc->peer->info->link_status_changed) {
1379 nc->peer->info->link_status_changed(nc->peer);
1384 static void net_vm_change_state_handler(void *opaque, int running,
1385 RunState state)
1387 NetClientState *nc;
1388 NetClientState *tmp;
1390 QTAILQ_FOREACH_SAFE(nc, &net_clients, next, tmp) {
1391 if (running) {
1392 /* Flush queued packets and wake up backends. */
1393 if (nc->peer && qemu_can_send_packet(nc)) {
1394 qemu_flush_queued_packets(nc->peer);
1396 } else {
1397 /* Complete all queued packets, to guarantee we don't modify
1398 * state later when VM is not running.
1400 qemu_flush_or_purge_queued_packets(nc, true);
1405 void net_cleanup(void)
1407 NetClientState *nc;
1409 /* We may del multiple entries during qemu_del_net_client(),
1410 * so QTAILQ_FOREACH_SAFE() is also not safe here.
1412 while (!QTAILQ_EMPTY(&net_clients)) {
1413 nc = QTAILQ_FIRST(&net_clients);
1414 if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
1415 qemu_del_nic(qemu_get_nic(nc));
1416 } else {
1417 qemu_del_net_client(nc);
1421 qemu_del_vm_change_state_handler(net_change_state_entry);
1424 void net_check_clients(void)
1426 NetClientState *nc;
1427 int i;
1429 net_hub_check_clients();
1431 QTAILQ_FOREACH(nc, &net_clients, next) {
1432 if (!nc->peer) {
1433 warn_report("%s %s has no peer",
1434 nc->info->type == NET_CLIENT_DRIVER_NIC
1435 ? "nic" : "netdev",
1436 nc->name);
1440 /* Check that all NICs requested via -net nic actually got created.
1441 * NICs created via -device don't need to be checked here because
1442 * they are always instantiated.
1444 for (i = 0; i < MAX_NICS; i++) {
1445 NICInfo *nd = &nd_table[i];
1446 if (nd->used && !nd->instantiated) {
1447 warn_report("requested NIC (%s, model %s) "
1448 "was not created (not supported by this machine?)",
1449 nd->name ? nd->name : "anonymous",
1450 nd->model ? nd->model : "unspecified");
1455 static int net_init_client(void *dummy, QemuOpts *opts, Error **errp)
1457 return net_client_init(opts, false, errp);
1460 static int net_init_netdev(void *dummy, QemuOpts *opts, Error **errp)
1462 return net_client_init(opts, true, errp);
1465 /* For the convenience "--nic" parameter */
1466 static int net_param_nic(void *dummy, QemuOpts *opts, Error **errp)
1468 char *mac, *nd_id;
1469 int idx, ret;
1470 NICInfo *ni;
1471 const char *type;
1473 type = qemu_opt_get(opts, "type");
1474 if (type && g_str_equal(type, "none")) {
1475 return 0; /* Nothing to do, default_net is cleared in vl.c */
1478 idx = nic_get_free_idx();
1479 if (idx == -1 || nb_nics >= MAX_NICS) {
1480 error_setg(errp, "no more on-board/default NIC slots available");
1481 return -1;
1484 if (!type) {
1485 qemu_opt_set(opts, "type", "user", &error_abort);
1488 ni = &nd_table[idx];
1489 memset(ni, 0, sizeof(*ni));
1490 ni->model = qemu_opt_get_del(opts, "model");
1492 /* Create an ID if the user did not specify one */
1493 nd_id = g_strdup(qemu_opts_id(opts));
1494 if (!nd_id) {
1495 nd_id = g_strdup_printf("__org.qemu.nic%i\n", idx);
1496 qemu_opts_set_id(opts, nd_id);
1499 /* Handle MAC address */
1500 mac = qemu_opt_get_del(opts, "mac");
1501 if (mac) {
1502 ret = net_parse_macaddr(ni->macaddr.a, mac);
1503 g_free(mac);
1504 if (ret) {
1505 error_setg(errp, "invalid syntax for ethernet address");
1506 return -1;
1508 if (is_multicast_ether_addr(ni->macaddr.a)) {
1509 error_setg(errp, "NIC cannot have multicast MAC address");
1510 return -1;
1513 qemu_macaddr_default_if_unset(&ni->macaddr);
1515 ret = net_client_init(opts, true, errp);
1516 if (ret == 0) {
1517 ni->netdev = qemu_find_netdev(nd_id);
1518 ni->used = true;
1519 nb_nics++;
1522 g_free(nd_id);
1523 return ret;
1526 int net_init_clients(Error **errp)
1528 net_change_state_entry =
1529 qemu_add_vm_change_state_handler(net_vm_change_state_handler, NULL);
1531 QTAILQ_INIT(&net_clients);
1533 if (qemu_opts_foreach(qemu_find_opts("netdev"),
1534 net_init_netdev, NULL, errp)) {
1535 return -1;
1538 if (qemu_opts_foreach(qemu_find_opts("nic"), net_param_nic, NULL, errp)) {
1539 return -1;
1542 if (qemu_opts_foreach(qemu_find_opts("net"), net_init_client, NULL, errp)) {
1543 return -1;
1546 return 0;
1549 int net_client_parse(QemuOptsList *opts_list, const char *optarg)
1551 if (!qemu_opts_parse_noisily(opts_list, optarg, true)) {
1552 return -1;
1555 return 0;
1558 /* From FreeBSD */
1559 /* XXX: optimize */
1560 uint32_t net_crc32(const uint8_t *p, int len)
1562 uint32_t crc;
1563 int carry, i, j;
1564 uint8_t b;
1566 crc = 0xffffffff;
1567 for (i = 0; i < len; i++) {
1568 b = *p++;
1569 for (j = 0; j < 8; j++) {
1570 carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
1571 crc <<= 1;
1572 b >>= 1;
1573 if (carry) {
1574 crc = ((crc ^ POLYNOMIAL_BE) | carry);
1579 return crc;
1582 uint32_t net_crc32_le(const uint8_t *p, int len)
1584 uint32_t crc;
1585 int carry, i, j;
1586 uint8_t b;
1588 crc = 0xffffffff;
1589 for (i = 0; i < len; i++) {
1590 b = *p++;
1591 for (j = 0; j < 8; j++) {
1592 carry = (crc & 0x1) ^ (b & 0x01);
1593 crc >>= 1;
1594 b >>= 1;
1595 if (carry) {
1596 crc ^= POLYNOMIAL_LE;
1601 return crc;
1604 QemuOptsList qemu_netdev_opts = {
1605 .name = "netdev",
1606 .implied_opt_name = "type",
1607 .head = QTAILQ_HEAD_INITIALIZER(qemu_netdev_opts.head),
1608 .desc = {
1610 * no elements => accept any params
1611 * validation will happen later
1613 { /* end of list */ }
1617 QemuOptsList qemu_nic_opts = {
1618 .name = "nic",
1619 .implied_opt_name = "type",
1620 .head = QTAILQ_HEAD_INITIALIZER(qemu_nic_opts.head),
1621 .desc = {
1623 * no elements => accept any params
1624 * validation will happen later
1626 { /* end of list */ }
1630 QemuOptsList qemu_net_opts = {
1631 .name = "net",
1632 .implied_opt_name = "type",
1633 .head = QTAILQ_HEAD_INITIALIZER(qemu_net_opts.head),
1634 .desc = {
1636 * no elements => accept any params
1637 * validation will happen later
1639 { /* end of list */ }
1643 void net_socket_rs_init(SocketReadState *rs,
1644 SocketReadStateFinalize *finalize,
1645 bool vnet_hdr)
1647 rs->state = 0;
1648 rs->vnet_hdr = vnet_hdr;
1649 rs->index = 0;
1650 rs->packet_len = 0;
1651 rs->vnet_hdr_len = 0;
1652 memset(rs->buf, 0, sizeof(rs->buf));
1653 rs->finalize = finalize;
1657 * Returns
1658 * 0: success
1659 * -1: error occurs
1661 int net_fill_rstate(SocketReadState *rs, const uint8_t *buf, int size)
1663 unsigned int l;
1665 while (size > 0) {
1666 /* Reassemble a packet from the network.
1667 * 0 = getting length.
1668 * 1 = getting vnet header length.
1669 * 2 = getting data.
1671 switch (rs->state) {
1672 case 0:
1673 l = 4 - rs->index;
1674 if (l > size) {
1675 l = size;
1677 memcpy(rs->buf + rs->index, buf, l);
1678 buf += l;
1679 size -= l;
1680 rs->index += l;
1681 if (rs->index == 4) {
1682 /* got length */
1683 rs->packet_len = ntohl(*(uint32_t *)rs->buf);
1684 rs->index = 0;
1685 if (rs->vnet_hdr) {
1686 rs->state = 1;
1687 } else {
1688 rs->state = 2;
1689 rs->vnet_hdr_len = 0;
1692 break;
1693 case 1:
1694 l = 4 - rs->index;
1695 if (l > size) {
1696 l = size;
1698 memcpy(rs->buf + rs->index, buf, l);
1699 buf += l;
1700 size -= l;
1701 rs->index += l;
1702 if (rs->index == 4) {
1703 /* got vnet header length */
1704 rs->vnet_hdr_len = ntohl(*(uint32_t *)rs->buf);
1705 rs->index = 0;
1706 rs->state = 2;
1708 break;
1709 case 2:
1710 l = rs->packet_len - rs->index;
1711 if (l > size) {
1712 l = size;
1714 if (rs->index + l <= sizeof(rs->buf)) {
1715 memcpy(rs->buf + rs->index, buf, l);
1716 } else {
1717 fprintf(stderr, "serious error: oversized packet received,"
1718 "connection terminated.\n");
1719 rs->index = rs->state = 0;
1720 return -1;
1723 rs->index += l;
1724 buf += l;
1725 size -= l;
1726 if (rs->index >= rs->packet_len) {
1727 rs->index = 0;
1728 rs->state = 0;
1729 assert(rs->finalize);
1730 rs->finalize(rs);
1732 break;
1736 assert(size == 0);
1737 return 0;