xref: /openbmc/qemu/net/net.c (revision 467397ea3051dcdf40fc5b3f6005ed5538937b01)
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 "qobject/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 "system/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,bool remove_from_net_clients)384 static void qemu_cleanup_net_client(NetClientState *nc,
385                                     bool remove_from_net_clients)
386 {
387     if (remove_from_net_clients) {
388         QTAILQ_REMOVE(&net_clients, nc, next);
389     }
390 
391     if (nc->info->cleanup) {
392         nc->info->cleanup(nc);
393     }
394 }
395 
qemu_free_net_client(NetClientState * nc)396 static void qemu_free_net_client(NetClientState *nc)
397 {
398     if (nc->incoming_queue) {
399         qemu_del_net_queue(nc->incoming_queue);
400     }
401     if (nc->peer) {
402         nc->peer->peer = NULL;
403     }
404     g_free(nc->name);
405     g_free(nc->model);
406     if (nc->destructor) {
407         nc->destructor(nc);
408     }
409 }
410 
qemu_del_net_client(NetClientState * nc)411 void qemu_del_net_client(NetClientState *nc)
412 {
413     NetClientState *ncs[MAX_QUEUE_NUM];
414     int queues, i;
415     NetFilterState *nf, *next;
416 
417     assert(nc->info->type != NET_CLIENT_DRIVER_NIC);
418 
419     /* If the NetClientState belongs to a multiqueue backend, we will change all
420      * other NetClientStates also.
421      */
422     queues = qemu_find_net_clients_except(nc->name, ncs,
423                                           NET_CLIENT_DRIVER_NIC,
424                                           MAX_QUEUE_NUM);
425     assert(queues != 0);
426 
427     QTAILQ_FOREACH_SAFE(nf, &nc->filters, next, next) {
428         object_unparent(OBJECT(nf));
429     }
430 
431     /*
432      * If there is a peer NIC, transfer ownership to it.  Delete the client
433      * from net_client list but do not cleanup nor free.  This way NIC can
434      * still access to members of the backend.
435      *
436      * The cleanup and free will be done when the NIC is free.
437      */
438     if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
439         NICState *nic = qemu_get_nic(nc->peer);
440         if (nic->peer_deleted) {
441             return;
442         }
443         nic->peer_deleted = true;
444 
445         for (i = 0; i < queues; i++) {
446             ncs[i]->peer->link_down = true;
447             QTAILQ_REMOVE(&net_clients, ncs[i], next);
448         }
449 
450         if (nc->peer->info->link_status_changed) {
451             nc->peer->info->link_status_changed(nc->peer);
452         }
453 
454         return;
455     }
456 
457     for (i = 0; i < queues; i++) {
458         qemu_cleanup_net_client(ncs[i], true);
459         qemu_free_net_client(ncs[i]);
460     }
461 }
462 
qemu_del_nic(NICState * nic)463 void qemu_del_nic(NICState *nic)
464 {
465     int i, queues = MAX(nic->conf->peers.queues, 1);
466 
467     qemu_macaddr_set_free(&nic->conf->macaddr);
468 
469     for (i = 0; i < queues; i++) {
470         NetClientState *nc = qemu_get_subqueue(nic, i);
471         /*
472          * If this is a peer NIC and peer has already been deleted, clean it up
473          * and free it now.
474          */
475         if (nic->peer_deleted) {
476             qemu_cleanup_net_client(nc->peer, false);
477             qemu_free_net_client(nc->peer);
478         } else if (nc->peer) {
479             /* if there are RX packets pending, complete them */
480             qemu_purge_queued_packets(nc->peer);
481         }
482     }
483 
484     for (i = queues - 1; i >= 0; i--) {
485         NetClientState *nc = qemu_get_subqueue(nic, i);
486 
487         qemu_cleanup_net_client(nc, true);
488         qemu_free_net_client(nc);
489     }
490 
491     g_free(nic);
492 }
493 
qemu_foreach_nic(qemu_nic_foreach func,void * opaque)494 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
495 {
496     NetClientState *nc;
497 
498     QTAILQ_FOREACH(nc, &net_clients, next) {
499         if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
500             if (nc->queue_index == 0) {
501                 func(qemu_get_nic(nc), opaque);
502             }
503         }
504     }
505 }
506 
qemu_has_ufo(NetClientState * nc)507 bool qemu_has_ufo(NetClientState *nc)
508 {
509     if (!nc || !nc->info->has_ufo) {
510         return false;
511     }
512 
513     return nc->info->has_ufo(nc);
514 }
515 
qemu_has_uso(NetClientState * nc)516 bool qemu_has_uso(NetClientState *nc)
517 {
518     if (!nc || !nc->info->has_uso) {
519         return false;
520     }
521 
522     return nc->info->has_uso(nc);
523 }
524 
qemu_has_vnet_hdr(NetClientState * nc)525 bool qemu_has_vnet_hdr(NetClientState *nc)
526 {
527     if (!nc || !nc->info->has_vnet_hdr) {
528         return false;
529     }
530 
531     return nc->info->has_vnet_hdr(nc);
532 }
533 
qemu_has_vnet_hdr_len(NetClientState * nc,int len)534 bool qemu_has_vnet_hdr_len(NetClientState *nc, int len)
535 {
536     if (!nc || !nc->info->has_vnet_hdr_len) {
537         return false;
538     }
539 
540     return nc->info->has_vnet_hdr_len(nc, len);
541 }
542 
qemu_set_offload(NetClientState * nc,int csum,int tso4,int tso6,int ecn,int ufo,int uso4,int uso6)543 void qemu_set_offload(NetClientState *nc, int csum, int tso4, int tso6,
544                           int ecn, int ufo, int uso4, int uso6)
545 {
546     if (!nc || !nc->info->set_offload) {
547         return;
548     }
549 
550     nc->info->set_offload(nc, csum, tso4, tso6, ecn, ufo, uso4, uso6);
551 }
552 
qemu_get_vnet_hdr_len(NetClientState * nc)553 int qemu_get_vnet_hdr_len(NetClientState *nc)
554 {
555     if (!nc) {
556         return 0;
557     }
558 
559     return nc->vnet_hdr_len;
560 }
561 
qemu_set_vnet_hdr_len(NetClientState * nc,int len)562 void qemu_set_vnet_hdr_len(NetClientState *nc, int len)
563 {
564     if (!nc || !nc->info->set_vnet_hdr_len) {
565         return;
566     }
567 
568     assert(len == sizeof(struct virtio_net_hdr_mrg_rxbuf) ||
569            len == sizeof(struct virtio_net_hdr) ||
570            len == sizeof(struct virtio_net_hdr_v1_hash));
571 
572     nc->vnet_hdr_len = len;
573     nc->info->set_vnet_hdr_len(nc, len);
574 }
575 
qemu_get_vnet_hash_supported_types(NetClientState * nc,uint32_t * types)576 bool qemu_get_vnet_hash_supported_types(NetClientState *nc, uint32_t *types)
577 {
578     if (!nc || !nc->info->get_vnet_hash_supported_types) {
579         return false;
580     }
581 
582     return nc->info->get_vnet_hash_supported_types(nc, types);
583 }
584 
qemu_set_vnet_le(NetClientState * nc,bool is_le)585 int qemu_set_vnet_le(NetClientState *nc, bool is_le)
586 {
587 #if HOST_BIG_ENDIAN
588     if (!nc || !nc->info->set_vnet_le) {
589         return -ENOSYS;
590     }
591 
592     return nc->info->set_vnet_le(nc, is_le);
593 #else
594     return 0;
595 #endif
596 }
597 
qemu_set_vnet_be(NetClientState * nc,bool is_be)598 int qemu_set_vnet_be(NetClientState *nc, bool is_be)
599 {
600 #if HOST_BIG_ENDIAN
601     return 0;
602 #else
603     if (!nc || !nc->info->set_vnet_be) {
604         return -ENOSYS;
605     }
606 
607     return nc->info->set_vnet_be(nc, is_be);
608 #endif
609 }
610 
qemu_can_receive_packet(NetClientState * nc)611 int qemu_can_receive_packet(NetClientState *nc)
612 {
613     if (nc->receive_disabled) {
614         return 0;
615     } else if (nc->info->can_receive &&
616                !nc->info->can_receive(nc)) {
617         return 0;
618     }
619     return 1;
620 }
621 
qemu_can_send_packet(NetClientState * sender)622 int qemu_can_send_packet(NetClientState *sender)
623 {
624     int vm_running = runstate_is_running();
625 
626     if (!vm_running) {
627         return 0;
628     }
629 
630     if (!sender->peer) {
631         return 1;
632     }
633 
634     return qemu_can_receive_packet(sender->peer);
635 }
636 
filter_receive_iov(NetClientState * nc,NetFilterDirection direction,NetClientState * sender,unsigned flags,const struct iovec * iov,int iovcnt,NetPacketSent * sent_cb)637 static ssize_t filter_receive_iov(NetClientState *nc,
638                                   NetFilterDirection direction,
639                                   NetClientState *sender,
640                                   unsigned flags,
641                                   const struct iovec *iov,
642                                   int iovcnt,
643                                   NetPacketSent *sent_cb)
644 {
645     ssize_t ret = 0;
646     NetFilterState *nf = NULL;
647 
648     if (direction == NET_FILTER_DIRECTION_TX) {
649         QTAILQ_FOREACH(nf, &nc->filters, next) {
650             ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
651                                          iovcnt, sent_cb);
652             if (ret) {
653                 return ret;
654             }
655         }
656     } else {
657         QTAILQ_FOREACH_REVERSE(nf, &nc->filters, next) {
658             ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
659                                          iovcnt, sent_cb);
660             if (ret) {
661                 return ret;
662             }
663         }
664     }
665 
666     return ret;
667 }
668 
filter_receive(NetClientState * nc,NetFilterDirection direction,NetClientState * sender,unsigned flags,const uint8_t * data,size_t size,NetPacketSent * sent_cb)669 static ssize_t filter_receive(NetClientState *nc,
670                               NetFilterDirection direction,
671                               NetClientState *sender,
672                               unsigned flags,
673                               const uint8_t *data,
674                               size_t size,
675                               NetPacketSent *sent_cb)
676 {
677     struct iovec iov = {
678         .iov_base = (void *)data,
679         .iov_len = size
680     };
681 
682     return filter_receive_iov(nc, direction, sender, flags, &iov, 1, sent_cb);
683 }
684 
qemu_purge_queued_packets(NetClientState * nc)685 void qemu_purge_queued_packets(NetClientState *nc)
686 {
687     if (!nc->peer) {
688         return;
689     }
690 
691     qemu_net_queue_purge(nc->peer->incoming_queue, nc);
692 }
693 
qemu_flush_or_purge_queued_packets(NetClientState * nc,bool purge)694 void qemu_flush_or_purge_queued_packets(NetClientState *nc, bool purge)
695 {
696     nc->receive_disabled = 0;
697 
698     if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_HUBPORT) {
699         if (net_hub_flush(nc->peer)) {
700             qemu_notify_event();
701         }
702     }
703     if (qemu_net_queue_flush(nc->incoming_queue)) {
704         /* We emptied the queue successfully, signal to the IO thread to repoll
705          * the file descriptor (for tap, for example).
706          */
707         qemu_notify_event();
708     } else if (purge) {
709         /* Unable to empty the queue, purge remaining packets */
710         qemu_net_queue_purge(nc->incoming_queue, nc->peer);
711     }
712 }
713 
qemu_flush_queued_packets(NetClientState * nc)714 void qemu_flush_queued_packets(NetClientState *nc)
715 {
716     qemu_flush_or_purge_queued_packets(nc, false);
717 }
718 
qemu_send_packet_async_with_flags(NetClientState * sender,unsigned flags,const uint8_t * buf,int size,NetPacketSent * sent_cb)719 static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
720                                                  unsigned flags,
721                                                  const uint8_t *buf, int size,
722                                                  NetPacketSent *sent_cb)
723 {
724     NetQueue *queue;
725     int ret;
726 
727 #ifdef DEBUG_NET
728     printf("qemu_send_packet_async:\n");
729     qemu_hexdump(stdout, "net", buf, size);
730 #endif
731 
732     if (sender->link_down || !sender->peer) {
733         return size;
734     }
735 
736     /* Let filters handle the packet first */
737     ret = filter_receive(sender, NET_FILTER_DIRECTION_TX,
738                          sender, flags, buf, size, sent_cb);
739     if (ret) {
740         return ret;
741     }
742 
743     ret = filter_receive(sender->peer, NET_FILTER_DIRECTION_RX,
744                          sender, flags, buf, size, sent_cb);
745     if (ret) {
746         return ret;
747     }
748 
749     queue = sender->peer->incoming_queue;
750 
751     return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
752 }
753 
qemu_send_packet_async(NetClientState * sender,const uint8_t * buf,int size,NetPacketSent * sent_cb)754 ssize_t qemu_send_packet_async(NetClientState *sender,
755                                const uint8_t *buf, int size,
756                                NetPacketSent *sent_cb)
757 {
758     return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
759                                              buf, size, sent_cb);
760 }
761 
qemu_send_packet(NetClientState * nc,const uint8_t * buf,int size)762 ssize_t qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size)
763 {
764     return qemu_send_packet_async(nc, buf, size, NULL);
765 }
766 
qemu_receive_packet(NetClientState * nc,const uint8_t * buf,int size)767 ssize_t qemu_receive_packet(NetClientState *nc, const uint8_t *buf, int size)
768 {
769     uint8_t min_pkt[ETH_ZLEN];
770     size_t min_pktsz = sizeof(min_pkt);
771 
772     if (!qemu_can_receive_packet(nc)) {
773         return 0;
774     }
775 
776     if (net_peer_needs_padding(nc)) {
777         if (eth_pad_short_frame(min_pkt, &min_pktsz, buf, size)) {
778             buf = min_pkt;
779             size = min_pktsz;
780         }
781     }
782 
783     return qemu_net_queue_receive(nc->incoming_queue, buf, size);
784 }
785 
qemu_send_packet_raw(NetClientState * nc,const uint8_t * buf,int size)786 ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size)
787 {
788     return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW,
789                                              buf, size, NULL);
790 }
791 
nc_sendv_compat(NetClientState * nc,const struct iovec * iov,int iovcnt,unsigned flags)792 static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
793                                int iovcnt, unsigned flags)
794 {
795     uint8_t *buf = NULL;
796     uint8_t *buffer;
797     size_t offset;
798     ssize_t ret;
799 
800     if (iovcnt == 1) {
801         buffer = iov[0].iov_base;
802         offset = iov[0].iov_len;
803     } else {
804         offset = iov_size(iov, iovcnt);
805         if (offset > NET_BUFSIZE) {
806             return -1;
807         }
808         buf = g_malloc(offset);
809         buffer = buf;
810         offset = iov_to_buf(iov, iovcnt, 0, buf, offset);
811     }
812 
813     ret = nc->info->receive(nc, buffer, offset);
814 
815     g_free(buf);
816     return ret;
817 }
818 
qemu_deliver_packet_iov(NetClientState * sender,unsigned flags,const struct iovec * iov,int iovcnt,void * opaque)819 static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
820                                        unsigned flags,
821                                        const struct iovec *iov,
822                                        int iovcnt,
823                                        void *opaque)
824 {
825     MemReentrancyGuard *owned_reentrancy_guard;
826     NetClientState *nc = opaque;
827     int ret;
828     struct virtio_net_hdr_v1_hash vnet_hdr = { };
829     g_autofree struct iovec *iov_copy = NULL;
830 
831 
832     if (nc->link_down) {
833         return iov_size(iov, iovcnt);
834     }
835 
836     if (nc->receive_disabled) {
837         return 0;
838     }
839 
840     if (nc->info->type != NET_CLIENT_DRIVER_NIC ||
841         qemu_get_nic(nc)->reentrancy_guard->engaged_in_io) {
842         owned_reentrancy_guard = NULL;
843     } else {
844         owned_reentrancy_guard = qemu_get_nic(nc)->reentrancy_guard;
845         owned_reentrancy_guard->engaged_in_io = true;
846     }
847 
848     if ((flags & QEMU_NET_PACKET_FLAG_RAW) && nc->vnet_hdr_len) {
849         iov_copy = g_new(struct iovec, iovcnt + 1);
850         iov_copy[0].iov_base = &vnet_hdr;
851         iov_copy[0].iov_len =  nc->vnet_hdr_len;
852         memcpy(&iov_copy[1], iov, iovcnt * sizeof(*iov));
853         iov = iov_copy;
854         iovcnt++;
855     }
856 
857     if (nc->info->receive_iov) {
858         ret = nc->info->receive_iov(nc, iov, iovcnt);
859     } else {
860         ret = nc_sendv_compat(nc, iov, iovcnt, flags);
861     }
862 
863     if (owned_reentrancy_guard) {
864         owned_reentrancy_guard->engaged_in_io = false;
865     }
866 
867     if (ret == 0) {
868         nc->receive_disabled = 1;
869     }
870 
871     return ret;
872 }
873 
qemu_sendv_packet_async(NetClientState * sender,const struct iovec * iov,int iovcnt,NetPacketSent * sent_cb)874 ssize_t qemu_sendv_packet_async(NetClientState *sender,
875                                 const struct iovec *iov, int iovcnt,
876                                 NetPacketSent *sent_cb)
877 {
878     NetQueue *queue;
879     size_t size = iov_size(iov, iovcnt);
880     int ret;
881 
882     if (size > NET_BUFSIZE) {
883         return size;
884     }
885 
886     if (sender->link_down || !sender->peer) {
887         return size;
888     }
889 
890     /* Let filters handle the packet first */
891     ret = filter_receive_iov(sender, NET_FILTER_DIRECTION_TX, sender,
892                              QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
893     if (ret) {
894         return ret;
895     }
896 
897     ret = filter_receive_iov(sender->peer, NET_FILTER_DIRECTION_RX, sender,
898                              QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
899     if (ret) {
900         return ret;
901     }
902 
903     queue = sender->peer->incoming_queue;
904 
905     return qemu_net_queue_send_iov(queue, sender,
906                                    QEMU_NET_PACKET_FLAG_NONE,
907                                    iov, iovcnt, sent_cb);
908 }
909 
910 ssize_t
qemu_sendv_packet(NetClientState * nc,const struct iovec * iov,int iovcnt)911 qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt)
912 {
913     return qemu_sendv_packet_async(nc, iov, iovcnt, NULL);
914 }
915 
qemu_find_netdev(const char * id)916 NetClientState *qemu_find_netdev(const char *id)
917 {
918     NetClientState *nc;
919 
920     QTAILQ_FOREACH(nc, &net_clients, next) {
921         if (nc->info->type == NET_CLIENT_DRIVER_NIC)
922             continue;
923         if (!strcmp(nc->name, id)) {
924             return nc;
925         }
926     }
927 
928     return NULL;
929 }
930 
qemu_find_net_clients_except(const char * id,NetClientState ** ncs,NetClientDriver type,int max)931 int qemu_find_net_clients_except(const char *id, NetClientState **ncs,
932                                  NetClientDriver type, int max)
933 {
934     NetClientState *nc;
935     int ret = 0;
936 
937     QTAILQ_FOREACH(nc, &net_clients, next) {
938         if (nc->info->type == type) {
939             continue;
940         }
941         if (!id || !strcmp(nc->name, id)) {
942             if (ret < max) {
943                 ncs[ret] = nc;
944             }
945             ret++;
946         }
947     }
948 
949     return ret;
950 }
951 
nic_get_free_idx(void)952 static int nic_get_free_idx(void)
953 {
954     int index;
955 
956     for (index = 0; index < MAX_NICS; index++)
957         if (!nd_table[index].used)
958             return index;
959     return -1;
960 }
961 
qemu_get_nic_models(const char * device_type)962 GPtrArray *qemu_get_nic_models(const char *device_type)
963 {
964     GPtrArray *nic_models = g_ptr_array_new();
965     GSList *list = object_class_get_list_sorted(device_type, false);
966 
967     while (list) {
968         DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, list->data,
969                                              TYPE_DEVICE);
970         GSList *next;
971         if (test_bit(DEVICE_CATEGORY_NETWORK, dc->categories) &&
972             dc->user_creatable) {
973             const char *name = object_class_get_name(list->data);
974             /*
975              * A network device might also be something else than a NIC, see
976              * e.g. the "rocker" device. Thus we have to look for the "netdev"
977              * property, too. Unfortunately, some devices like virtio-net only
978              * create this property during instance_init, so we have to create
979              * a temporary instance here to be able to check it.
980              */
981             Object *obj = object_new_with_class(OBJECT_CLASS(dc));
982             if (object_property_find(obj, "netdev")) {
983                 g_ptr_array_add(nic_models, (gpointer)name);
984             }
985             object_unref(obj);
986         }
987         next = list->next;
988         g_slist_free_1(list);
989         list = next;
990     }
991     g_ptr_array_add(nic_models, NULL);
992 
993     return nic_models;
994 }
995 
net_init_nic(const Netdev * netdev,const char * name,NetClientState * peer,Error ** errp)996 static int net_init_nic(const Netdev *netdev, const char *name,
997                         NetClientState *peer, Error **errp)
998 {
999     int idx;
1000     NICInfo *nd;
1001     const NetLegacyNicOptions *nic;
1002 
1003     assert(netdev->type == NET_CLIENT_DRIVER_NIC);
1004     nic = &netdev->u.nic;
1005 
1006     idx = nic_get_free_idx();
1007     if (idx == -1 || nb_nics >= MAX_NICS) {
1008         error_setg(errp, "too many NICs");
1009         return -1;
1010     }
1011 
1012     nd = &nd_table[idx];
1013 
1014     memset(nd, 0, sizeof(*nd));
1015 
1016     if (nic->netdev) {
1017         nd->netdev = qemu_find_netdev(nic->netdev);
1018         if (!nd->netdev) {
1019             error_setg(errp, "netdev '%s' not found", nic->netdev);
1020             return -1;
1021         }
1022     } else {
1023         assert(peer);
1024         nd->netdev = peer;
1025     }
1026     nd->name = g_strdup(name);
1027     if (nic->model) {
1028         nd->model = g_strdup(nic->model);
1029     }
1030     if (nic->addr) {
1031         nd->devaddr = g_strdup(nic->addr);
1032     }
1033 
1034     if (nic->macaddr &&
1035         net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {
1036         error_setg(errp, "invalid syntax for ethernet address");
1037         return -1;
1038     }
1039     if (nic->macaddr &&
1040         is_multicast_ether_addr(nd->macaddr.a)) {
1041         error_setg(errp,
1042                    "NIC cannot have multicast MAC address (odd 1st byte)");
1043         return -1;
1044     }
1045     qemu_macaddr_default_if_unset(&nd->macaddr);
1046 
1047     if (nic->has_vectors) {
1048         if (nic->vectors > 0x7ffffff) {
1049             error_setg(errp, "invalid # of vectors: %"PRIu32, nic->vectors);
1050             return -1;
1051         }
1052         nd->nvectors = nic->vectors;
1053     } else {
1054         nd->nvectors = DEV_NVECTORS_UNSPECIFIED;
1055     }
1056 
1057     nd->used = 1;
1058     nb_nics++;
1059 
1060     return idx;
1061 }
1062 
add_nic_result(gpointer key,gpointer value,gpointer user_data)1063 static gboolean add_nic_result(gpointer key, gpointer value, gpointer user_data)
1064 {
1065     GPtrArray *results = user_data;
1066     GPtrArray *alias_list = value;
1067     const char *model = key;
1068     char *result;
1069 
1070     if (!alias_list) {
1071         result = g_strdup(model);
1072     } else {
1073         GString *result_str = g_string_new(model);
1074         int i;
1075 
1076         g_string_append(result_str, " (aka ");
1077         for (i = 0; i < alias_list->len; i++) {
1078             if (i) {
1079                 g_string_append(result_str, ", ");
1080             }
1081             g_string_append(result_str, alias_list->pdata[i]);
1082         }
1083         g_string_append(result_str, ")");
1084         result = result_str->str;
1085         g_string_free(result_str, false);
1086         g_ptr_array_unref(alias_list);
1087     }
1088     g_ptr_array_add(results, result);
1089     return true;
1090 }
1091 
model_cmp(char ** a,char ** b)1092 static int model_cmp(char **a, char **b)
1093 {
1094     return strcmp(*a, *b);
1095 }
1096 
show_nic_models(void)1097 static void show_nic_models(void)
1098 {
1099     GPtrArray *results = g_ptr_array_new();
1100     int i;
1101 
1102     g_hash_table_foreach_remove(nic_model_help, add_nic_result, results);
1103     g_ptr_array_sort(results, (GCompareFunc)model_cmp);
1104 
1105     printf("Available NIC models for this configuration:\n");
1106     for (i = 0 ; i < results->len; i++) {
1107         printf("%s\n", (char *)results->pdata[i]);
1108     }
1109     g_hash_table_unref(nic_model_help);
1110     nic_model_help = NULL;
1111 }
1112 
add_nic_model_help(const char * model,const char * alias)1113 static void add_nic_model_help(const char *model, const char *alias)
1114 {
1115     GPtrArray *alias_list = NULL;
1116 
1117     if (g_hash_table_lookup_extended(nic_model_help, model, NULL,
1118                                      (gpointer *)&alias_list)) {
1119         /* Already exists, no alias to add: return */
1120         if (!alias) {
1121             return;
1122         }
1123         if (alias_list) {
1124             /* Check if this alias is already in the list. Add if not. */
1125             if (!g_ptr_array_find_with_equal_func(alias_list, alias,
1126                                                   g_str_equal, NULL)) {
1127                 g_ptr_array_add(alias_list, g_strdup(alias));
1128             }
1129             return;
1130         }
1131     }
1132     /* Either this model wasn't in the list already, or a first alias added */
1133     if (alias) {
1134         alias_list = g_ptr_array_new();
1135         g_ptr_array_set_free_func(alias_list, g_free);
1136         g_ptr_array_add(alias_list, g_strdup(alias));
1137     }
1138     g_hash_table_replace(nic_model_help, g_strdup(model), alias_list);
1139 }
1140 
qemu_find_nic_info(const char * typename,bool match_default,const char * alias)1141 NICInfo *qemu_find_nic_info(const char *typename, bool match_default,
1142                             const char *alias)
1143 {
1144     NICInfo *nd;
1145     int i;
1146 
1147     if (nic_model_help) {
1148         add_nic_model_help(typename, alias);
1149     }
1150 
1151     for (i = 0; i < nb_nics; i++) {
1152         nd = &nd_table[i];
1153 
1154         if (!nd->used || nd->instantiated) {
1155             continue;
1156         }
1157 
1158         if ((match_default && !nd->model) || !g_strcmp0(nd->model, typename)
1159             || (alias && !g_strcmp0(nd->model, alias))) {
1160             return nd;
1161         }
1162     }
1163     return NULL;
1164 }
1165 
is_nic_model_help_option(const char * model)1166 static bool is_nic_model_help_option(const char *model)
1167 {
1168     if (model && is_help_option(model)) {
1169         /*
1170          * Trigger the help output by instantiating the hash table which
1171          * will gather tha available models as they get registered.
1172          */
1173         if (!nic_model_help) {
1174             nic_model_help = g_hash_table_new_full(g_str_hash, g_str_equal,
1175                                                    g_free, NULL);
1176         }
1177         return true;
1178     }
1179     return false;
1180 }
1181 
1182 /* "I have created a device. Please configure it if you can" */
qemu_configure_nic_device(DeviceState * dev,bool match_default,const char * alias)1183 bool qemu_configure_nic_device(DeviceState *dev, bool match_default,
1184                                const char *alias)
1185 {
1186     NICInfo *nd = qemu_find_nic_info(object_get_typename(OBJECT(dev)),
1187                                      match_default, alias);
1188 
1189     if (nd) {
1190         qdev_set_nic_properties(dev, nd);
1191         return true;
1192     }
1193     return false;
1194 }
1195 
1196 /* "Please create a device, if you have a configuration for it" */
qemu_create_nic_device(const char * typename,bool match_default,const char * alias)1197 DeviceState *qemu_create_nic_device(const char *typename, bool match_default,
1198                                     const char *alias)
1199 {
1200     NICInfo *nd = qemu_find_nic_info(typename, match_default, alias);
1201     DeviceState *dev;
1202 
1203     if (!nd) {
1204         return NULL;
1205     }
1206 
1207     dev = qdev_new(typename);
1208     qdev_set_nic_properties(dev, nd);
1209     return dev;
1210 }
1211 
qemu_create_nic_bus_devices(BusState * bus,const char * parent_type,const char * default_model,const char * alias,const char * alias_target)1212 void qemu_create_nic_bus_devices(BusState *bus, const char *parent_type,
1213                                  const char *default_model,
1214                                  const char *alias, const char *alias_target)
1215 {
1216     GPtrArray *nic_models = qemu_get_nic_models(parent_type);
1217     const char *model;
1218     DeviceState *dev;
1219     NICInfo *nd;
1220     int i;
1221 
1222     if (nic_model_help) {
1223         if (alias_target) {
1224             add_nic_model_help(alias_target, alias);
1225         }
1226         for (i = 0; i < nic_models->len - 1; i++) {
1227             add_nic_model_help(nic_models->pdata[i], NULL);
1228         }
1229     }
1230 
1231     /* Drop the NULL terminator which would make g_str_equal() unhappy */
1232     nic_models->len--;
1233 
1234     for (i = 0; i < nb_nics; i++) {
1235         nd = &nd_table[i];
1236 
1237         if (!nd->used || nd->instantiated) {
1238             continue;
1239         }
1240 
1241         model = nd->model ? nd->model : default_model;
1242         if (!model) {
1243             continue;
1244         }
1245 
1246         /* Each bus type is allowed *one* substitution */
1247         if (g_str_equal(model, alias)) {
1248             model = alias_target;
1249         }
1250 
1251         if (!g_ptr_array_find_with_equal_func(nic_models, model,
1252                                               g_str_equal, NULL)) {
1253             /* This NIC does not live on this bus. */
1254             continue;
1255         }
1256 
1257         dev = qdev_new(model);
1258         qdev_set_nic_properties(dev, nd);
1259         qdev_realize_and_unref(dev, bus, &error_fatal);
1260     }
1261 
1262     g_ptr_array_free(nic_models, true);
1263 }
1264 
1265 static int (* const net_client_init_fun[NET_CLIENT_DRIVER__MAX])(
1266     const Netdev *netdev,
1267     const char *name,
1268     NetClientState *peer, Error **errp) = {
1269         [NET_CLIENT_DRIVER_NIC]       = net_init_nic,
1270 #ifdef CONFIG_PASST
1271         [NET_CLIENT_DRIVER_PASST]     = net_init_passt,
1272 #endif
1273 #ifdef CONFIG_SLIRP
1274         [NET_CLIENT_DRIVER_USER]      = net_init_slirp,
1275 #endif
1276         [NET_CLIENT_DRIVER_TAP]       = net_init_tap,
1277         [NET_CLIENT_DRIVER_SOCKET]    = net_init_socket,
1278         [NET_CLIENT_DRIVER_STREAM]    = net_init_stream,
1279         [NET_CLIENT_DRIVER_DGRAM]     = net_init_dgram,
1280 #ifdef CONFIG_VDE
1281         [NET_CLIENT_DRIVER_VDE]       = net_init_vde,
1282 #endif
1283 #ifdef CONFIG_NETMAP
1284         [NET_CLIENT_DRIVER_NETMAP]    = net_init_netmap,
1285 #endif
1286 #ifdef CONFIG_AF_XDP
1287         [NET_CLIENT_DRIVER_AF_XDP]    = net_init_af_xdp,
1288 #endif
1289 #ifdef CONFIG_NET_BRIDGE
1290         [NET_CLIENT_DRIVER_BRIDGE]    = net_init_bridge,
1291 #endif
1292         [NET_CLIENT_DRIVER_HUBPORT]   = net_init_hubport,
1293 #ifdef CONFIG_VHOST_NET_USER
1294         [NET_CLIENT_DRIVER_VHOST_USER] = net_init_vhost_user,
1295 #endif
1296 #ifdef CONFIG_VHOST_NET_VDPA
1297         [NET_CLIENT_DRIVER_VHOST_VDPA] = net_init_vhost_vdpa,
1298 #endif
1299 #ifdef CONFIG_L2TPV3
1300         [NET_CLIENT_DRIVER_L2TPV3]    = net_init_l2tpv3,
1301 #endif
1302 #ifdef CONFIG_VMNET
1303         [NET_CLIENT_DRIVER_VMNET_HOST] = net_init_vmnet_host,
1304         [NET_CLIENT_DRIVER_VMNET_SHARED] = net_init_vmnet_shared,
1305         [NET_CLIENT_DRIVER_VMNET_BRIDGED] = net_init_vmnet_bridged,
1306 #endif /* CONFIG_VMNET */
1307 };
1308 
1309 
net_client_init1(const Netdev * netdev,bool is_netdev,Error ** errp)1310 static int net_client_init1(const Netdev *netdev, bool is_netdev, Error **errp)
1311 {
1312     NetClientState *peer = NULL;
1313     NetClientState *nc;
1314 
1315     if (is_netdev) {
1316         if (netdev->type == NET_CLIENT_DRIVER_NIC ||
1317             !net_client_init_fun[netdev->type]) {
1318             error_setg(errp, "network backend '%s' is not compiled into this binary",
1319                        NetClientDriver_str(netdev->type));
1320             return -1;
1321         }
1322     } else {
1323         if (netdev->type == NET_CLIENT_DRIVER_NONE) {
1324             return 0; /* nothing to do */
1325         }
1326         if (netdev->type == NET_CLIENT_DRIVER_HUBPORT) {
1327             error_setg(errp, "network backend '%s' is only supported with -netdev/-nic",
1328                        NetClientDriver_str(netdev->type));
1329             return -1;
1330         }
1331 
1332         if (!net_client_init_fun[netdev->type]) {
1333             error_setg(errp, "network backend '%s' is not compiled into this binary",
1334                        NetClientDriver_str(netdev->type));
1335             return -1;
1336         }
1337 
1338         /* Do not add to a hub if it's a nic with a netdev= parameter. */
1339         if (netdev->type != NET_CLIENT_DRIVER_NIC ||
1340             !netdev->u.nic.netdev) {
1341             peer = net_hub_add_port(0, NULL, NULL);
1342         }
1343     }
1344 
1345     nc = qemu_find_netdev(netdev->id);
1346     if (nc) {
1347         error_setg(errp, "Duplicate ID '%s'", netdev->id);
1348         return -1;
1349     }
1350 
1351     if (net_client_init_fun[netdev->type](netdev, netdev->id, peer, errp) < 0) {
1352         /* FIXME drop when all init functions store an Error */
1353         if (errp && !*errp) {
1354             error_setg(errp, "Device '%s' could not be initialized",
1355                        NetClientDriver_str(netdev->type));
1356         }
1357         return -1;
1358     }
1359 
1360     if (is_netdev) {
1361         nc = qemu_find_netdev(netdev->id);
1362         assert(nc);
1363         nc->is_netdev = true;
1364     }
1365 
1366     return 0;
1367 }
1368 
show_netdevs(void)1369 void show_netdevs(void)
1370 {
1371     int idx;
1372     const char *available_netdevs[] = {
1373         "socket",
1374         "stream",
1375         "dgram",
1376         "hubport",
1377         "tap",
1378         "passt",
1379 #ifdef CONFIG_SLIRP
1380         "user",
1381 #endif
1382 #ifdef CONFIG_L2TPV3
1383         "l2tpv3",
1384 #endif
1385 #ifdef CONFIG_VDE
1386         "vde",
1387 #endif
1388 #ifdef CONFIG_NET_BRIDGE
1389         "bridge",
1390 #endif
1391 #ifdef CONFIG_NETMAP
1392         "netmap",
1393 #endif
1394 #ifdef CONFIG_AF_XDP
1395         "af-xdp",
1396 #endif
1397 #ifdef CONFIG_POSIX
1398         "vhost-user",
1399 #endif
1400 #ifdef CONFIG_VHOST_VDPA
1401         "vhost-vdpa",
1402 #endif
1403 #ifdef CONFIG_VMNET
1404         "vmnet-host",
1405         "vmnet-shared",
1406         "vmnet-bridged",
1407 #endif
1408     };
1409 
1410     qemu_printf("Available netdev backend types:\n");
1411     for (idx = 0; idx < ARRAY_SIZE(available_netdevs); idx++) {
1412         qemu_printf("%s\n", available_netdevs[idx]);
1413     }
1414 }
1415 
net_client_init(QemuOpts * opts,bool is_netdev,Error ** errp)1416 static int net_client_init(QemuOpts *opts, bool is_netdev, Error **errp)
1417 {
1418     gchar **substrings = NULL;
1419     Netdev *object = NULL;
1420     int ret = -1;
1421     Visitor *v = opts_visitor_new(opts);
1422 
1423     /* Parse convenience option format ipv6-net=fec0::0[/64] */
1424     const char *ip6_net = qemu_opt_get(opts, "ipv6-net");
1425 
1426     if (ip6_net) {
1427         char *prefix_addr;
1428         unsigned long prefix_len = 64; /* Default 64bit prefix length. */
1429 
1430         substrings = g_strsplit(ip6_net, "/", 2);
1431         if (!substrings || !substrings[0]) {
1432             error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "ipv6-net",
1433                        "a valid IPv6 prefix");
1434             goto out;
1435         }
1436 
1437         prefix_addr = substrings[0];
1438 
1439         /* Handle user-specified prefix length. */
1440         if (substrings[1] &&
1441             qemu_strtoul(substrings[1], NULL, 10, &prefix_len))
1442         {
1443             error_setg(errp,
1444                        "parameter 'ipv6-net' expects a number after '/'");
1445             goto out;
1446         }
1447 
1448         qemu_opt_set(opts, "ipv6-prefix", prefix_addr, &error_abort);
1449         qemu_opt_set_number(opts, "ipv6-prefixlen", prefix_len,
1450                             &error_abort);
1451         qemu_opt_unset(opts, "ipv6-net");
1452     }
1453 
1454     /* Create an ID for -net if the user did not specify one */
1455     if (!is_netdev && !qemu_opts_id(opts)) {
1456         qemu_opts_set_id(opts, id_generate(ID_NET));
1457     }
1458 
1459     if (visit_type_Netdev(v, NULL, &object, errp)) {
1460         ret = net_client_init1(object, is_netdev, errp);
1461     }
1462 
1463     qapi_free_Netdev(object);
1464 
1465 out:
1466     g_strfreev(substrings);
1467     visit_free(v);
1468     return ret;
1469 }
1470 
netdev_add(QemuOpts * opts,Error ** errp)1471 void netdev_add(QemuOpts *opts, Error **errp)
1472 {
1473     net_client_init(opts, true, errp);
1474 }
1475 
qmp_netdev_add(Netdev * netdev,Error ** errp)1476 void qmp_netdev_add(Netdev *netdev, Error **errp)
1477 {
1478     if (!id_wellformed(netdev->id)) {
1479         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "id", "an identifier");
1480         return;
1481     }
1482 
1483     net_client_init1(netdev, true, errp);
1484 }
1485 
qmp_netdev_del(const char * id,Error ** errp)1486 void qmp_netdev_del(const char *id, Error **errp)
1487 {
1488     NetClientState *nc;
1489     QemuOpts *opts;
1490 
1491     nc = qemu_find_netdev(id);
1492     if (!nc) {
1493         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1494                   "Device '%s' not found", id);
1495         return;
1496     }
1497 
1498     if (!nc->is_netdev) {
1499         error_setg(errp, "Device '%s' is not a netdev", id);
1500         return;
1501     }
1502 
1503     qemu_del_net_client(nc);
1504 
1505     /*
1506      * Wart: we need to delete the QemuOpts associated with netdevs
1507      * created via CLI or HMP, to avoid bogus "Duplicate ID" errors in
1508      * HMP netdev_add.
1509      */
1510     opts = qemu_opts_find(qemu_find_opts("netdev"), id);
1511     if (opts) {
1512         qemu_opts_del(opts);
1513     }
1514 }
1515 
netfilter_print_info(Monitor * mon,NetFilterState * nf)1516 static void netfilter_print_info(Monitor *mon, NetFilterState *nf)
1517 {
1518     char *str;
1519     ObjectProperty *prop;
1520     ObjectPropertyIterator iter;
1521     Visitor *v;
1522 
1523     /* generate info str */
1524     object_property_iter_init(&iter, OBJECT(nf));
1525     while ((prop = object_property_iter_next(&iter))) {
1526         if (!strcmp(prop->name, "type")) {
1527             continue;
1528         }
1529         v = string_output_visitor_new(false, &str);
1530         object_property_get(OBJECT(nf), prop->name, v, NULL);
1531         visit_complete(v, &str);
1532         visit_free(v);
1533         monitor_printf(mon, ",%s=%s", prop->name, str);
1534         g_free(str);
1535     }
1536     monitor_printf(mon, "\n");
1537 }
1538 
print_net_client(Monitor * mon,NetClientState * nc)1539 void print_net_client(Monitor *mon, NetClientState *nc)
1540 {
1541     NetFilterState *nf;
1542 
1543     monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
1544                    nc->queue_index,
1545                    NetClientDriver_str(nc->info->type),
1546                    nc->info_str);
1547     if (!QTAILQ_EMPTY(&nc->filters)) {
1548         monitor_printf(mon, "filters:\n");
1549     }
1550     QTAILQ_FOREACH(nf, &nc->filters, next) {
1551         monitor_printf(mon, "  - %s: type=%s",
1552                        object_get_canonical_path_component(OBJECT(nf)),
1553                        object_get_typename(OBJECT(nf)));
1554         netfilter_print_info(mon, nf);
1555     }
1556 }
1557 
qmp_query_rx_filter(const char * name,Error ** errp)1558 RxFilterInfoList *qmp_query_rx_filter(const char *name, Error **errp)
1559 {
1560     NetClientState *nc;
1561     RxFilterInfoList *filter_list = NULL, **tail = &filter_list;
1562 
1563     QTAILQ_FOREACH(nc, &net_clients, next) {
1564         RxFilterInfo *info;
1565 
1566         if (name && strcmp(nc->name, name) != 0) {
1567             continue;
1568         }
1569 
1570         /* only query rx-filter information of NIC */
1571         if (nc->info->type != NET_CLIENT_DRIVER_NIC) {
1572             if (name) {
1573                 error_setg(errp, "net client(%s) isn't a NIC", name);
1574                 assert(!filter_list);
1575                 return NULL;
1576             }
1577             continue;
1578         }
1579 
1580         /* only query information on queue 0 since the info is per nic,
1581          * not per queue
1582          */
1583         if (nc->queue_index != 0)
1584             continue;
1585 
1586         if (nc->info->query_rx_filter) {
1587             info = nc->info->query_rx_filter(nc);
1588             QAPI_LIST_APPEND(tail, info);
1589         } else if (name) {
1590             error_setg(errp, "net client(%s) doesn't support"
1591                        " rx-filter querying", name);
1592             assert(!filter_list);
1593             return NULL;
1594         }
1595 
1596         if (name) {
1597             break;
1598         }
1599     }
1600 
1601     if (filter_list == NULL && name) {
1602         error_setg(errp, "invalid net client name: %s", name);
1603     }
1604 
1605     return filter_list;
1606 }
1607 
colo_notify_filters_event(int event,Error ** errp)1608 void colo_notify_filters_event(int event, Error **errp)
1609 {
1610     NetClientState *nc;
1611     NetFilterState *nf;
1612     NetFilterClass *nfc = NULL;
1613     Error *local_err = NULL;
1614 
1615     QTAILQ_FOREACH(nc, &net_clients, next) {
1616         QTAILQ_FOREACH(nf, &nc->filters, next) {
1617             nfc = NETFILTER_GET_CLASS(OBJECT(nf));
1618             nfc->handle_event(nf, event, &local_err);
1619             if (local_err) {
1620                 error_propagate(errp, local_err);
1621                 return;
1622             }
1623         }
1624     }
1625 }
1626 
net_client_set_link(NetClientState ** ncs,int queues,bool up)1627 void net_client_set_link(NetClientState **ncs, int queues, bool up)
1628 {
1629     NetClientState *nc;
1630     int i;
1631 
1632     nc = ncs[0];
1633 
1634     for (i = 0; i < queues; i++) {
1635         ncs[i]->link_down = !up;
1636     }
1637 
1638     if (nc->info->link_status_changed) {
1639         nc->info->link_status_changed(nc);
1640     }
1641 
1642     if (nc->peer) {
1643         /* Change peer link only if the peer is NIC and then notify peer.
1644          * If the peer is a HUBPORT or a backend, we do not change the
1645          * link status.
1646          *
1647          * This behavior is compatible with qemu hubs where there could be
1648          * multiple clients that can still communicate with each other in
1649          * disconnected mode. For now maintain this compatibility.
1650          */
1651         if (nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
1652             for (i = 0; i < queues; i++) {
1653                 ncs[i]->peer->link_down = !up;
1654             }
1655         }
1656         if (nc->peer->info->link_status_changed) {
1657             nc->peer->info->link_status_changed(nc->peer);
1658         }
1659     }
1660 }
1661 
qmp_set_link(const char * name,bool up,Error ** errp)1662 void qmp_set_link(const char *name, bool up, Error **errp)
1663 {
1664     NetClientState *ncs[MAX_QUEUE_NUM];
1665     int queues;
1666 
1667     queues = qemu_find_net_clients_except(name, ncs,
1668                                           NET_CLIENT_DRIVER__MAX,
1669                                           MAX_QUEUE_NUM);
1670 
1671     if (queues == 0) {
1672         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1673                   "Device '%s' not found", name);
1674         return;
1675     }
1676 
1677     net_client_set_link(ncs, queues, up);
1678 }
1679 
net_vm_change_state_handler(void * opaque,bool running,RunState state)1680 static void net_vm_change_state_handler(void *opaque, bool running,
1681                                         RunState state)
1682 {
1683     NetClientState *nc;
1684     NetClientState *tmp;
1685 
1686     QTAILQ_FOREACH_SAFE(nc, &net_clients, next, tmp) {
1687         if (running) {
1688             /* Flush queued packets and wake up backends. */
1689             if (nc->peer && qemu_can_send_packet(nc)) {
1690                 qemu_flush_queued_packets(nc->peer);
1691             }
1692         } else {
1693             /* Complete all queued packets, to guarantee we don't modify
1694              * state later when VM is not running.
1695              */
1696             qemu_flush_or_purge_queued_packets(nc, true);
1697         }
1698     }
1699 }
1700 
net_cleanup(void)1701 void net_cleanup(void)
1702 {
1703     NetClientState *nc, **p = &QTAILQ_FIRST(&net_clients);
1704 
1705     /*cleanup colo compare module for COLO*/
1706     colo_compare_cleanup();
1707 
1708     /*
1709      * Walk the net_clients list and remove the netdevs but *not* any
1710      * NET_CLIENT_DRIVER_NIC entries. The latter are owned by the device
1711      * model which created them, and in some cases (e.g. xen-net-device)
1712      * the device itself may do cleanup at exit and will be upset if we
1713      * just delete its NIC from underneath it.
1714      *
1715      * Since qemu_del_net_client() may delete multiple entries, using
1716      * QTAILQ_FOREACH_SAFE() is not safe here. The only safe pointer
1717      * to keep as a bookmark is a NET_CLIENT_DRIVER_NIC entry, so keep
1718      * 'p' pointing to either the head of the list, or the 'next' field
1719      * of the latest NET_CLIENT_DRIVER_NIC, and operate on *p as we walk
1720      * the list.
1721      *
1722      * However, the NIC may have peers that trust to be clean beyond this
1723      * point.  For example, if they have been removed with device_del.
1724      *
1725      * The 'nc' variable isn't part of the list traversal; it's purely
1726      * for convenience as too much '(*p)->' has a tendency to make the
1727      * readers' eyes bleed.
1728      */
1729     while (*p) {
1730         nc = *p;
1731         if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
1732             NICState *nic = qemu_get_nic(nc);
1733 
1734             if (nic->peer_deleted) {
1735                 int queues = MAX(nic->conf->peers.queues, 1);
1736 
1737                 for (int i = 0; i < queues; i++) {
1738                     nc = qemu_get_subqueue(nic, i);
1739                     qemu_cleanup_net_client(nc->peer, false);
1740                 }
1741             }
1742 
1743             /* Skip NET_CLIENT_DRIVER_NIC entries */
1744             p = &QTAILQ_NEXT(nc, next);
1745         } else {
1746             qemu_del_net_client(nc);
1747         }
1748     }
1749 
1750     qemu_del_vm_change_state_handler(net_change_state_entry);
1751 }
1752 
net_check_clients(void)1753 void net_check_clients(void)
1754 {
1755     NetClientState *nc;
1756     int i;
1757 
1758     if (nic_model_help) {
1759         show_nic_models();
1760         exit(0);
1761     }
1762     net_hub_check_clients();
1763 
1764     QTAILQ_FOREACH(nc, &net_clients, next) {
1765         if (!nc->peer) {
1766             warn_report("%s %s has no peer",
1767                         nc->info->type == NET_CLIENT_DRIVER_NIC
1768                         ? "nic" : "netdev",
1769                         nc->name);
1770         }
1771     }
1772 
1773     /* Check that all NICs requested via -net nic actually got created.
1774      * NICs created via -device don't need to be checked here because
1775      * they are always instantiated.
1776      */
1777     for (i = 0; i < MAX_NICS; i++) {
1778         NICInfo *nd = &nd_table[i];
1779         if (nd->used && !nd->instantiated) {
1780             warn_report("requested NIC (%s, model %s) "
1781                         "was not created (not supported by this machine?)",
1782                         nd->name ? nd->name : "anonymous",
1783                         nd->model ? nd->model : "unspecified");
1784         }
1785     }
1786 }
1787 
net_init_client(void * dummy,QemuOpts * opts,Error ** errp)1788 static int net_init_client(void *dummy, QemuOpts *opts, Error **errp)
1789 {
1790     const char *model = qemu_opt_get(opts, "model");
1791 
1792     if (is_nic_model_help_option(model)) {
1793         return 0;
1794     }
1795 
1796     return net_client_init(opts, false, errp);
1797 }
1798 
net_init_netdev(void * dummy,QemuOpts * opts,Error ** errp)1799 static int net_init_netdev(void *dummy, QemuOpts *opts, Error **errp)
1800 {
1801     const char *type = qemu_opt_get(opts, "type");
1802 
1803     if (type && is_help_option(type)) {
1804         show_netdevs();
1805         exit(0);
1806     }
1807     return net_client_init(opts, true, errp);
1808 }
1809 
1810 /* For the convenience "--nic" parameter */
net_param_nic(void * dummy,QemuOpts * opts,Error ** errp)1811 static int net_param_nic(void *dummy, QemuOpts *opts, Error **errp)
1812 {
1813     char *mac, *nd_id;
1814     int idx, ret;
1815     NICInfo *ni;
1816     const char *type;
1817 
1818     type = qemu_opt_get(opts, "type");
1819     if (type) {
1820         if (g_str_equal(type, "none")) {
1821             return 0;    /* Nothing to do, default_net is cleared in vl.c */
1822         }
1823         if (is_help_option(type)) {
1824             GPtrArray *nic_models = qemu_get_nic_models(TYPE_DEVICE);
1825             int i;
1826             show_netdevs();
1827             printf("\n");
1828             printf("Available NIC models "
1829                    "(use -nic model=help for a filtered list):\n");
1830             for (i = 0 ; nic_models->pdata[i]; i++) {
1831                 printf("%s\n", (char *)nic_models->pdata[i]);
1832             }
1833             g_ptr_array_free(nic_models, true);
1834             exit(0);
1835         }
1836     }
1837 
1838     idx = nic_get_free_idx();
1839     if (idx == -1 || nb_nics >= MAX_NICS) {
1840         error_setg(errp, "no more on-board/default NIC slots available");
1841         return -1;
1842     }
1843 
1844     if (!type) {
1845         qemu_opt_set(opts, "type", "user", &error_abort);
1846     }
1847 
1848     ni = &nd_table[idx];
1849     memset(ni, 0, sizeof(*ni));
1850     ni->model = qemu_opt_get_del(opts, "model");
1851 
1852     if (is_nic_model_help_option(ni->model)) {
1853         return 0;
1854     }
1855 
1856     /* Create an ID if the user did not specify one */
1857     nd_id = g_strdup(qemu_opts_id(opts));
1858     if (!nd_id) {
1859         nd_id = id_generate(ID_NET);
1860         qemu_opts_set_id(opts, nd_id);
1861     }
1862 
1863     /* Handle MAC address */
1864     mac = qemu_opt_get_del(opts, "mac");
1865     if (mac) {
1866         ret = net_parse_macaddr(ni->macaddr.a, mac);
1867         g_free(mac);
1868         if (ret) {
1869             error_setg(errp, "invalid syntax for ethernet address");
1870             goto out;
1871         }
1872         if (is_multicast_ether_addr(ni->macaddr.a)) {
1873             error_setg(errp, "NIC cannot have multicast MAC address");
1874             ret = -1;
1875             goto out;
1876         }
1877     }
1878     qemu_macaddr_default_if_unset(&ni->macaddr);
1879 
1880     ret = net_client_init(opts, true, errp);
1881     if (ret == 0) {
1882         ni->netdev = qemu_find_netdev(nd_id);
1883         ni->used = true;
1884         nb_nics++;
1885     }
1886 
1887 out:
1888     g_free(nd_id);
1889     return ret;
1890 }
1891 
netdev_init_modern(void)1892 static void netdev_init_modern(void)
1893 {
1894     while (!QSIMPLEQ_EMPTY(&nd_queue)) {
1895         NetdevQueueEntry *nd = QSIMPLEQ_FIRST(&nd_queue);
1896 
1897         QSIMPLEQ_REMOVE_HEAD(&nd_queue, entry);
1898         loc_push_restore(&nd->loc);
1899         net_client_init1(nd->nd, true, &error_fatal);
1900         loc_pop(&nd->loc);
1901         qapi_free_Netdev(nd->nd);
1902         g_free(nd);
1903     }
1904 }
1905 
net_init_clients(void)1906 void net_init_clients(void)
1907 {
1908     net_change_state_entry =
1909         qemu_add_vm_change_state_handler(net_vm_change_state_handler, NULL);
1910 
1911     QTAILQ_INIT(&net_clients);
1912 
1913     netdev_init_modern();
1914 
1915     qemu_opts_foreach(qemu_find_opts("netdev"), net_init_netdev, NULL,
1916                       &error_fatal);
1917 
1918     qemu_opts_foreach(qemu_find_opts("nic"), net_param_nic, NULL,
1919                       &error_fatal);
1920 
1921     qemu_opts_foreach(qemu_find_opts("net"), net_init_client, NULL,
1922                       &error_fatal);
1923 }
1924 
1925 /*
1926  * Does this -netdev argument use modern rather than traditional syntax?
1927  * Modern syntax is to be parsed with netdev_parse_modern().
1928  * Traditional syntax is to be parsed with net_client_parse().
1929  */
netdev_is_modern(const char * optstr)1930 bool netdev_is_modern(const char *optstr)
1931 {
1932     QemuOpts *opts;
1933     bool is_modern;
1934     const char *type;
1935     static QemuOptsList dummy_opts = {
1936         .name = "netdev",
1937         .implied_opt_name = "type",
1938         .head = QTAILQ_HEAD_INITIALIZER(dummy_opts.head),
1939         .desc = { { } },
1940     };
1941 
1942     if (optstr[0] == '{') {
1943         /* This is JSON, which means it's modern syntax */
1944         return true;
1945     }
1946 
1947     opts = qemu_opts_create(&dummy_opts, NULL, false, &error_abort);
1948     qemu_opts_do_parse(opts, optstr, dummy_opts.implied_opt_name,
1949                        &error_abort);
1950     type = qemu_opt_get(opts, "type");
1951     is_modern = !g_strcmp0(type, "stream") || !g_strcmp0(type, "dgram");
1952 
1953     qemu_opts_reset(&dummy_opts);
1954 
1955     return is_modern;
1956 }
1957 
1958 /*
1959  * netdev_parse_modern() uses modern, more expressive syntax than
1960  * net_client_parse(), but supports only the -netdev option.
1961  * netdev_parse_modern() appends to @nd_queue, whereas net_client_parse()
1962  * appends to @qemu_netdev_opts.
1963  */
netdev_parse_modern(const char * optstr)1964 void netdev_parse_modern(const char *optstr)
1965 {
1966     Visitor *v;
1967     NetdevQueueEntry *nd;
1968 
1969     v = qobject_input_visitor_new_str(optstr, "type", &error_fatal);
1970     nd = g_new(NetdevQueueEntry, 1);
1971     visit_type_Netdev(v, NULL, &nd->nd, &error_fatal);
1972     visit_free(v);
1973     loc_save(&nd->loc);
1974 
1975     QSIMPLEQ_INSERT_TAIL(&nd_queue, nd, entry);
1976 }
1977 
net_client_parse(QemuOptsList * opts_list,const char * optstr)1978 void net_client_parse(QemuOptsList *opts_list, const char *optstr)
1979 {
1980     if (!qemu_opts_parse_noisily(opts_list, optstr, true)) {
1981         exit(1);
1982     }
1983 }
1984 
1985 /* From FreeBSD */
1986 /* XXX: optimize */
net_crc32(const uint8_t * p,int len)1987 uint32_t net_crc32(const uint8_t *p, int len)
1988 {
1989     uint32_t crc;
1990     int carry, i, j;
1991     uint8_t b;
1992 
1993     crc = 0xffffffff;
1994     for (i = 0; i < len; i++) {
1995         b = *p++;
1996         for (j = 0; j < 8; j++) {
1997             carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
1998             crc <<= 1;
1999             b >>= 1;
2000             if (carry) {
2001                 crc = ((crc ^ POLYNOMIAL_BE) | carry);
2002             }
2003         }
2004     }
2005 
2006     return crc;
2007 }
2008 
net_crc32_le(const uint8_t * p,int len)2009 uint32_t net_crc32_le(const uint8_t *p, int len)
2010 {
2011     uint32_t crc;
2012     int carry, i, j;
2013     uint8_t b;
2014 
2015     crc = 0xffffffff;
2016     for (i = 0; i < len; i++) {
2017         b = *p++;
2018         for (j = 0; j < 8; j++) {
2019             carry = (crc & 0x1) ^ (b & 0x01);
2020             crc >>= 1;
2021             b >>= 1;
2022             if (carry) {
2023                 crc ^= POLYNOMIAL_LE;
2024             }
2025         }
2026     }
2027 
2028     return crc;
2029 }
2030 
2031 QemuOptsList qemu_netdev_opts = {
2032     .name = "netdev",
2033     .implied_opt_name = "type",
2034     .head = QTAILQ_HEAD_INITIALIZER(qemu_netdev_opts.head),
2035     .desc = {
2036         /*
2037          * no elements => accept any params
2038          * validation will happen later
2039          */
2040         { /* end of list */ }
2041     },
2042 };
2043 
2044 QemuOptsList qemu_nic_opts = {
2045     .name = "nic",
2046     .implied_opt_name = "type",
2047     .head = QTAILQ_HEAD_INITIALIZER(qemu_nic_opts.head),
2048     .desc = {
2049         /*
2050          * no elements => accept any params
2051          * validation will happen later
2052          */
2053         { /* end of list */ }
2054     },
2055 };
2056 
2057 QemuOptsList qemu_net_opts = {
2058     .name = "net",
2059     .implied_opt_name = "type",
2060     .head = QTAILQ_HEAD_INITIALIZER(qemu_net_opts.head),
2061     .desc = {
2062         /*
2063          * no elements => accept any params
2064          * validation will happen later
2065          */
2066         { /* end of list */ }
2067     },
2068 };
2069 
net_socket_rs_init(SocketReadState * rs,SocketReadStateFinalize * finalize,bool vnet_hdr)2070 void net_socket_rs_init(SocketReadState *rs,
2071                         SocketReadStateFinalize *finalize,
2072                         bool vnet_hdr)
2073 {
2074     rs->state = 0;
2075     rs->vnet_hdr = vnet_hdr;
2076     rs->index = 0;
2077     rs->packet_len = 0;
2078     rs->vnet_hdr_len = 0;
2079     memset(rs->buf, 0, sizeof(rs->buf));
2080     rs->finalize = finalize;
2081 }
2082 
2083 /*
2084  * Returns
2085  * 0: success
2086  * -1: error occurs
2087  */
net_fill_rstate(SocketReadState * rs,const uint8_t * buf,int size)2088 int net_fill_rstate(SocketReadState *rs, const uint8_t *buf, int size)
2089 {
2090     unsigned int l;
2091 
2092     while (size > 0) {
2093         /* Reassemble a packet from the network.
2094          * 0 = getting length.
2095          * 1 = getting vnet header length.
2096          * 2 = getting data.
2097          */
2098         switch (rs->state) {
2099         case 0:
2100             l = 4 - rs->index;
2101             if (l > size) {
2102                 l = size;
2103             }
2104             memcpy(rs->buf + rs->index, buf, l);
2105             buf += l;
2106             size -= l;
2107             rs->index += l;
2108             if (rs->index == 4) {
2109                 /* got length */
2110                 rs->packet_len = ntohl(*(uint32_t *)rs->buf);
2111                 rs->index = 0;
2112                 if (rs->vnet_hdr) {
2113                     rs->state = 1;
2114                 } else {
2115                     rs->state = 2;
2116                     rs->vnet_hdr_len = 0;
2117                 }
2118             }
2119             break;
2120         case 1:
2121             l = 4 - rs->index;
2122             if (l > size) {
2123                 l = size;
2124             }
2125             memcpy(rs->buf + rs->index, buf, l);
2126             buf += l;
2127             size -= l;
2128             rs->index += l;
2129             if (rs->index == 4) {
2130                 /* got vnet header length */
2131                 rs->vnet_hdr_len = ntohl(*(uint32_t *)rs->buf);
2132                 rs->index = 0;
2133                 rs->state = 2;
2134             }
2135             break;
2136         case 2:
2137             l = rs->packet_len - rs->index;
2138             if (l > size) {
2139                 l = size;
2140             }
2141             if (rs->index + l <= sizeof(rs->buf)) {
2142                 memcpy(rs->buf + rs->index, buf, l);
2143             } else {
2144                 fprintf(stderr, "serious error: oversized packet received,"
2145                     "connection terminated.\n");
2146                 rs->index = rs->state = 0;
2147                 return -1;
2148             }
2149 
2150             rs->index += l;
2151             buf += l;
2152             size -= l;
2153             if (rs->index >= rs->packet_len) {
2154                 rs->index = 0;
2155                 rs->state = 0;
2156                 assert(rs->finalize);
2157                 rs->finalize(rs);
2158             }
2159             break;
2160         }
2161     }
2162 
2163     assert(size == 0);
2164     return 0;
2165 }
2166