xref: /openbmc/qemu/net/net.c (revision 49f95221)
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 "qapi/error.h"
52 #include "qapi/opts-visitor.h"
53 #include "sysemu/runstate.h"
54 #include "net/colo-compare.h"
55 #include "net/filter.h"
56 #include "qapi/string-output-visitor.h"
57 
58 /* Net bridge is currently not supported for W32. */
59 #if !defined(_WIN32)
60 # define CONFIG_NET_BRIDGE
61 #endif
62 
63 static VMChangeStateEntry *net_change_state_entry;
64 static QTAILQ_HEAD(, NetClientState) net_clients;
65 
66 /***********************************************************/
67 /* network device redirectors */
68 
69 int parse_host_port(struct sockaddr_in *saddr, const char *str,
70                     Error **errp)
71 {
72     gchar **substrings;
73     struct hostent *he;
74     const char *addr, *p, *r;
75     int port, ret = 0;
76 
77     memset(saddr, 0, sizeof(*saddr));
78 
79     substrings = g_strsplit(str, ":", 2);
80     if (!substrings || !substrings[0] || !substrings[1]) {
81         error_setg(errp, "host address '%s' doesn't contain ':' "
82                    "separating host from port", str);
83         ret = -1;
84         goto out;
85     }
86 
87     addr = substrings[0];
88     p = substrings[1];
89 
90     saddr->sin_family = AF_INET;
91     if (addr[0] == '\0') {
92         saddr->sin_addr.s_addr = 0;
93     } else {
94         if (qemu_isdigit(addr[0])) {
95             if (!inet_aton(addr, &saddr->sin_addr)) {
96                 error_setg(errp, "host address '%s' is not a valid "
97                            "IPv4 address", addr);
98                 ret = -1;
99                 goto out;
100             }
101         } else {
102             he = gethostbyname(addr);
103             if (he == NULL) {
104                 error_setg(errp, "can't resolve host address '%s'", addr);
105                 ret = -1;
106                 goto out;
107             }
108             saddr->sin_addr = *(struct in_addr *)he->h_addr;
109         }
110     }
111     port = strtol(p, (char **)&r, 0);
112     if (r == p) {
113         error_setg(errp, "port number '%s' is invalid", p);
114         ret = -1;
115         goto out;
116     }
117     saddr->sin_port = htons(port);
118 
119 out:
120     g_strfreev(substrings);
121     return ret;
122 }
123 
124 char *qemu_mac_strdup_printf(const uint8_t *macaddr)
125 {
126     return g_strdup_printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
127                            macaddr[0], macaddr[1], macaddr[2],
128                            macaddr[3], macaddr[4], macaddr[5]);
129 }
130 
131 void qemu_format_nic_info_str(NetClientState *nc, uint8_t macaddr[6])
132 {
133     snprintf(nc->info_str, sizeof(nc->info_str),
134              "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
135              nc->model,
136              macaddr[0], macaddr[1], macaddr[2],
137              macaddr[3], macaddr[4], macaddr[5]);
138 }
139 
140 static int mac_table[256] = {0};
141 
142 static void qemu_macaddr_set_used(MACAddr *macaddr)
143 {
144     int index;
145 
146     for (index = 0x56; index < 0xFF; index++) {
147         if (macaddr->a[5] == index) {
148             mac_table[index]++;
149         }
150     }
151 }
152 
153 static void qemu_macaddr_set_free(MACAddr *macaddr)
154 {
155     int index;
156     static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
157 
158     if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
159         return;
160     }
161     for (index = 0x56; index < 0xFF; index++) {
162         if (macaddr->a[5] == index) {
163             mac_table[index]--;
164         }
165     }
166 }
167 
168 static int qemu_macaddr_get_free(void)
169 {
170     int index;
171 
172     for (index = 0x56; index < 0xFF; index++) {
173         if (mac_table[index] == 0) {
174             return index;
175         }
176     }
177 
178     return -1;
179 }
180 
181 void qemu_macaddr_default_if_unset(MACAddr *macaddr)
182 {
183     static const MACAddr zero = { .a = { 0,0,0,0,0,0 } };
184     static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
185 
186     if (memcmp(macaddr, &zero, sizeof(zero)) != 0) {
187         if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
188             return;
189         } else {
190             qemu_macaddr_set_used(macaddr);
191             return;
192         }
193     }
194 
195     macaddr->a[0] = 0x52;
196     macaddr->a[1] = 0x54;
197     macaddr->a[2] = 0x00;
198     macaddr->a[3] = 0x12;
199     macaddr->a[4] = 0x34;
200     macaddr->a[5] = qemu_macaddr_get_free();
201     qemu_macaddr_set_used(macaddr);
202 }
203 
204 /**
205  * Generate a name for net client
206  *
207  * Only net clients created with the legacy -net option and NICs need this.
208  */
209 static char *assign_name(NetClientState *nc1, const char *model)
210 {
211     NetClientState *nc;
212     int id = 0;
213 
214     QTAILQ_FOREACH(nc, &net_clients, next) {
215         if (nc == nc1) {
216             continue;
217         }
218         if (strcmp(nc->model, model) == 0) {
219             id++;
220         }
221     }
222 
223     return g_strdup_printf("%s.%d", model, id);
224 }
225 
226 static void qemu_net_client_destructor(NetClientState *nc)
227 {
228     g_free(nc);
229 }
230 static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
231                                        unsigned flags,
232                                        const struct iovec *iov,
233                                        int iovcnt,
234                                        void *opaque);
235 
236 static void qemu_net_client_setup(NetClientState *nc,
237                                   NetClientInfo *info,
238                                   NetClientState *peer,
239                                   const char *model,
240                                   const char *name,
241                                   NetClientDestructor *destructor,
242                                   bool is_datapath)
243 {
244     nc->info = info;
245     nc->model = g_strdup(model);
246     if (name) {
247         nc->name = g_strdup(name);
248     } else {
249         nc->name = assign_name(nc, model);
250     }
251 
252     if (peer) {
253         assert(!peer->peer);
254         nc->peer = peer;
255         peer->peer = nc;
256     }
257     QTAILQ_INSERT_TAIL(&net_clients, nc, next);
258 
259     nc->incoming_queue = qemu_new_net_queue(qemu_deliver_packet_iov, nc);
260     nc->destructor = destructor;
261     nc->is_datapath = is_datapath;
262     QTAILQ_INIT(&nc->filters);
263 }
264 
265 NetClientState *qemu_new_net_client(NetClientInfo *info,
266                                     NetClientState *peer,
267                                     const char *model,
268                                     const char *name)
269 {
270     NetClientState *nc;
271 
272     assert(info->size >= sizeof(NetClientState));
273 
274     nc = g_malloc0(info->size);
275     qemu_net_client_setup(nc, info, peer, model, name,
276                           qemu_net_client_destructor, true);
277 
278     return nc;
279 }
280 
281 NetClientState *qemu_new_net_control_client(NetClientInfo *info,
282                                             NetClientState *peer,
283                                             const char *model,
284                                             const char *name)
285 {
286     NetClientState *nc;
287 
288     assert(info->size >= sizeof(NetClientState));
289 
290     nc = g_malloc0(info->size);
291     qemu_net_client_setup(nc, info, peer, model, name,
292                           qemu_net_client_destructor, false);
293 
294     return nc;
295 }
296 
297 NICState *qemu_new_nic(NetClientInfo *info,
298                        NICConf *conf,
299                        const char *model,
300                        const char *name,
301                        void *opaque)
302 {
303     NetClientState **peers = conf->peers.ncs;
304     NICState *nic;
305     int i, queues = MAX(1, conf->peers.queues);
306 
307     assert(info->type == NET_CLIENT_DRIVER_NIC);
308     assert(info->size >= sizeof(NICState));
309 
310     nic = g_malloc0(info->size + sizeof(NetClientState) * queues);
311     nic->ncs = (void *)nic + info->size;
312     nic->conf = conf;
313     nic->opaque = opaque;
314 
315     for (i = 0; i < queues; i++) {
316         qemu_net_client_setup(&nic->ncs[i], info, peers[i], model, name,
317                               NULL, true);
318         nic->ncs[i].queue_index = i;
319     }
320 
321     return nic;
322 }
323 
324 NetClientState *qemu_get_subqueue(NICState *nic, int queue_index)
325 {
326     return nic->ncs + queue_index;
327 }
328 
329 NetClientState *qemu_get_queue(NICState *nic)
330 {
331     return qemu_get_subqueue(nic, 0);
332 }
333 
334 NICState *qemu_get_nic(NetClientState *nc)
335 {
336     NetClientState *nc0 = nc - nc->queue_index;
337 
338     return (NICState *)((void *)nc0 - nc->info->size);
339 }
340 
341 void *qemu_get_nic_opaque(NetClientState *nc)
342 {
343     NICState *nic = qemu_get_nic(nc);
344 
345     return nic->opaque;
346 }
347 
348 NetClientState *qemu_get_peer(NetClientState *nc, int queue_index)
349 {
350     assert(nc != NULL);
351     NetClientState *ncs = nc + queue_index;
352     return ncs->peer;
353 }
354 
355 static void qemu_cleanup_net_client(NetClientState *nc)
356 {
357     QTAILQ_REMOVE(&net_clients, nc, next);
358 
359     if (nc->info->cleanup) {
360         nc->info->cleanup(nc);
361     }
362 }
363 
364 static void qemu_free_net_client(NetClientState *nc)
365 {
366     if (nc->incoming_queue) {
367         qemu_del_net_queue(nc->incoming_queue);
368     }
369     if (nc->peer) {
370         nc->peer->peer = NULL;
371     }
372     g_free(nc->name);
373     g_free(nc->model);
374     if (nc->destructor) {
375         nc->destructor(nc);
376     }
377 }
378 
379 void qemu_del_net_client(NetClientState *nc)
380 {
381     NetClientState *ncs[MAX_QUEUE_NUM];
382     int queues, i;
383     NetFilterState *nf, *next;
384 
385     assert(nc->info->type != NET_CLIENT_DRIVER_NIC);
386 
387     /* If the NetClientState belongs to a multiqueue backend, we will change all
388      * other NetClientStates also.
389      */
390     queues = qemu_find_net_clients_except(nc->name, ncs,
391                                           NET_CLIENT_DRIVER_NIC,
392                                           MAX_QUEUE_NUM);
393     assert(queues != 0);
394 
395     QTAILQ_FOREACH_SAFE(nf, &nc->filters, next, next) {
396         object_unparent(OBJECT(nf));
397     }
398 
399     /* If there is a peer NIC, delete and cleanup client, but do not free. */
400     if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
401         NICState *nic = qemu_get_nic(nc->peer);
402         if (nic->peer_deleted) {
403             return;
404         }
405         nic->peer_deleted = true;
406 
407         for (i = 0; i < queues; i++) {
408             ncs[i]->peer->link_down = true;
409         }
410 
411         if (nc->peer->info->link_status_changed) {
412             nc->peer->info->link_status_changed(nc->peer);
413         }
414 
415         for (i = 0; i < queues; i++) {
416             qemu_cleanup_net_client(ncs[i]);
417         }
418 
419         return;
420     }
421 
422     for (i = 0; i < queues; i++) {
423         qemu_cleanup_net_client(ncs[i]);
424         qemu_free_net_client(ncs[i]);
425     }
426 }
427 
428 void qemu_del_nic(NICState *nic)
429 {
430     int i, queues = MAX(nic->conf->peers.queues, 1);
431 
432     qemu_macaddr_set_free(&nic->conf->macaddr);
433 
434     for (i = 0; i < queues; i++) {
435         NetClientState *nc = qemu_get_subqueue(nic, i);
436         /* If this is a peer NIC and peer has already been deleted, free it now. */
437         if (nic->peer_deleted) {
438             qemu_free_net_client(nc->peer);
439         } else if (nc->peer) {
440             /* if there are RX packets pending, complete them */
441             qemu_purge_queued_packets(nc->peer);
442         }
443     }
444 
445     for (i = queues - 1; i >= 0; i--) {
446         NetClientState *nc = qemu_get_subqueue(nic, i);
447 
448         qemu_cleanup_net_client(nc);
449         qemu_free_net_client(nc);
450     }
451 
452     g_free(nic);
453 }
454 
455 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
456 {
457     NetClientState *nc;
458 
459     QTAILQ_FOREACH(nc, &net_clients, next) {
460         if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
461             if (nc->queue_index == 0) {
462                 func(qemu_get_nic(nc), opaque);
463             }
464         }
465     }
466 }
467 
468 bool qemu_has_ufo(NetClientState *nc)
469 {
470     if (!nc || !nc->info->has_ufo) {
471         return false;
472     }
473 
474     return nc->info->has_ufo(nc);
475 }
476 
477 bool qemu_has_vnet_hdr(NetClientState *nc)
478 {
479     if (!nc || !nc->info->has_vnet_hdr) {
480         return false;
481     }
482 
483     return nc->info->has_vnet_hdr(nc);
484 }
485 
486 bool qemu_has_vnet_hdr_len(NetClientState *nc, int len)
487 {
488     if (!nc || !nc->info->has_vnet_hdr_len) {
489         return false;
490     }
491 
492     return nc->info->has_vnet_hdr_len(nc, len);
493 }
494 
495 void qemu_using_vnet_hdr(NetClientState *nc, bool enable)
496 {
497     if (!nc || !nc->info->using_vnet_hdr) {
498         return;
499     }
500 
501     nc->info->using_vnet_hdr(nc, enable);
502 }
503 
504 void qemu_set_offload(NetClientState *nc, int csum, int tso4, int tso6,
505                           int ecn, int ufo)
506 {
507     if (!nc || !nc->info->set_offload) {
508         return;
509     }
510 
511     nc->info->set_offload(nc, csum, tso4, tso6, ecn, ufo);
512 }
513 
514 void qemu_set_vnet_hdr_len(NetClientState *nc, int len)
515 {
516     if (!nc || !nc->info->set_vnet_hdr_len) {
517         return;
518     }
519 
520     nc->vnet_hdr_len = len;
521     nc->info->set_vnet_hdr_len(nc, len);
522 }
523 
524 int qemu_set_vnet_le(NetClientState *nc, bool is_le)
525 {
526 #if HOST_BIG_ENDIAN
527     if (!nc || !nc->info->set_vnet_le) {
528         return -ENOSYS;
529     }
530 
531     return nc->info->set_vnet_le(nc, is_le);
532 #else
533     return 0;
534 #endif
535 }
536 
537 int qemu_set_vnet_be(NetClientState *nc, bool is_be)
538 {
539 #if HOST_BIG_ENDIAN
540     return 0;
541 #else
542     if (!nc || !nc->info->set_vnet_be) {
543         return -ENOSYS;
544     }
545 
546     return nc->info->set_vnet_be(nc, is_be);
547 #endif
548 }
549 
550 int qemu_can_receive_packet(NetClientState *nc)
551 {
552     if (nc->receive_disabled) {
553         return 0;
554     } else if (nc->info->can_receive &&
555                !nc->info->can_receive(nc)) {
556         return 0;
557     }
558     return 1;
559 }
560 
561 int qemu_can_send_packet(NetClientState *sender)
562 {
563     int vm_running = runstate_is_running();
564 
565     if (!vm_running) {
566         return 0;
567     }
568 
569     if (!sender->peer) {
570         return 1;
571     }
572 
573     return qemu_can_receive_packet(sender->peer);
574 }
575 
576 static ssize_t filter_receive_iov(NetClientState *nc,
577                                   NetFilterDirection direction,
578                                   NetClientState *sender,
579                                   unsigned flags,
580                                   const struct iovec *iov,
581                                   int iovcnt,
582                                   NetPacketSent *sent_cb)
583 {
584     ssize_t ret = 0;
585     NetFilterState *nf = NULL;
586 
587     if (direction == NET_FILTER_DIRECTION_TX) {
588         QTAILQ_FOREACH(nf, &nc->filters, next) {
589             ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
590                                          iovcnt, sent_cb);
591             if (ret) {
592                 return ret;
593             }
594         }
595     } else {
596         QTAILQ_FOREACH_REVERSE(nf, &nc->filters, next) {
597             ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
598                                          iovcnt, sent_cb);
599             if (ret) {
600                 return ret;
601             }
602         }
603     }
604 
605     return ret;
606 }
607 
608 static ssize_t filter_receive(NetClientState *nc,
609                               NetFilterDirection direction,
610                               NetClientState *sender,
611                               unsigned flags,
612                               const uint8_t *data,
613                               size_t size,
614                               NetPacketSent *sent_cb)
615 {
616     struct iovec iov = {
617         .iov_base = (void *)data,
618         .iov_len = size
619     };
620 
621     return filter_receive_iov(nc, direction, sender, flags, &iov, 1, sent_cb);
622 }
623 
624 void qemu_purge_queued_packets(NetClientState *nc)
625 {
626     if (!nc->peer) {
627         return;
628     }
629 
630     qemu_net_queue_purge(nc->peer->incoming_queue, nc);
631 }
632 
633 void qemu_flush_or_purge_queued_packets(NetClientState *nc, bool purge)
634 {
635     nc->receive_disabled = 0;
636 
637     if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_HUBPORT) {
638         if (net_hub_flush(nc->peer)) {
639             qemu_notify_event();
640         }
641     }
642     if (qemu_net_queue_flush(nc->incoming_queue)) {
643         /* We emptied the queue successfully, signal to the IO thread to repoll
644          * the file descriptor (for tap, for example).
645          */
646         qemu_notify_event();
647     } else if (purge) {
648         /* Unable to empty the queue, purge remaining packets */
649         qemu_net_queue_purge(nc->incoming_queue, nc->peer);
650     }
651 }
652 
653 void qemu_flush_queued_packets(NetClientState *nc)
654 {
655     qemu_flush_or_purge_queued_packets(nc, false);
656 }
657 
658 static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
659                                                  unsigned flags,
660                                                  const uint8_t *buf, int size,
661                                                  NetPacketSent *sent_cb)
662 {
663     NetQueue *queue;
664     int ret;
665 
666 #ifdef DEBUG_NET
667     printf("qemu_send_packet_async:\n");
668     qemu_hexdump(stdout, "net", buf, size);
669 #endif
670 
671     if (sender->link_down || !sender->peer) {
672         return size;
673     }
674 
675     /* Let filters handle the packet first */
676     ret = filter_receive(sender, NET_FILTER_DIRECTION_TX,
677                          sender, flags, buf, size, sent_cb);
678     if (ret) {
679         return ret;
680     }
681 
682     ret = filter_receive(sender->peer, NET_FILTER_DIRECTION_RX,
683                          sender, flags, buf, size, sent_cb);
684     if (ret) {
685         return ret;
686     }
687 
688     queue = sender->peer->incoming_queue;
689 
690     return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
691 }
692 
693 ssize_t qemu_send_packet_async(NetClientState *sender,
694                                const uint8_t *buf, int size,
695                                NetPacketSent *sent_cb)
696 {
697     return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
698                                              buf, size, sent_cb);
699 }
700 
701 ssize_t qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size)
702 {
703     return qemu_send_packet_async(nc, buf, size, NULL);
704 }
705 
706 ssize_t qemu_receive_packet(NetClientState *nc, const uint8_t *buf, int size)
707 {
708     if (!qemu_can_receive_packet(nc)) {
709         return 0;
710     }
711 
712     return qemu_net_queue_receive(nc->incoming_queue, buf, size);
713 }
714 
715 ssize_t qemu_receive_packet_iov(NetClientState *nc, const struct iovec *iov,
716                                 int iovcnt)
717 {
718     if (!qemu_can_receive_packet(nc)) {
719         return 0;
720     }
721 
722     return qemu_net_queue_receive_iov(nc->incoming_queue, iov, iovcnt);
723 }
724 
725 ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size)
726 {
727     return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW,
728                                              buf, size, NULL);
729 }
730 
731 static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
732                                int iovcnt, unsigned flags)
733 {
734     uint8_t *buf = NULL;
735     uint8_t *buffer;
736     size_t offset;
737     ssize_t ret;
738 
739     if (iovcnt == 1) {
740         buffer = iov[0].iov_base;
741         offset = iov[0].iov_len;
742     } else {
743         offset = iov_size(iov, iovcnt);
744         if (offset > NET_BUFSIZE) {
745             return -1;
746         }
747         buf = g_malloc(offset);
748         buffer = buf;
749         offset = iov_to_buf(iov, iovcnt, 0, buf, offset);
750     }
751 
752     if (flags & QEMU_NET_PACKET_FLAG_RAW && nc->info->receive_raw) {
753         ret = nc->info->receive_raw(nc, buffer, offset);
754     } else {
755         ret = nc->info->receive(nc, buffer, offset);
756     }
757 
758     g_free(buf);
759     return ret;
760 }
761 
762 static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
763                                        unsigned flags,
764                                        const struct iovec *iov,
765                                        int iovcnt,
766                                        void *opaque)
767 {
768     NetClientState *nc = opaque;
769     int ret;
770 
771 
772     if (nc->link_down) {
773         return iov_size(iov, iovcnt);
774     }
775 
776     if (nc->receive_disabled) {
777         return 0;
778     }
779 
780     if (nc->info->receive_iov && !(flags & QEMU_NET_PACKET_FLAG_RAW)) {
781         ret = nc->info->receive_iov(nc, iov, iovcnt);
782     } else {
783         ret = nc_sendv_compat(nc, iov, iovcnt, flags);
784     }
785 
786     if (ret == 0) {
787         nc->receive_disabled = 1;
788     }
789 
790     return ret;
791 }
792 
793 ssize_t qemu_sendv_packet_async(NetClientState *sender,
794                                 const struct iovec *iov, int iovcnt,
795                                 NetPacketSent *sent_cb)
796 {
797     NetQueue *queue;
798     size_t size = iov_size(iov, iovcnt);
799     int ret;
800 
801     if (size > NET_BUFSIZE) {
802         return size;
803     }
804 
805     if (sender->link_down || !sender->peer) {
806         return size;
807     }
808 
809     /* Let filters handle the packet first */
810     ret = filter_receive_iov(sender, NET_FILTER_DIRECTION_TX, sender,
811                              QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
812     if (ret) {
813         return ret;
814     }
815 
816     ret = filter_receive_iov(sender->peer, NET_FILTER_DIRECTION_RX, sender,
817                              QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
818     if (ret) {
819         return ret;
820     }
821 
822     queue = sender->peer->incoming_queue;
823 
824     return qemu_net_queue_send_iov(queue, sender,
825                                    QEMU_NET_PACKET_FLAG_NONE,
826                                    iov, iovcnt, sent_cb);
827 }
828 
829 ssize_t
830 qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt)
831 {
832     return qemu_sendv_packet_async(nc, iov, iovcnt, NULL);
833 }
834 
835 NetClientState *qemu_find_netdev(const char *id)
836 {
837     NetClientState *nc;
838 
839     QTAILQ_FOREACH(nc, &net_clients, next) {
840         if (nc->info->type == NET_CLIENT_DRIVER_NIC)
841             continue;
842         if (!strcmp(nc->name, id)) {
843             return nc;
844         }
845     }
846 
847     return NULL;
848 }
849 
850 int qemu_find_net_clients_except(const char *id, NetClientState **ncs,
851                                  NetClientDriver type, int max)
852 {
853     NetClientState *nc;
854     int ret = 0;
855 
856     QTAILQ_FOREACH(nc, &net_clients, next) {
857         if (nc->info->type == type) {
858             continue;
859         }
860         if (!id || !strcmp(nc->name, id)) {
861             if (ret < max) {
862                 ncs[ret] = nc;
863             }
864             ret++;
865         }
866     }
867 
868     return ret;
869 }
870 
871 static int nic_get_free_idx(void)
872 {
873     int index;
874 
875     for (index = 0; index < MAX_NICS; index++)
876         if (!nd_table[index].used)
877             return index;
878     return -1;
879 }
880 
881 int qemu_show_nic_models(const char *arg, const char *const *models)
882 {
883     int i;
884 
885     if (!arg || !is_help_option(arg)) {
886         return 0;
887     }
888 
889     printf("Supported NIC models:\n");
890     for (i = 0 ; models[i]; i++) {
891         printf("%s\n", models[i]);
892     }
893     return 1;
894 }
895 
896 void qemu_check_nic_model(NICInfo *nd, const char *model)
897 {
898     const char *models[2];
899 
900     models[0] = model;
901     models[1] = NULL;
902 
903     if (qemu_show_nic_models(nd->model, models))
904         exit(0);
905     if (qemu_find_nic_model(nd, models, model) < 0)
906         exit(1);
907 }
908 
909 int qemu_find_nic_model(NICInfo *nd, const char * const *models,
910                         const char *default_model)
911 {
912     int i;
913 
914     if (!nd->model)
915         nd->model = g_strdup(default_model);
916 
917     for (i = 0 ; models[i]; i++) {
918         if (strcmp(nd->model, models[i]) == 0)
919             return i;
920     }
921 
922     error_report("Unsupported NIC model: %s", nd->model);
923     return -1;
924 }
925 
926 static int net_init_nic(const Netdev *netdev, const char *name,
927                         NetClientState *peer, Error **errp)
928 {
929     int idx;
930     NICInfo *nd;
931     const NetLegacyNicOptions *nic;
932 
933     assert(netdev->type == NET_CLIENT_DRIVER_NIC);
934     nic = &netdev->u.nic;
935 
936     idx = nic_get_free_idx();
937     if (idx == -1 || nb_nics >= MAX_NICS) {
938         error_setg(errp, "too many NICs");
939         return -1;
940     }
941 
942     nd = &nd_table[idx];
943 
944     memset(nd, 0, sizeof(*nd));
945 
946     if (nic->has_netdev) {
947         nd->netdev = qemu_find_netdev(nic->netdev);
948         if (!nd->netdev) {
949             error_setg(errp, "netdev '%s' not found", nic->netdev);
950             return -1;
951         }
952     } else {
953         assert(peer);
954         nd->netdev = peer;
955     }
956     nd->name = g_strdup(name);
957     if (nic->has_model) {
958         nd->model = g_strdup(nic->model);
959     }
960     if (nic->has_addr) {
961         nd->devaddr = g_strdup(nic->addr);
962     }
963 
964     if (nic->has_macaddr &&
965         net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {
966         error_setg(errp, "invalid syntax for ethernet address");
967         return -1;
968     }
969     if (nic->has_macaddr &&
970         is_multicast_ether_addr(nd->macaddr.a)) {
971         error_setg(errp,
972                    "NIC cannot have multicast MAC address (odd 1st byte)");
973         return -1;
974     }
975     qemu_macaddr_default_if_unset(&nd->macaddr);
976 
977     if (nic->has_vectors) {
978         if (nic->vectors > 0x7ffffff) {
979             error_setg(errp, "invalid # of vectors: %"PRIu32, nic->vectors);
980             return -1;
981         }
982         nd->nvectors = nic->vectors;
983     } else {
984         nd->nvectors = DEV_NVECTORS_UNSPECIFIED;
985     }
986 
987     nd->used = 1;
988     nb_nics++;
989 
990     return idx;
991 }
992 
993 
994 static int (* const net_client_init_fun[NET_CLIENT_DRIVER__MAX])(
995     const Netdev *netdev,
996     const char *name,
997     NetClientState *peer, Error **errp) = {
998         [NET_CLIENT_DRIVER_NIC]       = net_init_nic,
999 #ifdef CONFIG_SLIRP
1000         [NET_CLIENT_DRIVER_USER]      = net_init_slirp,
1001 #endif
1002         [NET_CLIENT_DRIVER_TAP]       = net_init_tap,
1003         [NET_CLIENT_DRIVER_SOCKET]    = net_init_socket,
1004 #ifdef CONFIG_VDE
1005         [NET_CLIENT_DRIVER_VDE]       = net_init_vde,
1006 #endif
1007 #ifdef CONFIG_NETMAP
1008         [NET_CLIENT_DRIVER_NETMAP]    = net_init_netmap,
1009 #endif
1010 #ifdef CONFIG_NET_BRIDGE
1011         [NET_CLIENT_DRIVER_BRIDGE]    = net_init_bridge,
1012 #endif
1013         [NET_CLIENT_DRIVER_HUBPORT]   = net_init_hubport,
1014 #ifdef CONFIG_VHOST_NET_USER
1015         [NET_CLIENT_DRIVER_VHOST_USER] = net_init_vhost_user,
1016 #endif
1017 #ifdef CONFIG_VHOST_NET_VDPA
1018         [NET_CLIENT_DRIVER_VHOST_VDPA] = net_init_vhost_vdpa,
1019 #endif
1020 #ifdef CONFIG_L2TPV3
1021         [NET_CLIENT_DRIVER_L2TPV3]    = net_init_l2tpv3,
1022 #endif
1023 };
1024 
1025 
1026 static int net_client_init1(const Netdev *netdev, bool is_netdev, Error **errp)
1027 {
1028     NetClientState *peer = NULL;
1029     NetClientState *nc;
1030 
1031     if (is_netdev) {
1032         if (netdev->type == NET_CLIENT_DRIVER_NIC ||
1033             !net_client_init_fun[netdev->type]) {
1034             error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
1035                        "a netdev backend type");
1036             return -1;
1037         }
1038     } else {
1039         if (netdev->type == NET_CLIENT_DRIVER_NONE) {
1040             return 0; /* nothing to do */
1041         }
1042         if (netdev->type == NET_CLIENT_DRIVER_HUBPORT ||
1043             !net_client_init_fun[netdev->type]) {
1044             error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
1045                        "a net backend type (maybe it is not compiled "
1046                        "into this binary)");
1047             return -1;
1048         }
1049 
1050         /* Do not add to a hub if it's a nic with a netdev= parameter. */
1051         if (netdev->type != NET_CLIENT_DRIVER_NIC ||
1052             !netdev->u.nic.has_netdev) {
1053             peer = net_hub_add_port(0, NULL, NULL);
1054         }
1055     }
1056 
1057     nc = qemu_find_netdev(netdev->id);
1058     if (nc) {
1059         error_setg(errp, "Duplicate ID '%s'", netdev->id);
1060         return -1;
1061     }
1062 
1063     if (net_client_init_fun[netdev->type](netdev, netdev->id, peer, errp) < 0) {
1064         /* FIXME drop when all init functions store an Error */
1065         if (errp && !*errp) {
1066             error_setg(errp, "Device '%s' could not be initialized",
1067                        NetClientDriver_str(netdev->type));
1068         }
1069         return -1;
1070     }
1071 
1072     if (is_netdev) {
1073         nc = qemu_find_netdev(netdev->id);
1074         assert(nc);
1075         nc->is_netdev = true;
1076     }
1077 
1078     return 0;
1079 }
1080 
1081 void show_netdevs(void)
1082 {
1083     int idx;
1084     const char *available_netdevs[] = {
1085         "socket",
1086         "hubport",
1087         "tap",
1088 #ifdef CONFIG_SLIRP
1089         "user",
1090 #endif
1091 #ifdef CONFIG_L2TPV3
1092         "l2tpv3",
1093 #endif
1094 #ifdef CONFIG_VDE
1095         "vde",
1096 #endif
1097 #ifdef CONFIG_NET_BRIDGE
1098         "bridge",
1099 #endif
1100 #ifdef CONFIG_NETMAP
1101         "netmap",
1102 #endif
1103 #ifdef CONFIG_POSIX
1104         "vhost-user",
1105 #endif
1106 #ifdef CONFIG_VHOST_VDPA
1107         "vhost-vdpa",
1108 #endif
1109     };
1110 
1111     qemu_printf("Available netdev backend types:\n");
1112     for (idx = 0; idx < ARRAY_SIZE(available_netdevs); idx++) {
1113         qemu_printf("%s\n", available_netdevs[idx]);
1114     }
1115 }
1116 
1117 static int net_client_init(QemuOpts *opts, bool is_netdev, Error **errp)
1118 {
1119     gchar **substrings = NULL;
1120     Netdev *object = NULL;
1121     int ret = -1;
1122     Visitor *v = opts_visitor_new(opts);
1123 
1124     /* Parse convenience option format ip6-net=fec0::0[/64] */
1125     const char *ip6_net = qemu_opt_get(opts, "ipv6-net");
1126 
1127     if (ip6_net) {
1128         char *prefix_addr;
1129         unsigned long prefix_len = 64; /* Default 64bit prefix length. */
1130 
1131         substrings = g_strsplit(ip6_net, "/", 2);
1132         if (!substrings || !substrings[0]) {
1133             error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "ipv6-net",
1134                        "a valid IPv6 prefix");
1135             goto out;
1136         }
1137 
1138         prefix_addr = substrings[0];
1139 
1140         /* Handle user-specified prefix length. */
1141         if (substrings[1] &&
1142             qemu_strtoul(substrings[1], NULL, 10, &prefix_len))
1143         {
1144             error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1145                        "ipv6-prefixlen", "a number");
1146             goto out;
1147         }
1148 
1149         qemu_opt_set(opts, "ipv6-prefix", prefix_addr, &error_abort);
1150         qemu_opt_set_number(opts, "ipv6-prefixlen", prefix_len,
1151                             &error_abort);
1152         qemu_opt_unset(opts, "ipv6-net");
1153     }
1154 
1155     /* Create an ID for -net if the user did not specify one */
1156     if (!is_netdev && !qemu_opts_id(opts)) {
1157         qemu_opts_set_id(opts, id_generate(ID_NET));
1158     }
1159 
1160     if (visit_type_Netdev(v, NULL, &object, errp)) {
1161         ret = net_client_init1(object, is_netdev, errp);
1162     }
1163 
1164     qapi_free_Netdev(object);
1165 
1166 out:
1167     g_strfreev(substrings);
1168     visit_free(v);
1169     return ret;
1170 }
1171 
1172 void netdev_add(QemuOpts *opts, Error **errp)
1173 {
1174     net_client_init(opts, true, errp);
1175 }
1176 
1177 void qmp_netdev_add(Netdev *netdev, Error **errp)
1178 {
1179     if (!id_wellformed(netdev->id)) {
1180         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "id", "an identifier");
1181         return;
1182     }
1183 
1184     net_client_init1(netdev, true, errp);
1185 }
1186 
1187 void qmp_netdev_del(const char *id, Error **errp)
1188 {
1189     NetClientState *nc;
1190     QemuOpts *opts;
1191 
1192     nc = qemu_find_netdev(id);
1193     if (!nc) {
1194         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1195                   "Device '%s' not found", id);
1196         return;
1197     }
1198 
1199     if (!nc->is_netdev) {
1200         error_setg(errp, "Device '%s' is not a netdev", id);
1201         return;
1202     }
1203 
1204     qemu_del_net_client(nc);
1205 
1206     /*
1207      * Wart: we need to delete the QemuOpts associated with netdevs
1208      * created via CLI or HMP, to avoid bogus "Duplicate ID" errors in
1209      * HMP netdev_add.
1210      */
1211     opts = qemu_opts_find(qemu_find_opts("netdev"), id);
1212     if (opts) {
1213         qemu_opts_del(opts);
1214     }
1215 }
1216 
1217 static void netfilter_print_info(Monitor *mon, NetFilterState *nf)
1218 {
1219     char *str;
1220     ObjectProperty *prop;
1221     ObjectPropertyIterator iter;
1222     Visitor *v;
1223 
1224     /* generate info str */
1225     object_property_iter_init(&iter, OBJECT(nf));
1226     while ((prop = object_property_iter_next(&iter))) {
1227         if (!strcmp(prop->name, "type")) {
1228             continue;
1229         }
1230         v = string_output_visitor_new(false, &str);
1231         object_property_get(OBJECT(nf), prop->name, v, NULL);
1232         visit_complete(v, &str);
1233         visit_free(v);
1234         monitor_printf(mon, ",%s=%s", prop->name, str);
1235         g_free(str);
1236     }
1237     monitor_printf(mon, "\n");
1238 }
1239 
1240 void print_net_client(Monitor *mon, NetClientState *nc)
1241 {
1242     NetFilterState *nf;
1243 
1244     monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
1245                    nc->queue_index,
1246                    NetClientDriver_str(nc->info->type),
1247                    nc->info_str);
1248     if (!QTAILQ_EMPTY(&nc->filters)) {
1249         monitor_printf(mon, "filters:\n");
1250     }
1251     QTAILQ_FOREACH(nf, &nc->filters, next) {
1252         monitor_printf(mon, "  - %s: type=%s",
1253                        object_get_canonical_path_component(OBJECT(nf)),
1254                        object_get_typename(OBJECT(nf)));
1255         netfilter_print_info(mon, nf);
1256     }
1257 }
1258 
1259 RxFilterInfoList *qmp_query_rx_filter(bool has_name, const char *name,
1260                                       Error **errp)
1261 {
1262     NetClientState *nc;
1263     RxFilterInfoList *filter_list = NULL, **tail = &filter_list;
1264 
1265     QTAILQ_FOREACH(nc, &net_clients, next) {
1266         RxFilterInfo *info;
1267 
1268         if (has_name && strcmp(nc->name, name) != 0) {
1269             continue;
1270         }
1271 
1272         /* only query rx-filter information of NIC */
1273         if (nc->info->type != NET_CLIENT_DRIVER_NIC) {
1274             if (has_name) {
1275                 error_setg(errp, "net client(%s) isn't a NIC", name);
1276                 assert(!filter_list);
1277                 return NULL;
1278             }
1279             continue;
1280         }
1281 
1282         /* only query information on queue 0 since the info is per nic,
1283          * not per queue
1284          */
1285         if (nc->queue_index != 0)
1286             continue;
1287 
1288         if (nc->info->query_rx_filter) {
1289             info = nc->info->query_rx_filter(nc);
1290             QAPI_LIST_APPEND(tail, info);
1291         } else if (has_name) {
1292             error_setg(errp, "net client(%s) doesn't support"
1293                        " rx-filter querying", name);
1294             assert(!filter_list);
1295             return NULL;
1296         }
1297 
1298         if (has_name) {
1299             break;
1300         }
1301     }
1302 
1303     if (filter_list == NULL && has_name) {
1304         error_setg(errp, "invalid net client name: %s", name);
1305     }
1306 
1307     return filter_list;
1308 }
1309 
1310 void hmp_info_network(Monitor *mon, const QDict *qdict)
1311 {
1312     NetClientState *nc, *peer;
1313     NetClientDriver type;
1314 
1315     net_hub_info(mon);
1316 
1317     QTAILQ_FOREACH(nc, &net_clients, next) {
1318         peer = nc->peer;
1319         type = nc->info->type;
1320 
1321         /* Skip if already printed in hub info */
1322         if (net_hub_id_for_client(nc, NULL) == 0) {
1323             continue;
1324         }
1325 
1326         if (!peer || type == NET_CLIENT_DRIVER_NIC) {
1327             print_net_client(mon, nc);
1328         } /* else it's a netdev connected to a NIC, printed with the NIC */
1329         if (peer && type == NET_CLIENT_DRIVER_NIC) {
1330             monitor_printf(mon, " \\ ");
1331             print_net_client(mon, peer);
1332         }
1333     }
1334 }
1335 
1336 void colo_notify_filters_event(int event, Error **errp)
1337 {
1338     NetClientState *nc;
1339     NetFilterState *nf;
1340     NetFilterClass *nfc = NULL;
1341     Error *local_err = NULL;
1342 
1343     QTAILQ_FOREACH(nc, &net_clients, next) {
1344         QTAILQ_FOREACH(nf, &nc->filters, next) {
1345             nfc = NETFILTER_GET_CLASS(OBJECT(nf));
1346             nfc->handle_event(nf, event, &local_err);
1347             if (local_err) {
1348                 error_propagate(errp, local_err);
1349                 return;
1350             }
1351         }
1352     }
1353 }
1354 
1355 void qmp_set_link(const char *name, bool up, Error **errp)
1356 {
1357     NetClientState *ncs[MAX_QUEUE_NUM];
1358     NetClientState *nc;
1359     int queues, i;
1360 
1361     queues = qemu_find_net_clients_except(name, ncs,
1362                                           NET_CLIENT_DRIVER__MAX,
1363                                           MAX_QUEUE_NUM);
1364 
1365     if (queues == 0) {
1366         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1367                   "Device '%s' not found", name);
1368         return;
1369     }
1370     nc = ncs[0];
1371 
1372     for (i = 0; i < queues; i++) {
1373         ncs[i]->link_down = !up;
1374     }
1375 
1376     if (nc->info->link_status_changed) {
1377         nc->info->link_status_changed(nc);
1378     }
1379 
1380     if (nc->peer) {
1381         /* Change peer link only if the peer is NIC and then notify peer.
1382          * If the peer is a HUBPORT or a backend, we do not change the
1383          * link status.
1384          *
1385          * This behavior is compatible with qemu hubs where there could be
1386          * multiple clients that can still communicate with each other in
1387          * disconnected mode. For now maintain this compatibility.
1388          */
1389         if (nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
1390             for (i = 0; i < queues; i++) {
1391                 ncs[i]->peer->link_down = !up;
1392             }
1393         }
1394         if (nc->peer->info->link_status_changed) {
1395             nc->peer->info->link_status_changed(nc->peer);
1396         }
1397     }
1398 }
1399 
1400 static void net_vm_change_state_handler(void *opaque, bool running,
1401                                         RunState state)
1402 {
1403     NetClientState *nc;
1404     NetClientState *tmp;
1405 
1406     QTAILQ_FOREACH_SAFE(nc, &net_clients, next, tmp) {
1407         if (running) {
1408             /* Flush queued packets and wake up backends. */
1409             if (nc->peer && qemu_can_send_packet(nc)) {
1410                 qemu_flush_queued_packets(nc->peer);
1411             }
1412         } else {
1413             /* Complete all queued packets, to guarantee we don't modify
1414              * state later when VM is not running.
1415              */
1416             qemu_flush_or_purge_queued_packets(nc, true);
1417         }
1418     }
1419 }
1420 
1421 void net_cleanup(void)
1422 {
1423     NetClientState *nc;
1424 
1425     /*cleanup colo compare module for COLO*/
1426     colo_compare_cleanup();
1427 
1428     /* We may del multiple entries during qemu_del_net_client(),
1429      * so QTAILQ_FOREACH_SAFE() is also not safe here.
1430      */
1431     while (!QTAILQ_EMPTY(&net_clients)) {
1432         nc = QTAILQ_FIRST(&net_clients);
1433         if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
1434             qemu_del_nic(qemu_get_nic(nc));
1435         } else {
1436             qemu_del_net_client(nc);
1437         }
1438     }
1439 
1440     qemu_del_vm_change_state_handler(net_change_state_entry);
1441 }
1442 
1443 void net_check_clients(void)
1444 {
1445     NetClientState *nc;
1446     int i;
1447 
1448     net_hub_check_clients();
1449 
1450     QTAILQ_FOREACH(nc, &net_clients, next) {
1451         if (!nc->peer) {
1452             warn_report("%s %s has no peer",
1453                         nc->info->type == NET_CLIENT_DRIVER_NIC
1454                         ? "nic" : "netdev",
1455                         nc->name);
1456         }
1457     }
1458 
1459     /* Check that all NICs requested via -net nic actually got created.
1460      * NICs created via -device don't need to be checked here because
1461      * they are always instantiated.
1462      */
1463     for (i = 0; i < MAX_NICS; i++) {
1464         NICInfo *nd = &nd_table[i];
1465         if (nd->used && !nd->instantiated) {
1466             warn_report("requested NIC (%s, model %s) "
1467                         "was not created (not supported by this machine?)",
1468                         nd->name ? nd->name : "anonymous",
1469                         nd->model ? nd->model : "unspecified");
1470         }
1471     }
1472 }
1473 
1474 static int net_init_client(void *dummy, QemuOpts *opts, Error **errp)
1475 {
1476     return net_client_init(opts, false, errp);
1477 }
1478 
1479 static int net_init_netdev(void *dummy, QemuOpts *opts, Error **errp)
1480 {
1481     const char *type = qemu_opt_get(opts, "type");
1482 
1483     if (type && is_help_option(type)) {
1484         show_netdevs();
1485         exit(0);
1486     }
1487     return net_client_init(opts, true, errp);
1488 }
1489 
1490 /* For the convenience "--nic" parameter */
1491 static int net_param_nic(void *dummy, QemuOpts *opts, Error **errp)
1492 {
1493     char *mac, *nd_id;
1494     int idx, ret;
1495     NICInfo *ni;
1496     const char *type;
1497 
1498     type = qemu_opt_get(opts, "type");
1499     if (type && g_str_equal(type, "none")) {
1500         return 0;    /* Nothing to do, default_net is cleared in vl.c */
1501     }
1502 
1503     idx = nic_get_free_idx();
1504     if (idx == -1 || nb_nics >= MAX_NICS) {
1505         error_setg(errp, "no more on-board/default NIC slots available");
1506         return -1;
1507     }
1508 
1509     if (!type) {
1510         qemu_opt_set(opts, "type", "user", &error_abort);
1511     }
1512 
1513     ni = &nd_table[idx];
1514     memset(ni, 0, sizeof(*ni));
1515     ni->model = qemu_opt_get_del(opts, "model");
1516 
1517     /* Create an ID if the user did not specify one */
1518     nd_id = g_strdup(qemu_opts_id(opts));
1519     if (!nd_id) {
1520         nd_id = id_generate(ID_NET);
1521         qemu_opts_set_id(opts, nd_id);
1522     }
1523 
1524     /* Handle MAC address */
1525     mac = qemu_opt_get_del(opts, "mac");
1526     if (mac) {
1527         ret = net_parse_macaddr(ni->macaddr.a, mac);
1528         g_free(mac);
1529         if (ret) {
1530             error_setg(errp, "invalid syntax for ethernet address");
1531             goto out;
1532         }
1533         if (is_multicast_ether_addr(ni->macaddr.a)) {
1534             error_setg(errp, "NIC cannot have multicast MAC address");
1535             ret = -1;
1536             goto out;
1537         }
1538     }
1539     qemu_macaddr_default_if_unset(&ni->macaddr);
1540 
1541     ret = net_client_init(opts, true, errp);
1542     if (ret == 0) {
1543         ni->netdev = qemu_find_netdev(nd_id);
1544         ni->used = true;
1545         nb_nics++;
1546     }
1547 
1548 out:
1549     g_free(nd_id);
1550     return ret;
1551 }
1552 
1553 int net_init_clients(Error **errp)
1554 {
1555     net_change_state_entry =
1556         qemu_add_vm_change_state_handler(net_vm_change_state_handler, NULL);
1557 
1558     QTAILQ_INIT(&net_clients);
1559 
1560     if (qemu_opts_foreach(qemu_find_opts("netdev"),
1561                           net_init_netdev, NULL, errp)) {
1562         return -1;
1563     }
1564 
1565     if (qemu_opts_foreach(qemu_find_opts("nic"), net_param_nic, NULL, errp)) {
1566         return -1;
1567     }
1568 
1569     if (qemu_opts_foreach(qemu_find_opts("net"), net_init_client, NULL, errp)) {
1570         return -1;
1571     }
1572 
1573     return 0;
1574 }
1575 
1576 int net_client_parse(QemuOptsList *opts_list, const char *optarg)
1577 {
1578     if (!qemu_opts_parse_noisily(opts_list, optarg, true)) {
1579         return -1;
1580     }
1581 
1582     return 0;
1583 }
1584 
1585 /* From FreeBSD */
1586 /* XXX: optimize */
1587 uint32_t net_crc32(const uint8_t *p, int len)
1588 {
1589     uint32_t crc;
1590     int carry, i, j;
1591     uint8_t b;
1592 
1593     crc = 0xffffffff;
1594     for (i = 0; i < len; i++) {
1595         b = *p++;
1596         for (j = 0; j < 8; j++) {
1597             carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
1598             crc <<= 1;
1599             b >>= 1;
1600             if (carry) {
1601                 crc = ((crc ^ POLYNOMIAL_BE) | carry);
1602             }
1603         }
1604     }
1605 
1606     return crc;
1607 }
1608 
1609 uint32_t net_crc32_le(const uint8_t *p, int len)
1610 {
1611     uint32_t crc;
1612     int carry, i, j;
1613     uint8_t b;
1614 
1615     crc = 0xffffffff;
1616     for (i = 0; i < len; i++) {
1617         b = *p++;
1618         for (j = 0; j < 8; j++) {
1619             carry = (crc & 0x1) ^ (b & 0x01);
1620             crc >>= 1;
1621             b >>= 1;
1622             if (carry) {
1623                 crc ^= POLYNOMIAL_LE;
1624             }
1625         }
1626     }
1627 
1628     return crc;
1629 }
1630 
1631 QemuOptsList qemu_netdev_opts = {
1632     .name = "netdev",
1633     .implied_opt_name = "type",
1634     .head = QTAILQ_HEAD_INITIALIZER(qemu_netdev_opts.head),
1635     .desc = {
1636         /*
1637          * no elements => accept any params
1638          * validation will happen later
1639          */
1640         { /* end of list */ }
1641     },
1642 };
1643 
1644 QemuOptsList qemu_nic_opts = {
1645     .name = "nic",
1646     .implied_opt_name = "type",
1647     .head = QTAILQ_HEAD_INITIALIZER(qemu_nic_opts.head),
1648     .desc = {
1649         /*
1650          * no elements => accept any params
1651          * validation will happen later
1652          */
1653         { /* end of list */ }
1654     },
1655 };
1656 
1657 QemuOptsList qemu_net_opts = {
1658     .name = "net",
1659     .implied_opt_name = "type",
1660     .head = QTAILQ_HEAD_INITIALIZER(qemu_net_opts.head),
1661     .desc = {
1662         /*
1663          * no elements => accept any params
1664          * validation will happen later
1665          */
1666         { /* end of list */ }
1667     },
1668 };
1669 
1670 void net_socket_rs_init(SocketReadState *rs,
1671                         SocketReadStateFinalize *finalize,
1672                         bool vnet_hdr)
1673 {
1674     rs->state = 0;
1675     rs->vnet_hdr = vnet_hdr;
1676     rs->index = 0;
1677     rs->packet_len = 0;
1678     rs->vnet_hdr_len = 0;
1679     memset(rs->buf, 0, sizeof(rs->buf));
1680     rs->finalize = finalize;
1681 }
1682 
1683 /*
1684  * Returns
1685  * 0: success
1686  * -1: error occurs
1687  */
1688 int net_fill_rstate(SocketReadState *rs, const uint8_t *buf, int size)
1689 {
1690     unsigned int l;
1691 
1692     while (size > 0) {
1693         /* Reassemble a packet from the network.
1694          * 0 = getting length.
1695          * 1 = getting vnet header length.
1696          * 2 = getting data.
1697          */
1698         switch (rs->state) {
1699         case 0:
1700             l = 4 - rs->index;
1701             if (l > size) {
1702                 l = size;
1703             }
1704             memcpy(rs->buf + rs->index, buf, l);
1705             buf += l;
1706             size -= l;
1707             rs->index += l;
1708             if (rs->index == 4) {
1709                 /* got length */
1710                 rs->packet_len = ntohl(*(uint32_t *)rs->buf);
1711                 rs->index = 0;
1712                 if (rs->vnet_hdr) {
1713                     rs->state = 1;
1714                 } else {
1715                     rs->state = 2;
1716                     rs->vnet_hdr_len = 0;
1717                 }
1718             }
1719             break;
1720         case 1:
1721             l = 4 - rs->index;
1722             if (l > size) {
1723                 l = size;
1724             }
1725             memcpy(rs->buf + rs->index, buf, l);
1726             buf += l;
1727             size -= l;
1728             rs->index += l;
1729             if (rs->index == 4) {
1730                 /* got vnet header length */
1731                 rs->vnet_hdr_len = ntohl(*(uint32_t *)rs->buf);
1732                 rs->index = 0;
1733                 rs->state = 2;
1734             }
1735             break;
1736         case 2:
1737             l = rs->packet_len - rs->index;
1738             if (l > size) {
1739                 l = size;
1740             }
1741             if (rs->index + l <= sizeof(rs->buf)) {
1742                 memcpy(rs->buf + rs->index, buf, l);
1743             } else {
1744                 fprintf(stderr, "serious error: oversized packet received,"
1745                     "connection terminated.\n");
1746                 rs->index = rs->state = 0;
1747                 return -1;
1748             }
1749 
1750             rs->index += l;
1751             buf += l;
1752             size -= l;
1753             if (rs->index >= rs->packet_len) {
1754                 rs->index = 0;
1755                 rs->state = 0;
1756                 assert(rs->finalize);
1757                 rs->finalize(rs);
1758             }
1759             break;
1760         }
1761     }
1762 
1763     assert(size == 0);
1764     return 0;
1765 }
1766