OSDN Git Service

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