xref: /qemu/net/net.c (revision 76240dd2)
1 /*
2  * QEMU System Emulator
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #include "qemu/osdep.h"
26 
27 #include "net/net.h"
28 #include "clients.h"
29 #include "hub.h"
30 #include "hw/qdev-properties.h"
31 #include "net/slirp.h"
32 #include "net/eth.h"
33 #include "util.h"
34 
35 #include "monitor/monitor.h"
36 #include "qemu/help_option.h"
37 #include "qapi/qapi-commands-net.h"
38 #include "qapi/qapi-visit-net.h"
39 #include "qapi/qmp/qdict.h"
40 #include "qapi/qmp/qerror.h"
41 #include "qemu/error-report.h"
42 #include "qemu/sockets.h"
43 #include "qemu/cutils.h"
44 #include "qemu/config-file.h"
45 #include "qemu/ctype.h"
46 #include "qemu/id.h"
47 #include "qemu/iov.h"
48 #include "qemu/qemu-print.h"
49 #include "qemu/main-loop.h"
50 #include "qemu/option.h"
51 #include "qemu/keyval.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"
58 #include "qapi/qobject-input-visitor.h"
59 #include "standard-headers/linux/virtio_net.h"
60 
61 /* Net bridge is currently not supported for W32. */
62 #if !defined(_WIN32)
63 # define CONFIG_NET_BRIDGE
64 #endif
65 
66 static VMChangeStateEntry *net_change_state_entry;
67 NetClientStateList net_clients;
68 
69 typedef struct NetdevQueueEntry {
70     Netdev *nd;
71     Location loc;
72     QSIMPLEQ_ENTRY(NetdevQueueEntry) entry;
73 } NetdevQueueEntry;
74 
75 typedef QSIMPLEQ_HEAD(, NetdevQueueEntry) NetdevQueue;
76 
77 static NetdevQueue nd_queue = QSIMPLEQ_HEAD_INITIALIZER(nd_queue);
78 
79 static GHashTable *nic_model_help;
80 
81 static int nb_nics;
82 static NICInfo nd_table[MAX_NICS];
83 
84 /***********************************************************/
85 /* network device redirectors */
86 
convert_host_port(struct sockaddr_in * saddr,const char * host,const char * port,Error ** errp)87 int convert_host_port(struct sockaddr_in *saddr, const char *host,
88                       const char *port, Error **errp)
89 {
90     struct hostent *he;
91     const char *r;
92     long p;
93 
94     memset(saddr, 0, sizeof(*saddr));
95 
96     saddr->sin_family = AF_INET;
97     if (host[0] == '\0') {
98         saddr->sin_addr.s_addr = 0;
99     } else {
100         if (qemu_isdigit(host[0])) {
101             if (!inet_aton(host, &saddr->sin_addr)) {
102                 error_setg(errp, "host address '%s' is not a valid "
103                            "IPv4 address", host);
104                 return -1;
105             }
106         } else {
107             he = gethostbyname(host);
108             if (he == NULL) {
109                 error_setg(errp, "can't resolve host address '%s'", host);
110                 return -1;
111             }
112             saddr->sin_addr = *(struct in_addr *)he->h_addr;
113         }
114     }
115     if (qemu_strtol(port, &r, 0, &p) != 0) {
116         error_setg(errp, "port number '%s' is invalid", port);
117         return -1;
118     }
119     saddr->sin_port = htons(p);
120     return 0;
121 }
122 
parse_host_port(struct sockaddr_in * saddr,const char * str,Error ** errp)123 int parse_host_port(struct sockaddr_in *saddr, const char *str,
124                     Error **errp)
125 {
126     gchar **substrings;
127     int ret;
128 
129     substrings = g_strsplit(str, ":", 2);
130     if (!substrings || !substrings[0] || !substrings[1]) {
131         error_setg(errp, "host address '%s' doesn't contain ':' "
132                    "separating host from port", str);
133         ret = -1;
134         goto out;
135     }
136 
137     ret = convert_host_port(saddr, substrings[0], substrings[1], errp);
138 
139 out:
140     g_strfreev(substrings);
141     return ret;
142 }
143 
qemu_mac_strdup_printf(const uint8_t * macaddr)144 char *qemu_mac_strdup_printf(const uint8_t *macaddr)
145 {
146     return g_strdup_printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
147                            macaddr[0], macaddr[1], macaddr[2],
148                            macaddr[3], macaddr[4], macaddr[5]);
149 }
150 
qemu_set_info_str(NetClientState * nc,const char * fmt,...)151 void qemu_set_info_str(NetClientState *nc, const char *fmt, ...)
152 {
153     va_list ap;
154 
155     va_start(ap, fmt);
156     vsnprintf(nc->info_str, sizeof(nc->info_str), fmt, ap);
157     va_end(ap);
158 }
159 
qemu_format_nic_info_str(NetClientState * nc,uint8_t macaddr[6])160 void qemu_format_nic_info_str(NetClientState *nc, uint8_t macaddr[6])
161 {
162     qemu_set_info_str(nc, "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
163                       nc->model, macaddr[0], macaddr[1], macaddr[2],
164                       macaddr[3], macaddr[4], macaddr[5]);
165 }
166 
167 static int mac_table[256] = {0};
168 
qemu_macaddr_set_used(MACAddr * macaddr)169 static void qemu_macaddr_set_used(MACAddr *macaddr)
170 {
171     int index;
172 
173     for (index = 0x56; index < 0xFF; index++) {
174         if (macaddr->a[5] == index) {
175             mac_table[index]++;
176         }
177     }
178 }
179 
qemu_macaddr_set_free(MACAddr * macaddr)180 static void qemu_macaddr_set_free(MACAddr *macaddr)
181 {
182     int index;
183     static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
184 
185     if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
186         return;
187     }
188     for (index = 0x56; index < 0xFF; index++) {
189         if (macaddr->a[5] == index) {
190             mac_table[index]--;
191         }
192     }
193 }
194 
qemu_macaddr_get_free(void)195 static int qemu_macaddr_get_free(void)
196 {
197     int index;
198 
199     for (index = 0x56; index < 0xFF; index++) {
200         if (mac_table[index] == 0) {
201             return index;
202         }
203     }
204 
205     return -1;
206 }
207 
qemu_macaddr_default_if_unset(MACAddr * macaddr)208 void qemu_macaddr_default_if_unset(MACAddr *macaddr)
209 {
210     static const MACAddr zero = { .a = { 0,0,0,0,0,0 } };
211     static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
212 
213     if (memcmp(macaddr, &zero, sizeof(zero)) != 0) {
214         if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
215             return;
216         } else {
217             qemu_macaddr_set_used(macaddr);
218             return;
219         }
220     }
221 
222     macaddr->a[0] = 0x52;
223     macaddr->a[1] = 0x54;
224     macaddr->a[2] = 0x00;
225     macaddr->a[3] = 0x12;
226     macaddr->a[4] = 0x34;
227     macaddr->a[5] = qemu_macaddr_get_free();
228     qemu_macaddr_set_used(macaddr);
229 }
230 
231 /**
232  * Generate a name for net client
233  *
234  * Only net clients created with the legacy -net option and NICs need this.
235  */
assign_name(NetClientState * nc1,const char * model)236 static char *assign_name(NetClientState *nc1, const char *model)
237 {
238     NetClientState *nc;
239     int id = 0;
240 
241     QTAILQ_FOREACH(nc, &net_clients, next) {
242         if (nc == nc1) {
243             continue;
244         }
245         if (strcmp(nc->model, model) == 0) {
246             id++;
247         }
248     }
249 
250     return g_strdup_printf("%s.%d", model, id);
251 }
252 
qemu_net_client_destructor(NetClientState * nc)253 static void qemu_net_client_destructor(NetClientState *nc)
254 {
255     g_free(nc);
256 }
257 static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
258                                        unsigned flags,
259                                        const struct iovec *iov,
260                                        int iovcnt,
261                                        void *opaque);
262 
qemu_net_client_setup(NetClientState * nc,NetClientInfo * info,NetClientState * peer,const char * model,const char * name,NetClientDestructor * destructor,bool is_datapath)263 static void qemu_net_client_setup(NetClientState *nc,
264                                   NetClientInfo *info,
265                                   NetClientState *peer,
266                                   const char *model,
267                                   const char *name,
268                                   NetClientDestructor *destructor,
269                                   bool is_datapath)
270 {
271     nc->info = info;
272     nc->model = g_strdup(model);
273     if (name) {
274         nc->name = g_strdup(name);
275     } else {
276         nc->name = assign_name(nc, model);
277     }
278 
279     if (peer) {
280         assert(!peer->peer);
281         nc->peer = peer;
282         peer->peer = nc;
283     }
284     QTAILQ_INSERT_TAIL(&net_clients, nc, next);
285 
286     nc->incoming_queue = qemu_new_net_queue(qemu_deliver_packet_iov, nc);
287     nc->destructor = destructor;
288     nc->is_datapath = is_datapath;
289     QTAILQ_INIT(&nc->filters);
290 }
291 
qemu_new_net_client(NetClientInfo * info,NetClientState * peer,const char * model,const char * name)292 NetClientState *qemu_new_net_client(NetClientInfo *info,
293                                     NetClientState *peer,
294                                     const char *model,
295                                     const char *name)
296 {
297     NetClientState *nc;
298 
299     assert(info->size >= sizeof(NetClientState));
300 
301     nc = g_malloc0(info->size);
302     qemu_net_client_setup(nc, info, peer, model, name,
303                           qemu_net_client_destructor, true);
304 
305     return nc;
306 }
307 
qemu_new_net_control_client(NetClientInfo * info,NetClientState * peer,const char * model,const char * name)308 NetClientState *qemu_new_net_control_client(NetClientInfo *info,
309                                             NetClientState *peer,
310                                             const char *model,
311                                             const char *name)
312 {
313     NetClientState *nc;
314 
315     assert(info->size >= sizeof(NetClientState));
316 
317     nc = g_malloc0(info->size);
318     qemu_net_client_setup(nc, info, peer, model, name,
319                           qemu_net_client_destructor, false);
320 
321     return nc;
322 }
323 
qemu_new_nic(NetClientInfo * info,NICConf * conf,const char * model,const char * name,MemReentrancyGuard * reentrancy_guard,void * opaque)324 NICState *qemu_new_nic(NetClientInfo *info,
325                        NICConf *conf,
326                        const char *model,
327                        const char *name,
328                        MemReentrancyGuard *reentrancy_guard,
329                        void *opaque)
330 {
331     NetClientState **peers = conf->peers.ncs;
332     NICState *nic;
333     int i, queues = MAX(1, conf->peers.queues);
334 
335     assert(info->type == NET_CLIENT_DRIVER_NIC);
336     assert(info->size >= sizeof(NICState));
337 
338     nic = g_malloc0(info->size + sizeof(NetClientState) * queues);
339     nic->ncs = (void *)nic + info->size;
340     nic->conf = conf;
341     nic->reentrancy_guard = reentrancy_guard,
342     nic->opaque = opaque;
343 
344     for (i = 0; i < queues; i++) {
345         qemu_net_client_setup(&nic->ncs[i], info, peers[i], model, name,
346                               NULL, true);
347         nic->ncs[i].queue_index = i;
348     }
349 
350     return nic;
351 }
352 
qemu_get_subqueue(NICState * nic,int queue_index)353 NetClientState *qemu_get_subqueue(NICState *nic, int queue_index)
354 {
355     return nic->ncs + queue_index;
356 }
357 
qemu_get_queue(NICState * nic)358 NetClientState *qemu_get_queue(NICState *nic)
359 {
360     return qemu_get_subqueue(nic, 0);
361 }
362 
qemu_get_nic(NetClientState * nc)363 NICState *qemu_get_nic(NetClientState *nc)
364 {
365     NetClientState *nc0 = nc - nc->queue_index;
366 
367     return (NICState *)((void *)nc0 - nc->info->size);
368 }
369 
qemu_get_nic_opaque(NetClientState * nc)370 void *qemu_get_nic_opaque(NetClientState *nc)
371 {
372     NICState *nic = qemu_get_nic(nc);
373 
374     return nic->opaque;
375 }
376 
qemu_get_peer(NetClientState * nc,int queue_index)377 NetClientState *qemu_get_peer(NetClientState *nc, int queue_index)
378 {
379     assert(nc != NULL);
380     NetClientState *ncs = nc + queue_index;
381     return ncs->peer;
382 }
383 
qemu_cleanup_net_client(NetClientState * nc)384 static void qemu_cleanup_net_client(NetClientState *nc)
385 {
386     QTAILQ_REMOVE(&net_clients, nc, next);
387 
388     if (nc->info->cleanup) {
389         nc->info->cleanup(nc);
390     }
391 }
392 
qemu_free_net_client(NetClientState * nc)393 static void qemu_free_net_client(NetClientState *nc)
394 {
395     if (nc->incoming_queue) {
396         qemu_del_net_queue(nc->incoming_queue);
397     }
398     if (nc->peer) {
399         nc->peer->peer = NULL;
400     }
401     g_free(nc->name);
402     g_free(nc->model);
403     if (nc->destructor) {
404         nc->destructor(nc);
405     }
406 }
407 
qemu_del_net_client(NetClientState * nc)408 void qemu_del_net_client(NetClientState *nc)
409 {
410     NetClientState *ncs[MAX_QUEUE_NUM];
411     int queues, i;
412     NetFilterState *nf, *next;
413 
414     assert(nc->info->type != NET_CLIENT_DRIVER_NIC);
415 
416     /* If the NetClientState belongs to a multiqueue backend, we will change all
417      * other NetClientStates also.
418      */
419     queues = qemu_find_net_clients_except(nc->name, ncs,
420                                           NET_CLIENT_DRIVER_NIC,
421                                           MAX_QUEUE_NUM);
422     assert(queues != 0);
423 
424     QTAILQ_FOREACH_SAFE(nf, &nc->filters, next, next) {
425         object_unparent(OBJECT(nf));
426     }
427 
428     /* If there is a peer NIC, delete and cleanup client, but do not free. */
429     if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
430         NICState *nic = qemu_get_nic(nc->peer);
431         if (nic->peer_deleted) {
432             return;
433         }
434         nic->peer_deleted = true;
435 
436         for (i = 0; i < queues; i++) {
437             ncs[i]->peer->link_down = true;
438         }
439 
440         if (nc->peer->info->link_status_changed) {
441             nc->peer->info->link_status_changed(nc->peer);
442         }
443 
444         for (i = 0; i < queues; i++) {
445             qemu_cleanup_net_client(ncs[i]);
446         }
447 
448         return;
449     }
450 
451     for (i = 0; i < queues; i++) {
452         qemu_cleanup_net_client(ncs[i]);
453         qemu_free_net_client(ncs[i]);
454     }
455 }
456 
qemu_del_nic(NICState * nic)457 void qemu_del_nic(NICState *nic)
458 {
459     int i, queues = MAX(nic->conf->peers.queues, 1);
460 
461     qemu_macaddr_set_free(&nic->conf->macaddr);
462 
463     for (i = 0; i < queues; i++) {
464         NetClientState *nc = qemu_get_subqueue(nic, i);
465         /* If this is a peer NIC and peer has already been deleted, free it now. */
466         if (nic->peer_deleted) {
467             qemu_free_net_client(nc->peer);
468         } else if (nc->peer) {
469             /* if there are RX packets pending, complete them */
470             qemu_purge_queued_packets(nc->peer);
471         }
472     }
473 
474     for (i = queues - 1; i >= 0; i--) {
475         NetClientState *nc = qemu_get_subqueue(nic, i);
476 
477         qemu_cleanup_net_client(nc);
478         qemu_free_net_client(nc);
479     }
480 
481     g_free(nic);
482 }
483 
qemu_foreach_nic(qemu_nic_foreach func,void * opaque)484 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
485 {
486     NetClientState *nc;
487 
488     QTAILQ_FOREACH(nc, &net_clients, next) {
489         if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
490             if (nc->queue_index == 0) {
491                 func(qemu_get_nic(nc), opaque);
492             }
493         }
494     }
495 }
496 
qemu_has_ufo(NetClientState * nc)497 bool qemu_has_ufo(NetClientState *nc)
498 {
499     if (!nc || !nc->info->has_ufo) {
500         return false;
501     }
502 
503     return nc->info->has_ufo(nc);
504 }
505 
qemu_has_uso(NetClientState * nc)506 bool qemu_has_uso(NetClientState *nc)
507 {
508     if (!nc || !nc->info->has_uso) {
509         return false;
510     }
511 
512     return nc->info->has_uso(nc);
513 }
514 
qemu_has_vnet_hdr(NetClientState * nc)515 bool qemu_has_vnet_hdr(NetClientState *nc)
516 {
517     if (!nc || !nc->info->has_vnet_hdr) {
518         return false;
519     }
520 
521     return nc->info->has_vnet_hdr(nc);
522 }
523 
qemu_has_vnet_hdr_len(NetClientState * nc,int len)524 bool qemu_has_vnet_hdr_len(NetClientState *nc, int len)
525 {
526     if (!nc || !nc->info->has_vnet_hdr_len) {
527         return false;
528     }
529 
530     return nc->info->has_vnet_hdr_len(nc, len);
531 }
532 
qemu_set_offload(NetClientState * nc,int csum,int tso4,int tso6,int ecn,int ufo,int uso4,int uso6)533 void qemu_set_offload(NetClientState *nc, int csum, int tso4, int tso6,
534                           int ecn, int ufo, int uso4, int uso6)
535 {
536     if (!nc || !nc->info->set_offload) {
537         return;
538     }
539 
540     nc->info->set_offload(nc, csum, tso4, tso6, ecn, ufo, uso4, uso6);
541 }
542 
qemu_get_vnet_hdr_len(NetClientState * nc)543 int qemu_get_vnet_hdr_len(NetClientState *nc)
544 {
545     if (!nc) {
546         return 0;
547     }
548 
549     return nc->vnet_hdr_len;
550 }
551 
qemu_set_vnet_hdr_len(NetClientState * nc,int len)552 void qemu_set_vnet_hdr_len(NetClientState *nc, int len)
553 {
554     if (!nc || !nc->info->set_vnet_hdr_len) {
555         return;
556     }
557 
558     assert(len == sizeof(struct virtio_net_hdr_mrg_rxbuf) ||
559            len == sizeof(struct virtio_net_hdr) ||
560            len == sizeof(struct virtio_net_hdr_v1_hash));
561 
562     nc->vnet_hdr_len = len;
563     nc->info->set_vnet_hdr_len(nc, len);
564 }
565 
qemu_set_vnet_le(NetClientState * nc,bool is_le)566 int qemu_set_vnet_le(NetClientState *nc, bool is_le)
567 {
568 #if HOST_BIG_ENDIAN
569     if (!nc || !nc->info->set_vnet_le) {
570         return -ENOSYS;
571     }
572 
573     return nc->info->set_vnet_le(nc, is_le);
574 #else
575     return 0;
576 #endif
577 }
578 
qemu_set_vnet_be(NetClientState * nc,bool is_be)579 int qemu_set_vnet_be(NetClientState *nc, bool is_be)
580 {
581 #if HOST_BIG_ENDIAN
582     return 0;
583 #else
584     if (!nc || !nc->info->set_vnet_be) {
585         return -ENOSYS;
586     }
587 
588     return nc->info->set_vnet_be(nc, is_be);
589 #endif
590 }
591 
qemu_can_receive_packet(NetClientState * nc)592 int qemu_can_receive_packet(NetClientState *nc)
593 {
594     if (nc->receive_disabled) {
595         return 0;
596     } else if (nc->info->can_receive &&
597                !nc->info->can_receive(nc)) {
598         return 0;
599     }
600     return 1;
601 }
602 
qemu_can_send_packet(NetClientState * sender)603 int qemu_can_send_packet(NetClientState *sender)
604 {
605     int vm_running = runstate_is_running();
606 
607     if (!vm_running) {
608         return 0;
609     }
610 
611     if (!sender->peer) {
612         return 1;
613     }
614 
615     return qemu_can_receive_packet(sender->peer);
616 }
617 
filter_receive_iov(NetClientState * nc,NetFilterDirection direction,NetClientState * sender,unsigned flags,const struct iovec * iov,int iovcnt,NetPacketSent * sent_cb)618 static ssize_t filter_receive_iov(NetClientState *nc,
619                                   NetFilterDirection direction,
620                                   NetClientState *sender,
621                                   unsigned flags,
622                                   const struct iovec *iov,
623                                   int iovcnt,
624                                   NetPacketSent *sent_cb)
625 {
626     ssize_t ret = 0;
627     NetFilterState *nf = NULL;
628 
629     if (direction == NET_FILTER_DIRECTION_TX) {
630         QTAILQ_FOREACH(nf, &nc->filters, next) {
631             ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
632                                          iovcnt, sent_cb);
633             if (ret) {
634                 return ret;
635             }
636         }
637     } else {
638         QTAILQ_FOREACH_REVERSE(nf, &nc->filters, next) {
639             ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
640                                          iovcnt, sent_cb);
641             if (ret) {
642                 return ret;
643             }
644         }
645     }
646 
647     return ret;
648 }
649 
filter_receive(NetClientState * nc,NetFilterDirection direction,NetClientState * sender,unsigned flags,const uint8_t * data,size_t size,NetPacketSent * sent_cb)650 static ssize_t filter_receive(NetClientState *nc,
651                               NetFilterDirection direction,
652                               NetClientState *sender,
653                               unsigned flags,
654                               const uint8_t *data,
655                               size_t size,
656                               NetPacketSent *sent_cb)
657 {
658     struct iovec iov = {
659         .iov_base = (void *)data,
660         .iov_len = size
661     };
662 
663     return filter_receive_iov(nc, direction, sender, flags, &iov, 1, sent_cb);
664 }
665 
qemu_purge_queued_packets(NetClientState * nc)666 void qemu_purge_queued_packets(NetClientState *nc)
667 {
668     if (!nc->peer) {
669         return;
670     }
671 
672     qemu_net_queue_purge(nc->peer->incoming_queue, nc);
673 }
674 
qemu_flush_or_purge_queued_packets(NetClientState * nc,bool purge)675 void qemu_flush_or_purge_queued_packets(NetClientState *nc, bool purge)
676 {
677     nc->receive_disabled = 0;
678 
679     if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_HUBPORT) {
680         if (net_hub_flush(nc->peer)) {
681             qemu_notify_event();
682         }
683     }
684     if (qemu_net_queue_flush(nc->incoming_queue)) {
685         /* We emptied the queue successfully, signal to the IO thread to repoll
686          * the file descriptor (for tap, for example).
687          */
688         qemu_notify_event();
689     } else if (purge) {
690         /* Unable to empty the queue, purge remaining packets */
691         qemu_net_queue_purge(nc->incoming_queue, nc->peer);
692     }
693 }
694 
qemu_flush_queued_packets(NetClientState * nc)695 void qemu_flush_queued_packets(NetClientState *nc)
696 {
697     qemu_flush_or_purge_queued_packets(nc, false);
698 }
699 
qemu_send_packet_async_with_flags(NetClientState * sender,unsigned flags,const uint8_t * buf,int size,NetPacketSent * sent_cb)700 static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
701                                                  unsigned flags,
702                                                  const uint8_t *buf, int size,
703                                                  NetPacketSent *sent_cb)
704 {
705     NetQueue *queue;
706     int ret;
707 
708 #ifdef DEBUG_NET
709     printf("qemu_send_packet_async:\n");
710     qemu_hexdump(stdout, "net", buf, size);
711 #endif
712 
713     if (sender->link_down || !sender->peer) {
714         return size;
715     }
716 
717     /* Let filters handle the packet first */
718     ret = filter_receive(sender, NET_FILTER_DIRECTION_TX,
719                          sender, flags, buf, size, sent_cb);
720     if (ret) {
721         return ret;
722     }
723 
724     ret = filter_receive(sender->peer, NET_FILTER_DIRECTION_RX,
725                          sender, flags, buf, size, sent_cb);
726     if (ret) {
727         return ret;
728     }
729 
730     queue = sender->peer->incoming_queue;
731 
732     return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
733 }
734 
qemu_send_packet_async(NetClientState * sender,const uint8_t * buf,int size,NetPacketSent * sent_cb)735 ssize_t qemu_send_packet_async(NetClientState *sender,
736                                const uint8_t *buf, int size,
737                                NetPacketSent *sent_cb)
738 {
739     return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
740                                              buf, size, sent_cb);
741 }
742 
qemu_send_packet(NetClientState * nc,const uint8_t * buf,int size)743 ssize_t qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size)
744 {
745     return qemu_send_packet_async(nc, buf, size, NULL);
746 }
747 
qemu_receive_packet(NetClientState * nc,const uint8_t * buf,int size)748 ssize_t qemu_receive_packet(NetClientState *nc, const uint8_t *buf, int size)
749 {
750     if (!qemu_can_receive_packet(nc)) {
751         return 0;
752     }
753 
754     return qemu_net_queue_receive(nc->incoming_queue, buf, size);
755 }
756 
qemu_send_packet_raw(NetClientState * nc,const uint8_t * buf,int size)757 ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size)
758 {
759     return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW,
760                                              buf, size, NULL);
761 }
762 
nc_sendv_compat(NetClientState * nc,const struct iovec * iov,int iovcnt,unsigned flags)763 static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
764                                int iovcnt, unsigned flags)
765 {
766     uint8_t *buf = NULL;
767     uint8_t *buffer;
768     size_t offset;
769     ssize_t ret;
770 
771     if (iovcnt == 1) {
772         buffer = iov[0].iov_base;
773         offset = iov[0].iov_len;
774     } else {
775         offset = iov_size(iov, iovcnt);
776         if (offset > NET_BUFSIZE) {
777             return -1;
778         }
779         buf = g_malloc(offset);
780         buffer = buf;
781         offset = iov_to_buf(iov, iovcnt, 0, buf, offset);
782     }
783 
784     ret = nc->info->receive(nc, buffer, offset);
785 
786     g_free(buf);
787     return ret;
788 }
789 
qemu_deliver_packet_iov(NetClientState * sender,unsigned flags,const struct iovec * iov,int iovcnt,void * opaque)790 static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
791                                        unsigned flags,
792                                        const struct iovec *iov,
793                                        int iovcnt,
794                                        void *opaque)
795 {
796     MemReentrancyGuard *owned_reentrancy_guard;
797     NetClientState *nc = opaque;
798     int ret;
799     struct virtio_net_hdr_v1_hash vnet_hdr = { };
800     g_autofree struct iovec *iov_copy = NULL;
801 
802 
803     if (nc->link_down) {
804         return iov_size(iov, iovcnt);
805     }
806 
807     if (nc->receive_disabled) {
808         return 0;
809     }
810 
811     if (nc->info->type != NET_CLIENT_DRIVER_NIC ||
812         qemu_get_nic(nc)->reentrancy_guard->engaged_in_io) {
813         owned_reentrancy_guard = NULL;
814     } else {
815         owned_reentrancy_guard = qemu_get_nic(nc)->reentrancy_guard;
816         owned_reentrancy_guard->engaged_in_io = true;
817     }
818 
819     if ((flags & QEMU_NET_PACKET_FLAG_RAW) && nc->vnet_hdr_len) {
820         iov_copy = g_new(struct iovec, iovcnt + 1);
821         iov_copy[0].iov_base = &vnet_hdr;
822         iov_copy[0].iov_len =  nc->vnet_hdr_len;
823         memcpy(&iov_copy[1], iov, iovcnt * sizeof(*iov));
824         iov = iov_copy;
825     }
826 
827     if (nc->info->receive_iov) {
828         ret = nc->info->receive_iov(nc, iov, iovcnt);
829     } else {
830         ret = nc_sendv_compat(nc, iov, iovcnt, flags);
831     }
832 
833     if (owned_reentrancy_guard) {
834         owned_reentrancy_guard->engaged_in_io = false;
835     }
836 
837     if (ret == 0) {
838         nc->receive_disabled = 1;
839     }
840 
841     return ret;
842 }
843 
qemu_sendv_packet_async(NetClientState * sender,const struct iovec * iov,int iovcnt,NetPacketSent * sent_cb)844 ssize_t qemu_sendv_packet_async(NetClientState *sender,
845                                 const struct iovec *iov, int iovcnt,
846                                 NetPacketSent *sent_cb)
847 {
848     NetQueue *queue;
849     size_t size = iov_size(iov, iovcnt);
850     int ret;
851 
852     if (size > NET_BUFSIZE) {
853         return size;
854     }
855 
856     if (sender->link_down || !sender->peer) {
857         return size;
858     }
859 
860     /* Let filters handle the packet first */
861     ret = filter_receive_iov(sender, NET_FILTER_DIRECTION_TX, sender,
862                              QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
863     if (ret) {
864         return ret;
865     }
866 
867     ret = filter_receive_iov(sender->peer, NET_FILTER_DIRECTION_RX, sender,
868                              QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
869     if (ret) {
870         return ret;
871     }
872 
873     queue = sender->peer->incoming_queue;
874 
875     return qemu_net_queue_send_iov(queue, sender,
876                                    QEMU_NET_PACKET_FLAG_NONE,
877                                    iov, iovcnt, sent_cb);
878 }
879 
880 ssize_t
qemu_sendv_packet(NetClientState * nc,const struct iovec * iov,int iovcnt)881 qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt)
882 {
883     return qemu_sendv_packet_async(nc, iov, iovcnt, NULL);
884 }
885 
qemu_find_netdev(const char * id)886 NetClientState *qemu_find_netdev(const char *id)
887 {
888     NetClientState *nc;
889 
890     QTAILQ_FOREACH(nc, &net_clients, next) {
891         if (nc->info->type == NET_CLIENT_DRIVER_NIC)
892             continue;
893         if (!strcmp(nc->name, id)) {
894             return nc;
895         }
896     }
897 
898     return NULL;
899 }
900 
qemu_find_net_clients_except(const char * id,NetClientState ** ncs,NetClientDriver type,int max)901 int qemu_find_net_clients_except(const char *id, NetClientState **ncs,
902                                  NetClientDriver type, int max)
903 {
904     NetClientState *nc;
905     int ret = 0;
906 
907     QTAILQ_FOREACH(nc, &net_clients, next) {
908         if (nc->info->type == type) {
909             continue;
910         }
911         if (!id || !strcmp(nc->name, id)) {
912             if (ret < max) {
913                 ncs[ret] = nc;
914             }
915             ret++;
916         }
917     }
918 
919     return ret;
920 }
921 
nic_get_free_idx(void)922 static int nic_get_free_idx(void)
923 {
924     int index;
925 
926     for (index = 0; index < MAX_NICS; index++)
927         if (!nd_table[index].used)
928             return index;
929     return -1;
930 }
931 
qemu_get_nic_models(const char * device_type)932 GPtrArray *qemu_get_nic_models(const char *device_type)
933 {
934     GPtrArray *nic_models = g_ptr_array_new();
935     GSList *list = object_class_get_list_sorted(device_type, false);
936 
937     while (list) {
938         DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, list->data,
939                                              TYPE_DEVICE);
940         GSList *next;
941         if (test_bit(DEVICE_CATEGORY_NETWORK, dc->categories) &&
942             dc->user_creatable) {
943             const char *name = object_class_get_name(list->data);
944             /*
945              * A network device might also be something else than a NIC, see
946              * e.g. the "rocker" device. Thus we have to look for the "netdev"
947              * property, too. Unfortunately, some devices like virtio-net only
948              * create this property during instance_init, so we have to create
949              * a temporary instance here to be able to check it.
950              */
951             Object *obj = object_new_with_class(OBJECT_CLASS(dc));
952             if (object_property_find(obj, "netdev")) {
953                 g_ptr_array_add(nic_models, (gpointer)name);
954             }
955             object_unref(obj);
956         }
957         next = list->next;
958         g_slist_free_1(list);
959         list = next;
960     }
961     g_ptr_array_add(nic_models, NULL);
962 
963     return nic_models;
964 }
965 
net_init_nic(const Netdev * netdev,const char * name,NetClientState * peer,Error ** errp)966 static int net_init_nic(const Netdev *netdev, const char *name,
967                         NetClientState *peer, Error **errp)
968 {
969     int idx;
970     NICInfo *nd;
971     const NetLegacyNicOptions *nic;
972 
973     assert(netdev->type == NET_CLIENT_DRIVER_NIC);
974     nic = &netdev->u.nic;
975 
976     idx = nic_get_free_idx();
977     if (idx == -1 || nb_nics >= MAX_NICS) {
978         error_setg(errp, "too many NICs");
979         return -1;
980     }
981 
982     nd = &nd_table[idx];
983 
984     memset(nd, 0, sizeof(*nd));
985 
986     if (nic->netdev) {
987         nd->netdev = qemu_find_netdev(nic->netdev);
988         if (!nd->netdev) {
989             error_setg(errp, "netdev '%s' not found", nic->netdev);
990             return -1;
991         }
992     } else {
993         assert(peer);
994         nd->netdev = peer;
995     }
996     nd->name = g_strdup(name);
997     if (nic->model) {
998         nd->model = g_strdup(nic->model);
999     }
1000     if (nic->addr) {
1001         nd->devaddr = g_strdup(nic->addr);
1002     }
1003 
1004     if (nic->macaddr &&
1005         net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {
1006         error_setg(errp, "invalid syntax for ethernet address");
1007         return -1;
1008     }
1009     if (nic->macaddr &&
1010         is_multicast_ether_addr(nd->macaddr.a)) {
1011         error_setg(errp,
1012                    "NIC cannot have multicast MAC address (odd 1st byte)");
1013         return -1;
1014     }
1015     qemu_macaddr_default_if_unset(&nd->macaddr);
1016 
1017     if (nic->has_vectors) {
1018         if (nic->vectors > 0x7ffffff) {
1019             error_setg(errp, "invalid # of vectors: %"PRIu32, nic->vectors);
1020             return -1;
1021         }
1022         nd->nvectors = nic->vectors;
1023     } else {
1024         nd->nvectors = DEV_NVECTORS_UNSPECIFIED;
1025     }
1026 
1027     nd->used = 1;
1028     nb_nics++;
1029 
1030     return idx;
1031 }
1032 
add_nic_result(gpointer key,gpointer value,gpointer user_data)1033 static gboolean add_nic_result(gpointer key, gpointer value, gpointer user_data)
1034 {
1035     GPtrArray *results = user_data;
1036     GPtrArray *alias_list = value;
1037     const char *model = key;
1038     char *result;
1039 
1040     if (!alias_list) {
1041         result = g_strdup(model);
1042     } else {
1043         GString *result_str = g_string_new(model);
1044         int i;
1045 
1046         g_string_append(result_str, " (aka ");
1047         for (i = 0; i < alias_list->len; i++) {
1048             if (i) {
1049                 g_string_append(result_str, ", ");
1050             }
1051             g_string_append(result_str, alias_list->pdata[i]);
1052         }
1053         g_string_append(result_str, ")");
1054         result = result_str->str;
1055         g_string_free(result_str, false);
1056         g_ptr_array_unref(alias_list);
1057     }
1058     g_ptr_array_add(results, result);
1059     return true;
1060 }
1061 
model_cmp(char ** a,char ** b)1062 static int model_cmp(char **a, char **b)
1063 {
1064     return strcmp(*a, *b);
1065 }
1066 
show_nic_models(void)1067 static void show_nic_models(void)
1068 {
1069     GPtrArray *results = g_ptr_array_new();
1070     int i;
1071 
1072     g_hash_table_foreach_remove(nic_model_help, add_nic_result, results);
1073     g_ptr_array_sort(results, (GCompareFunc)model_cmp);
1074 
1075     printf("Available NIC models for this configuration:\n");
1076     for (i = 0 ; i < results->len; i++) {
1077         printf("%s\n", (char *)results->pdata[i]);
1078     }
1079     g_hash_table_unref(nic_model_help);
1080     nic_model_help = NULL;
1081 }
1082 
add_nic_model_help(const char * model,const char * alias)1083 static void add_nic_model_help(const char *model, const char *alias)
1084 {
1085     GPtrArray *alias_list = NULL;
1086 
1087     if (g_hash_table_lookup_extended(nic_model_help, model, NULL,
1088                                      (gpointer *)&alias_list)) {
1089         /* Already exists, no alias to add: return */
1090         if (!alias) {
1091             return;
1092         }
1093         if (alias_list) {
1094             /* Check if this alias is already in the list. Add if not. */
1095             if (!g_ptr_array_find_with_equal_func(alias_list, alias,
1096                                                   g_str_equal, NULL)) {
1097                 g_ptr_array_add(alias_list, g_strdup(alias));
1098             }
1099             return;
1100         }
1101     }
1102     /* Either this model wasn't in the list already, or a first alias added */
1103     if (alias) {
1104         alias_list = g_ptr_array_new();
1105         g_ptr_array_set_free_func(alias_list, g_free);
1106         g_ptr_array_add(alias_list, g_strdup(alias));
1107     }
1108     g_hash_table_replace(nic_model_help, g_strdup(model), alias_list);
1109 }
1110 
qemu_find_nic_info(const char * typename,bool match_default,const char * alias)1111 NICInfo *qemu_find_nic_info(const char *typename, bool match_default,
1112                             const char *alias)
1113 {
1114     NICInfo *nd;
1115     int i;
1116 
1117     if (nic_model_help) {
1118         add_nic_model_help(typename, alias);
1119     }
1120 
1121     for (i = 0; i < nb_nics; i++) {
1122         nd = &nd_table[i];
1123 
1124         if (!nd->used || nd->instantiated) {
1125             continue;
1126         }
1127 
1128         if ((match_default && !nd->model) || !g_strcmp0(nd->model, typename)
1129             || (alias && !g_strcmp0(nd->model, alias))) {
1130             return nd;
1131         }
1132     }
1133     return NULL;
1134 }
1135 
is_nic_model_help_option(const char * model)1136 static bool is_nic_model_help_option(const char *model)
1137 {
1138     if (model && is_help_option(model)) {
1139         /*
1140          * Trigger the help output by instantiating the hash table which
1141          * will gather tha available models as they get registered.
1142          */
1143         if (!nic_model_help) {
1144             nic_model_help = g_hash_table_new_full(g_str_hash, g_str_equal,
1145                                                    g_free, NULL);
1146         }
1147         return true;
1148     }
1149     return false;
1150 }
1151 
1152 /* "I have created a device. Please configure it if you can" */
qemu_configure_nic_device(DeviceState * dev,bool match_default,const char * alias)1153 bool qemu_configure_nic_device(DeviceState *dev, bool match_default,
1154                                const char *alias)
1155 {
1156     NICInfo *nd = qemu_find_nic_info(object_get_typename(OBJECT(dev)),
1157                                      match_default, alias);
1158 
1159     if (nd) {
1160         qdev_set_nic_properties(dev, nd);
1161         return true;
1162     }
1163     return false;
1164 }
1165 
1166 /* "Please create a device, if you have a configuration for it" */
qemu_create_nic_device(const char * typename,bool match_default,const char * alias)1167 DeviceState *qemu_create_nic_device(const char *typename, bool match_default,
1168                                     const char *alias)
1169 {
1170     NICInfo *nd = qemu_find_nic_info(typename, match_default, alias);
1171     DeviceState *dev;
1172 
1173     if (!nd) {
1174         return NULL;
1175     }
1176 
1177     dev = qdev_new(typename);
1178     qdev_set_nic_properties(dev, nd);
1179     return dev;
1180 }
1181 
qemu_create_nic_bus_devices(BusState * bus,const char * parent_type,const char * default_model,const char * alias,const char * alias_target)1182 void qemu_create_nic_bus_devices(BusState *bus, const char *parent_type,
1183                                  const char *default_model,
1184                                  const char *alias, const char *alias_target)
1185 {
1186     GPtrArray *nic_models = qemu_get_nic_models(parent_type);
1187     const char *model;
1188     DeviceState *dev;
1189     NICInfo *nd;
1190     int i;
1191 
1192     if (nic_model_help) {
1193         if (alias_target) {
1194             add_nic_model_help(alias_target, alias);
1195         }
1196         for (i = 0; i < nic_models->len - 1; i++) {
1197             add_nic_model_help(nic_models->pdata[i], NULL);
1198         }
1199     }
1200 
1201     /* Drop the NULL terminator which would make g_str_equal() unhappy */
1202     nic_models->len--;
1203 
1204     for (i = 0; i < nb_nics; i++) {
1205         nd = &nd_table[i];
1206 
1207         if (!nd->used || nd->instantiated) {
1208             continue;
1209         }
1210 
1211         model = nd->model ? nd->model : default_model;
1212         if (!model) {
1213             continue;
1214         }
1215 
1216         /* Each bus type is allowed *one* substitution */
1217         if (g_str_equal(model, alias)) {
1218             model = alias_target;
1219         }
1220 
1221         if (!g_ptr_array_find_with_equal_func(nic_models, model,
1222                                               g_str_equal, NULL)) {
1223             /* This NIC does not live on this bus. */
1224             continue;
1225         }
1226 
1227         dev = qdev_new(model);
1228         qdev_set_nic_properties(dev, nd);
1229         qdev_realize_and_unref(dev, bus, &error_fatal);
1230     }
1231 
1232     g_ptr_array_free(nic_models, true);
1233 }
1234 
1235 static int (* const net_client_init_fun[NET_CLIENT_DRIVER__MAX])(
1236     const Netdev *netdev,
1237     const char *name,
1238     NetClientState *peer, Error **errp) = {
1239         [NET_CLIENT_DRIVER_NIC]       = net_init_nic,
1240 #ifdef CONFIG_SLIRP
1241         [NET_CLIENT_DRIVER_USER]      = net_init_slirp,
1242 #endif
1243         [NET_CLIENT_DRIVER_TAP]       = net_init_tap,
1244         [NET_CLIENT_DRIVER_SOCKET]    = net_init_socket,
1245         [NET_CLIENT_DRIVER_STREAM]    = net_init_stream,
1246         [NET_CLIENT_DRIVER_DGRAM]     = net_init_dgram,
1247 #ifdef CONFIG_VDE
1248         [NET_CLIENT_DRIVER_VDE]       = net_init_vde,
1249 #endif
1250 #ifdef CONFIG_NETMAP
1251         [NET_CLIENT_DRIVER_NETMAP]    = net_init_netmap,
1252 #endif
1253 #ifdef CONFIG_AF_XDP
1254         [NET_CLIENT_DRIVER_AF_XDP]    = net_init_af_xdp,
1255 #endif
1256 #ifdef CONFIG_NET_BRIDGE
1257         [NET_CLIENT_DRIVER_BRIDGE]    = net_init_bridge,
1258 #endif
1259         [NET_CLIENT_DRIVER_HUBPORT]   = net_init_hubport,
1260 #ifdef CONFIG_VHOST_NET_USER
1261         [NET_CLIENT_DRIVER_VHOST_USER] = net_init_vhost_user,
1262 #endif
1263 #ifdef CONFIG_VHOST_NET_VDPA
1264         [NET_CLIENT_DRIVER_VHOST_VDPA] = net_init_vhost_vdpa,
1265 #endif
1266 #ifdef CONFIG_L2TPV3
1267         [NET_CLIENT_DRIVER_L2TPV3]    = net_init_l2tpv3,
1268 #endif
1269 #ifdef CONFIG_VMNET
1270         [NET_CLIENT_DRIVER_VMNET_HOST] = net_init_vmnet_host,
1271         [NET_CLIENT_DRIVER_VMNET_SHARED] = net_init_vmnet_shared,
1272         [NET_CLIENT_DRIVER_VMNET_BRIDGED] = net_init_vmnet_bridged,
1273 #endif /* CONFIG_VMNET */
1274 };
1275 
1276 
net_client_init1(const Netdev * netdev,bool is_netdev,Error ** errp)1277 static int net_client_init1(const Netdev *netdev, bool is_netdev, Error **errp)
1278 {
1279     NetClientState *peer = NULL;
1280     NetClientState *nc;
1281 
1282     if (is_netdev) {
1283         if (netdev->type == NET_CLIENT_DRIVER_NIC ||
1284             !net_client_init_fun[netdev->type]) {
1285             error_setg(errp, "network backend '%s' is not compiled into this binary",
1286                        NetClientDriver_str(netdev->type));
1287             return -1;
1288         }
1289     } else {
1290         if (netdev->type == NET_CLIENT_DRIVER_NONE) {
1291             return 0; /* nothing to do */
1292         }
1293         if (netdev->type == NET_CLIENT_DRIVER_HUBPORT) {
1294             error_setg(errp, "network backend '%s' is only supported with -netdev/-nic",
1295                        NetClientDriver_str(netdev->type));
1296             return -1;
1297         }
1298 
1299         if (!net_client_init_fun[netdev->type]) {
1300             error_setg(errp, "network backend '%s' is not compiled into this binary",
1301                        NetClientDriver_str(netdev->type));
1302             return -1;
1303         }
1304 
1305         /* Do not add to a hub if it's a nic with a netdev= parameter. */
1306         if (netdev->type != NET_CLIENT_DRIVER_NIC ||
1307             !netdev->u.nic.netdev) {
1308             peer = net_hub_add_port(0, NULL, NULL);
1309         }
1310     }
1311 
1312     nc = qemu_find_netdev(netdev->id);
1313     if (nc) {
1314         error_setg(errp, "Duplicate ID '%s'", netdev->id);
1315         return -1;
1316     }
1317 
1318     if (net_client_init_fun[netdev->type](netdev, netdev->id, peer, errp) < 0) {
1319         /* FIXME drop when all init functions store an Error */
1320         if (errp && !*errp) {
1321             error_setg(errp, "Device '%s' could not be initialized",
1322                        NetClientDriver_str(netdev->type));
1323         }
1324         return -1;
1325     }
1326 
1327     if (is_netdev) {
1328         nc = qemu_find_netdev(netdev->id);
1329         assert(nc);
1330         nc->is_netdev = true;
1331     }
1332 
1333     return 0;
1334 }
1335 
show_netdevs(void)1336 void show_netdevs(void)
1337 {
1338     int idx;
1339     const char *available_netdevs[] = {
1340         "socket",
1341         "stream",
1342         "dgram",
1343         "hubport",
1344         "tap",
1345 #ifdef CONFIG_SLIRP
1346         "user",
1347 #endif
1348 #ifdef CONFIG_L2TPV3
1349         "l2tpv3",
1350 #endif
1351 #ifdef CONFIG_VDE
1352         "vde",
1353 #endif
1354 #ifdef CONFIG_NET_BRIDGE
1355         "bridge",
1356 #endif
1357 #ifdef CONFIG_NETMAP
1358         "netmap",
1359 #endif
1360 #ifdef CONFIG_AF_XDP
1361         "af-xdp",
1362 #endif
1363 #ifdef CONFIG_POSIX
1364         "vhost-user",
1365 #endif
1366 #ifdef CONFIG_VHOST_VDPA
1367         "vhost-vdpa",
1368 #endif
1369 #ifdef CONFIG_VMNET
1370         "vmnet-host",
1371         "vmnet-shared",
1372         "vmnet-bridged",
1373 #endif
1374     };
1375 
1376     qemu_printf("Available netdev backend types:\n");
1377     for (idx = 0; idx < ARRAY_SIZE(available_netdevs); idx++) {
1378         qemu_printf("%s\n", available_netdevs[idx]);
1379     }
1380 }
1381 
net_client_init(QemuOpts * opts,bool is_netdev,Error ** errp)1382 static int net_client_init(QemuOpts *opts, bool is_netdev, Error **errp)
1383 {
1384     gchar **substrings = NULL;
1385     Netdev *object = NULL;
1386     int ret = -1;
1387     Visitor *v = opts_visitor_new(opts);
1388 
1389     /* Parse convenience option format ipv6-net=fec0::0[/64] */
1390     const char *ip6_net = qemu_opt_get(opts, "ipv6-net");
1391 
1392     if (ip6_net) {
1393         char *prefix_addr;
1394         unsigned long prefix_len = 64; /* Default 64bit prefix length. */
1395 
1396         substrings = g_strsplit(ip6_net, "/", 2);
1397         if (!substrings || !substrings[0]) {
1398             error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "ipv6-net",
1399                        "a valid IPv6 prefix");
1400             goto out;
1401         }
1402 
1403         prefix_addr = substrings[0];
1404 
1405         /* Handle user-specified prefix length. */
1406         if (substrings[1] &&
1407             qemu_strtoul(substrings[1], NULL, 10, &prefix_len))
1408         {
1409             error_setg(errp,
1410                        "parameter 'ipv6-net' expects a number after '/'");
1411             goto out;
1412         }
1413 
1414         qemu_opt_set(opts, "ipv6-prefix", prefix_addr, &error_abort);
1415         qemu_opt_set_number(opts, "ipv6-prefixlen", prefix_len,
1416                             &error_abort);
1417         qemu_opt_unset(opts, "ipv6-net");
1418     }
1419 
1420     /* Create an ID for -net if the user did not specify one */
1421     if (!is_netdev && !qemu_opts_id(opts)) {
1422         qemu_opts_set_id(opts, id_generate(ID_NET));
1423     }
1424 
1425     if (visit_type_Netdev(v, NULL, &object, errp)) {
1426         ret = net_client_init1(object, is_netdev, errp);
1427     }
1428 
1429     qapi_free_Netdev(object);
1430 
1431 out:
1432     g_strfreev(substrings);
1433     visit_free(v);
1434     return ret;
1435 }
1436 
netdev_add(QemuOpts * opts,Error ** errp)1437 void netdev_add(QemuOpts *opts, Error **errp)
1438 {
1439     net_client_init(opts, true, errp);
1440 }
1441 
qmp_netdev_add(Netdev * netdev,Error ** errp)1442 void qmp_netdev_add(Netdev *netdev, Error **errp)
1443 {
1444     if (!id_wellformed(netdev->id)) {
1445         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "id", "an identifier");
1446         return;
1447     }
1448 
1449     net_client_init1(netdev, true, errp);
1450 }
1451 
qmp_netdev_del(const char * id,Error ** errp)1452 void qmp_netdev_del(const char *id, Error **errp)
1453 {
1454     NetClientState *nc;
1455     QemuOpts *opts;
1456 
1457     nc = qemu_find_netdev(id);
1458     if (!nc) {
1459         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1460                   "Device '%s' not found", id);
1461         return;
1462     }
1463 
1464     if (!nc->is_netdev) {
1465         error_setg(errp, "Device '%s' is not a netdev", id);
1466         return;
1467     }
1468 
1469     qemu_del_net_client(nc);
1470 
1471     /*
1472      * Wart: we need to delete the QemuOpts associated with netdevs
1473      * created via CLI or HMP, to avoid bogus "Duplicate ID" errors in
1474      * HMP netdev_add.
1475      */
1476     opts = qemu_opts_find(qemu_find_opts("netdev"), id);
1477     if (opts) {
1478         qemu_opts_del(opts);
1479     }
1480 }
1481 
netfilter_print_info(Monitor * mon,NetFilterState * nf)1482 static void netfilter_print_info(Monitor *mon, NetFilterState *nf)
1483 {
1484     char *str;
1485     ObjectProperty *prop;
1486     ObjectPropertyIterator iter;
1487     Visitor *v;
1488 
1489     /* generate info str */
1490     object_property_iter_init(&iter, OBJECT(nf));
1491     while ((prop = object_property_iter_next(&iter))) {
1492         if (!strcmp(prop->name, "type")) {
1493             continue;
1494         }
1495         v = string_output_visitor_new(false, &str);
1496         object_property_get(OBJECT(nf), prop->name, v, NULL);
1497         visit_complete(v, &str);
1498         visit_free(v);
1499         monitor_printf(mon, ",%s=%s", prop->name, str);
1500         g_free(str);
1501     }
1502     monitor_printf(mon, "\n");
1503 }
1504 
print_net_client(Monitor * mon,NetClientState * nc)1505 void print_net_client(Monitor *mon, NetClientState *nc)
1506 {
1507     NetFilterState *nf;
1508 
1509     monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
1510                    nc->queue_index,
1511                    NetClientDriver_str(nc->info->type),
1512                    nc->info_str);
1513     if (!QTAILQ_EMPTY(&nc->filters)) {
1514         monitor_printf(mon, "filters:\n");
1515     }
1516     QTAILQ_FOREACH(nf, &nc->filters, next) {
1517         monitor_printf(mon, "  - %s: type=%s",
1518                        object_get_canonical_path_component(OBJECT(nf)),
1519                        object_get_typename(OBJECT(nf)));
1520         netfilter_print_info(mon, nf);
1521     }
1522 }
1523 
qmp_query_rx_filter(const char * name,Error ** errp)1524 RxFilterInfoList *qmp_query_rx_filter(const char *name, Error **errp)
1525 {
1526     NetClientState *nc;
1527     RxFilterInfoList *filter_list = NULL, **tail = &filter_list;
1528 
1529     QTAILQ_FOREACH(nc, &net_clients, next) {
1530         RxFilterInfo *info;
1531 
1532         if (name && strcmp(nc->name, name) != 0) {
1533             continue;
1534         }
1535 
1536         /* only query rx-filter information of NIC */
1537         if (nc->info->type != NET_CLIENT_DRIVER_NIC) {
1538             if (name) {
1539                 error_setg(errp, "net client(%s) isn't a NIC", name);
1540                 assert(!filter_list);
1541                 return NULL;
1542             }
1543             continue;
1544         }
1545 
1546         /* only query information on queue 0 since the info is per nic,
1547          * not per queue
1548          */
1549         if (nc->queue_index != 0)
1550             continue;
1551 
1552         if (nc->info->query_rx_filter) {
1553             info = nc->info->query_rx_filter(nc);
1554             QAPI_LIST_APPEND(tail, info);
1555         } else if (name) {
1556             error_setg(errp, "net client(%s) doesn't support"
1557                        " rx-filter querying", name);
1558             assert(!filter_list);
1559             return NULL;
1560         }
1561 
1562         if (name) {
1563             break;
1564         }
1565     }
1566 
1567     if (filter_list == NULL && name) {
1568         error_setg(errp, "invalid net client name: %s", name);
1569     }
1570 
1571     return filter_list;
1572 }
1573 
colo_notify_filters_event(int event,Error ** errp)1574 void colo_notify_filters_event(int event, Error **errp)
1575 {
1576     NetClientState *nc;
1577     NetFilterState *nf;
1578     NetFilterClass *nfc = NULL;
1579     Error *local_err = NULL;
1580 
1581     QTAILQ_FOREACH(nc, &net_clients, next) {
1582         QTAILQ_FOREACH(nf, &nc->filters, next) {
1583             nfc = NETFILTER_GET_CLASS(OBJECT(nf));
1584             nfc->handle_event(nf, event, &local_err);
1585             if (local_err) {
1586                 error_propagate(errp, local_err);
1587                 return;
1588             }
1589         }
1590     }
1591 }
1592 
qmp_set_link(const char * name,bool up,Error ** errp)1593 void qmp_set_link(const char *name, bool up, Error **errp)
1594 {
1595     NetClientState *ncs[MAX_QUEUE_NUM];
1596     NetClientState *nc;
1597     int queues, i;
1598 
1599     queues = qemu_find_net_clients_except(name, ncs,
1600                                           NET_CLIENT_DRIVER__MAX,
1601                                           MAX_QUEUE_NUM);
1602 
1603     if (queues == 0) {
1604         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1605                   "Device '%s' not found", name);
1606         return;
1607     }
1608     nc = ncs[0];
1609 
1610     for (i = 0; i < queues; i++) {
1611         ncs[i]->link_down = !up;
1612     }
1613 
1614     if (nc->info->link_status_changed) {
1615         nc->info->link_status_changed(nc);
1616     }
1617 
1618     if (nc->peer) {
1619         /* Change peer link only if the peer is NIC and then notify peer.
1620          * If the peer is a HUBPORT or a backend, we do not change the
1621          * link status.
1622          *
1623          * This behavior is compatible with qemu hubs where there could be
1624          * multiple clients that can still communicate with each other in
1625          * disconnected mode. For now maintain this compatibility.
1626          */
1627         if (nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
1628             for (i = 0; i < queues; i++) {
1629                 ncs[i]->peer->link_down = !up;
1630             }
1631         }
1632         if (nc->peer->info->link_status_changed) {
1633             nc->peer->info->link_status_changed(nc->peer);
1634         }
1635     }
1636 }
1637 
net_vm_change_state_handler(void * opaque,bool running,RunState state)1638 static void net_vm_change_state_handler(void *opaque, bool running,
1639                                         RunState state)
1640 {
1641     NetClientState *nc;
1642     NetClientState *tmp;
1643 
1644     QTAILQ_FOREACH_SAFE(nc, &net_clients, next, tmp) {
1645         if (running) {
1646             /* Flush queued packets and wake up backends. */
1647             if (nc->peer && qemu_can_send_packet(nc)) {
1648                 qemu_flush_queued_packets(nc->peer);
1649             }
1650         } else {
1651             /* Complete all queued packets, to guarantee we don't modify
1652              * state later when VM is not running.
1653              */
1654             qemu_flush_or_purge_queued_packets(nc, true);
1655         }
1656     }
1657 }
1658 
net_cleanup(void)1659 void net_cleanup(void)
1660 {
1661     NetClientState *nc, **p = &QTAILQ_FIRST(&net_clients);
1662 
1663     /*cleanup colo compare module for COLO*/
1664     colo_compare_cleanup();
1665 
1666     /*
1667      * Walk the net_clients list and remove the netdevs but *not* any
1668      * NET_CLIENT_DRIVER_NIC entries. The latter are owned by the device
1669      * model which created them, and in some cases (e.g. xen-net-device)
1670      * the device itself may do cleanup at exit and will be upset if we
1671      * just delete its NIC from underneath it.
1672      *
1673      * Since qemu_del_net_client() may delete multiple entries, using
1674      * QTAILQ_FOREACH_SAFE() is not safe here. The only safe pointer
1675      * to keep as a bookmark is a NET_CLIENT_DRIVER_NIC entry, so keep
1676      * 'p' pointing to either the head of the list, or the 'next' field
1677      * of the latest NET_CLIENT_DRIVER_NIC, and operate on *p as we walk
1678      * the list.
1679      *
1680      * The 'nc' variable isn't part of the list traversal; it's purely
1681      * for convenience as too much '(*p)->' has a tendency to make the
1682      * readers' eyes bleed.
1683      */
1684     while (*p) {
1685         nc = *p;
1686         if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
1687             /* Skip NET_CLIENT_DRIVER_NIC entries */
1688             p = &QTAILQ_NEXT(nc, next);
1689         } else {
1690             qemu_del_net_client(nc);
1691         }
1692     }
1693 
1694     qemu_del_vm_change_state_handler(net_change_state_entry);
1695 }
1696 
net_check_clients(void)1697 void net_check_clients(void)
1698 {
1699     NetClientState *nc;
1700     int i;
1701 
1702     if (nic_model_help) {
1703         show_nic_models();
1704         exit(0);
1705     }
1706     net_hub_check_clients();
1707 
1708     QTAILQ_FOREACH(nc, &net_clients, next) {
1709         if (!nc->peer) {
1710             warn_report("%s %s has no peer",
1711                         nc->info->type == NET_CLIENT_DRIVER_NIC
1712                         ? "nic" : "netdev",
1713                         nc->name);
1714         }
1715     }
1716 
1717     /* Check that all NICs requested via -net nic actually got created.
1718      * NICs created via -device don't need to be checked here because
1719      * they are always instantiated.
1720      */
1721     for (i = 0; i < MAX_NICS; i++) {
1722         NICInfo *nd = &nd_table[i];
1723         if (nd->used && !nd->instantiated) {
1724             warn_report("requested NIC (%s, model %s) "
1725                         "was not created (not supported by this machine?)",
1726                         nd->name ? nd->name : "anonymous",
1727                         nd->model ? nd->model : "unspecified");
1728         }
1729     }
1730 }
1731 
net_init_client(void * dummy,QemuOpts * opts,Error ** errp)1732 static int net_init_client(void *dummy, QemuOpts *opts, Error **errp)
1733 {
1734     const char *model = qemu_opt_get(opts, "model");
1735 
1736     if (is_nic_model_help_option(model)) {
1737         return 0;
1738     }
1739 
1740     return net_client_init(opts, false, errp);
1741 }
1742 
net_init_netdev(void * dummy,QemuOpts * opts,Error ** errp)1743 static int net_init_netdev(void *dummy, QemuOpts *opts, Error **errp)
1744 {
1745     const char *type = qemu_opt_get(opts, "type");
1746 
1747     if (type && is_help_option(type)) {
1748         show_netdevs();
1749         exit(0);
1750     }
1751     return net_client_init(opts, true, errp);
1752 }
1753 
1754 /* For the convenience "--nic" parameter */
net_param_nic(void * dummy,QemuOpts * opts,Error ** errp)1755 static int net_param_nic(void *dummy, QemuOpts *opts, Error **errp)
1756 {
1757     char *mac, *nd_id;
1758     int idx, ret;
1759     NICInfo *ni;
1760     const char *type;
1761 
1762     type = qemu_opt_get(opts, "type");
1763     if (type) {
1764         if (g_str_equal(type, "none")) {
1765             return 0;    /* Nothing to do, default_net is cleared in vl.c */
1766         }
1767         if (is_help_option(type)) {
1768             GPtrArray *nic_models = qemu_get_nic_models(TYPE_DEVICE);
1769             int i;
1770             show_netdevs();
1771             printf("\n");
1772             printf("Available NIC models "
1773                    "(use -nic model=help for a filtered list):\n");
1774             for (i = 0 ; nic_models->pdata[i]; i++) {
1775                 printf("%s\n", (char *)nic_models->pdata[i]);
1776             }
1777             g_ptr_array_free(nic_models, true);
1778             exit(0);
1779         }
1780     }
1781 
1782     idx = nic_get_free_idx();
1783     if (idx == -1 || nb_nics >= MAX_NICS) {
1784         error_setg(errp, "no more on-board/default NIC slots available");
1785         return -1;
1786     }
1787 
1788     if (!type) {
1789         qemu_opt_set(opts, "type", "user", &error_abort);
1790     }
1791 
1792     ni = &nd_table[idx];
1793     memset(ni, 0, sizeof(*ni));
1794     ni->model = qemu_opt_get_del(opts, "model");
1795 
1796     if (is_nic_model_help_option(ni->model)) {
1797         return 0;
1798     }
1799 
1800     /* Create an ID if the user did not specify one */
1801     nd_id = g_strdup(qemu_opts_id(opts));
1802     if (!nd_id) {
1803         nd_id = id_generate(ID_NET);
1804         qemu_opts_set_id(opts, nd_id);
1805     }
1806 
1807     /* Handle MAC address */
1808     mac = qemu_opt_get_del(opts, "mac");
1809     if (mac) {
1810         ret = net_parse_macaddr(ni->macaddr.a, mac);
1811         g_free(mac);
1812         if (ret) {
1813             error_setg(errp, "invalid syntax for ethernet address");
1814             goto out;
1815         }
1816         if (is_multicast_ether_addr(ni->macaddr.a)) {
1817             error_setg(errp, "NIC cannot have multicast MAC address");
1818             ret = -1;
1819             goto out;
1820         }
1821     }
1822     qemu_macaddr_default_if_unset(&ni->macaddr);
1823 
1824     ret = net_client_init(opts, true, errp);
1825     if (ret == 0) {
1826         ni->netdev = qemu_find_netdev(nd_id);
1827         ni->used = true;
1828         nb_nics++;
1829     }
1830 
1831 out:
1832     g_free(nd_id);
1833     return ret;
1834 }
1835 
netdev_init_modern(void)1836 static void netdev_init_modern(void)
1837 {
1838     while (!QSIMPLEQ_EMPTY(&nd_queue)) {
1839         NetdevQueueEntry *nd = QSIMPLEQ_FIRST(&nd_queue);
1840 
1841         QSIMPLEQ_REMOVE_HEAD(&nd_queue, entry);
1842         loc_push_restore(&nd->loc);
1843         net_client_init1(nd->nd, true, &error_fatal);
1844         loc_pop(&nd->loc);
1845         qapi_free_Netdev(nd->nd);
1846         g_free(nd);
1847     }
1848 }
1849 
net_init_clients(void)1850 void net_init_clients(void)
1851 {
1852     net_change_state_entry =
1853         qemu_add_vm_change_state_handler(net_vm_change_state_handler, NULL);
1854 
1855     QTAILQ_INIT(&net_clients);
1856 
1857     netdev_init_modern();
1858 
1859     qemu_opts_foreach(qemu_find_opts("netdev"), net_init_netdev, NULL,
1860                       &error_fatal);
1861 
1862     qemu_opts_foreach(qemu_find_opts("nic"), net_param_nic, NULL,
1863                       &error_fatal);
1864 
1865     qemu_opts_foreach(qemu_find_opts("net"), net_init_client, NULL,
1866                       &error_fatal);
1867 }
1868 
1869 /*
1870  * Does this -netdev argument use modern rather than traditional syntax?
1871  * Modern syntax is to be parsed with netdev_parse_modern().
1872  * Traditional syntax is to be parsed with net_client_parse().
1873  */
netdev_is_modern(const char * optstr)1874 bool netdev_is_modern(const char *optstr)
1875 {
1876     QemuOpts *opts;
1877     bool is_modern;
1878     const char *type;
1879     static QemuOptsList dummy_opts = {
1880         .name = "netdev",
1881         .implied_opt_name = "type",
1882         .head = QTAILQ_HEAD_INITIALIZER(dummy_opts.head),
1883         .desc = { { } },
1884     };
1885 
1886     if (optstr[0] == '{') {
1887         /* This is JSON, which means it's modern syntax */
1888         return true;
1889     }
1890 
1891     opts = qemu_opts_create(&dummy_opts, NULL, false, &error_abort);
1892     qemu_opts_do_parse(opts, optstr, dummy_opts.implied_opt_name,
1893                        &error_abort);
1894     type = qemu_opt_get(opts, "type");
1895     is_modern = !g_strcmp0(type, "stream") || !g_strcmp0(type, "dgram");
1896 
1897     qemu_opts_reset(&dummy_opts);
1898 
1899     return is_modern;
1900 }
1901 
1902 /*
1903  * netdev_parse_modern() uses modern, more expressive syntax than
1904  * net_client_parse(), but supports only the -netdev option.
1905  * netdev_parse_modern() appends to @nd_queue, whereas net_client_parse()
1906  * appends to @qemu_netdev_opts.
1907  */
netdev_parse_modern(const char * optstr)1908 void netdev_parse_modern(const char *optstr)
1909 {
1910     Visitor *v;
1911     NetdevQueueEntry *nd;
1912 
1913     v = qobject_input_visitor_new_str(optstr, "type", &error_fatal);
1914     nd = g_new(NetdevQueueEntry, 1);
1915     visit_type_Netdev(v, NULL, &nd->nd, &error_fatal);
1916     visit_free(v);
1917     loc_save(&nd->loc);
1918 
1919     QSIMPLEQ_INSERT_TAIL(&nd_queue, nd, entry);
1920 }
1921 
net_client_parse(QemuOptsList * opts_list,const char * optstr)1922 void net_client_parse(QemuOptsList *opts_list, const char *optstr)
1923 {
1924     if (!qemu_opts_parse_noisily(opts_list, optstr, true)) {
1925         exit(1);
1926     }
1927 }
1928 
1929 /* From FreeBSD */
1930 /* XXX: optimize */
net_crc32(const uint8_t * p,int len)1931 uint32_t net_crc32(const uint8_t *p, int len)
1932 {
1933     uint32_t crc;
1934     int carry, i, j;
1935     uint8_t b;
1936 
1937     crc = 0xffffffff;
1938     for (i = 0; i < len; i++) {
1939         b = *p++;
1940         for (j = 0; j < 8; j++) {
1941             carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
1942             crc <<= 1;
1943             b >>= 1;
1944             if (carry) {
1945                 crc = ((crc ^ POLYNOMIAL_BE) | carry);
1946             }
1947         }
1948     }
1949 
1950     return crc;
1951 }
1952 
net_crc32_le(const uint8_t * p,int len)1953 uint32_t net_crc32_le(const uint8_t *p, int len)
1954 {
1955     uint32_t crc;
1956     int carry, i, j;
1957     uint8_t b;
1958 
1959     crc = 0xffffffff;
1960     for (i = 0; i < len; i++) {
1961         b = *p++;
1962         for (j = 0; j < 8; j++) {
1963             carry = (crc & 0x1) ^ (b & 0x01);
1964             crc >>= 1;
1965             b >>= 1;
1966             if (carry) {
1967                 crc ^= POLYNOMIAL_LE;
1968             }
1969         }
1970     }
1971 
1972     return crc;
1973 }
1974 
1975 QemuOptsList qemu_netdev_opts = {
1976     .name = "netdev",
1977     .implied_opt_name = "type",
1978     .head = QTAILQ_HEAD_INITIALIZER(qemu_netdev_opts.head),
1979     .desc = {
1980         /*
1981          * no elements => accept any params
1982          * validation will happen later
1983          */
1984         { /* end of list */ }
1985     },
1986 };
1987 
1988 QemuOptsList qemu_nic_opts = {
1989     .name = "nic",
1990     .implied_opt_name = "type",
1991     .head = QTAILQ_HEAD_INITIALIZER(qemu_nic_opts.head),
1992     .desc = {
1993         /*
1994          * no elements => accept any params
1995          * validation will happen later
1996          */
1997         { /* end of list */ }
1998     },
1999 };
2000 
2001 QemuOptsList qemu_net_opts = {
2002     .name = "net",
2003     .implied_opt_name = "type",
2004     .head = QTAILQ_HEAD_INITIALIZER(qemu_net_opts.head),
2005     .desc = {
2006         /*
2007          * no elements => accept any params
2008          * validation will happen later
2009          */
2010         { /* end of list */ }
2011     },
2012 };
2013 
net_socket_rs_init(SocketReadState * rs,SocketReadStateFinalize * finalize,bool vnet_hdr)2014 void net_socket_rs_init(SocketReadState *rs,
2015                         SocketReadStateFinalize *finalize,
2016                         bool vnet_hdr)
2017 {
2018     rs->state = 0;
2019     rs->vnet_hdr = vnet_hdr;
2020     rs->index = 0;
2021     rs->packet_len = 0;
2022     rs->vnet_hdr_len = 0;
2023     memset(rs->buf, 0, sizeof(rs->buf));
2024     rs->finalize = finalize;
2025 }
2026 
2027 /*
2028  * Returns
2029  * 0: success
2030  * -1: error occurs
2031  */
net_fill_rstate(SocketReadState * rs,const uint8_t * buf,int size)2032 int net_fill_rstate(SocketReadState *rs, const uint8_t *buf, int size)
2033 {
2034     unsigned int l;
2035 
2036     while (size > 0) {
2037         /* Reassemble a packet from the network.
2038          * 0 = getting length.
2039          * 1 = getting vnet header length.
2040          * 2 = getting data.
2041          */
2042         switch (rs->state) {
2043         case 0:
2044             l = 4 - rs->index;
2045             if (l > size) {
2046                 l = size;
2047             }
2048             memcpy(rs->buf + rs->index, buf, l);
2049             buf += l;
2050             size -= l;
2051             rs->index += l;
2052             if (rs->index == 4) {
2053                 /* got length */
2054                 rs->packet_len = ntohl(*(uint32_t *)rs->buf);
2055                 rs->index = 0;
2056                 if (rs->vnet_hdr) {
2057                     rs->state = 1;
2058                 } else {
2059                     rs->state = 2;
2060                     rs->vnet_hdr_len = 0;
2061                 }
2062             }
2063             break;
2064         case 1:
2065             l = 4 - rs->index;
2066             if (l > size) {
2067                 l = size;
2068             }
2069             memcpy(rs->buf + rs->index, buf, l);
2070             buf += l;
2071             size -= l;
2072             rs->index += l;
2073             if (rs->index == 4) {
2074                 /* got vnet header length */
2075                 rs->vnet_hdr_len = ntohl(*(uint32_t *)rs->buf);
2076                 rs->index = 0;
2077                 rs->state = 2;
2078             }
2079             break;
2080         case 2:
2081             l = rs->packet_len - rs->index;
2082             if (l > size) {
2083                 l = size;
2084             }
2085             if (rs->index + l <= sizeof(rs->buf)) {
2086                 memcpy(rs->buf + rs->index, buf, l);
2087             } else {
2088                 fprintf(stderr, "serious error: oversized packet received,"
2089                     "connection terminated.\n");
2090                 rs->index = rs->state = 0;
2091                 return -1;
2092             }
2093 
2094             rs->index += l;
2095             buf += l;
2096             size -= l;
2097             if (rs->index >= rs->packet_len) {
2098                 rs->index = 0;
2099                 rs->state = 0;
2100                 assert(rs->finalize);
2101                 rs->finalize(rs);
2102             }
2103             break;
2104         }
2105     }
2106 
2107     assert(size == 0);
2108     return 0;
2109 }
2110