]> Git Repo - qemu.git/blob - net/net.c
netfilter: print filter info associate with the netdev
[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 #include "config-host.h"
25
26 #include "net/net.h"
27 #include "clients.h"
28 #include "hub.h"
29 #include "net/slirp.h"
30 #include "net/eth.h"
31 #include "util.h"
32
33 #include "monitor/monitor.h"
34 #include "qemu-common.h"
35 #include "qapi/qmp/qerror.h"
36 #include "qemu/error-report.h"
37 #include "qemu/sockets.h"
38 #include "qemu/config-file.h"
39 #include "qmp-commands.h"
40 #include "hw/qdev.h"
41 #include "qemu/iov.h"
42 #include "qemu/main-loop.h"
43 #include "qapi-visit.h"
44 #include "qapi/opts-visitor.h"
45 #include "qapi/dealloc-visitor.h"
46 #include "sysemu/sysemu.h"
47 #include "net/filter.h"
48
49 /* Net bridge is currently not supported for W32. */
50 #if !defined(_WIN32)
51 # define CONFIG_NET_BRIDGE
52 #endif
53
54 static VMChangeStateEntry *net_change_state_entry;
55 static QTAILQ_HEAD(, NetClientState) net_clients;
56
57 const char *host_net_devices[] = {
58     "tap",
59     "socket",
60     "dump",
61 #ifdef CONFIG_NET_BRIDGE
62     "bridge",
63 #endif
64 #ifdef CONFIG_NETMAP
65     "netmap",
66 #endif
67 #ifdef CONFIG_SLIRP
68     "user",
69 #endif
70 #ifdef CONFIG_VDE
71     "vde",
72 #endif
73     "vhost-user",
74     NULL,
75 };
76
77 int default_net = 1;
78
79 /***********************************************************/
80 /* network device redirectors */
81
82 #if defined(DEBUG_NET)
83 static void hex_dump(FILE *f, const uint8_t *buf, int size)
84 {
85     int len, i, j, c;
86
87     for(i=0;i<size;i+=16) {
88         len = size - i;
89         if (len > 16)
90             len = 16;
91         fprintf(f, "%08x ", i);
92         for(j=0;j<16;j++) {
93             if (j < len)
94                 fprintf(f, " %02x", buf[i+j]);
95             else
96                 fprintf(f, "   ");
97         }
98         fprintf(f, " ");
99         for(j=0;j<len;j++) {
100             c = buf[i+j];
101             if (c < ' ' || c > '~')
102                 c = '.';
103             fprintf(f, "%c", c);
104         }
105         fprintf(f, "\n");
106     }
107 }
108 #endif
109
110 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
111 {
112     const char *p, *p1;
113     int len;
114     p = *pp;
115     p1 = strchr(p, sep);
116     if (!p1)
117         return -1;
118     len = p1 - p;
119     p1++;
120     if (buf_size > 0) {
121         if (len > buf_size - 1)
122             len = buf_size - 1;
123         memcpy(buf, p, len);
124         buf[len] = '\0';
125     }
126     *pp = p1;
127     return 0;
128 }
129
130 int parse_host_port(struct sockaddr_in *saddr, const char *str)
131 {
132     char buf[512];
133     struct hostent *he;
134     const char *p, *r;
135     int port;
136
137     p = str;
138     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
139         return -1;
140     saddr->sin_family = AF_INET;
141     if (buf[0] == '\0') {
142         saddr->sin_addr.s_addr = 0;
143     } else {
144         if (qemu_isdigit(buf[0])) {
145             if (!inet_aton(buf, &saddr->sin_addr))
146                 return -1;
147         } else {
148             if ((he = gethostbyname(buf)) == NULL)
149                 return - 1;
150             saddr->sin_addr = *(struct in_addr *)he->h_addr;
151         }
152     }
153     port = strtol(p, (char **)&r, 0);
154     if (r == p)
155         return -1;
156     saddr->sin_port = htons(port);
157     return 0;
158 }
159
160 char *qemu_mac_strdup_printf(const uint8_t *macaddr)
161 {
162     return g_strdup_printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
163                            macaddr[0], macaddr[1], macaddr[2],
164                            macaddr[3], macaddr[4], macaddr[5]);
165 }
166
167 void qemu_format_nic_info_str(NetClientState *nc, uint8_t macaddr[6])
168 {
169     snprintf(nc->info_str, sizeof(nc->info_str),
170              "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
171              nc->model,
172              macaddr[0], macaddr[1], macaddr[2],
173              macaddr[3], macaddr[4], macaddr[5]);
174 }
175
176 static int mac_table[256] = {0};
177
178 static void qemu_macaddr_set_used(MACAddr *macaddr)
179 {
180     int index;
181
182     for (index = 0x56; index < 0xFF; index++) {
183         if (macaddr->a[5] == index) {
184             mac_table[index]++;
185         }
186     }
187 }
188
189 static void qemu_macaddr_set_free(MACAddr *macaddr)
190 {
191     int index;
192     static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
193
194     if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
195         return;
196     }
197     for (index = 0x56; index < 0xFF; index++) {
198         if (macaddr->a[5] == index) {
199             mac_table[index]--;
200         }
201     }
202 }
203
204 static int qemu_macaddr_get_free(void)
205 {
206     int index;
207
208     for (index = 0x56; index < 0xFF; index++) {
209         if (mac_table[index] == 0) {
210             return index;
211         }
212     }
213
214     return -1;
215 }
216
217 void qemu_macaddr_default_if_unset(MACAddr *macaddr)
218 {
219     static const MACAddr zero = { .a = { 0,0,0,0,0,0 } };
220     static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
221
222     if (memcmp(macaddr, &zero, sizeof(zero)) != 0) {
223         if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
224             return;
225         } else {
226             qemu_macaddr_set_used(macaddr);
227             return;
228         }
229     }
230
231     macaddr->a[0] = 0x52;
232     macaddr->a[1] = 0x54;
233     macaddr->a[2] = 0x00;
234     macaddr->a[3] = 0x12;
235     macaddr->a[4] = 0x34;
236     macaddr->a[5] = qemu_macaddr_get_free();
237     qemu_macaddr_set_used(macaddr);
238 }
239
240 /**
241  * Generate a name for net client
242  *
243  * Only net clients created with the legacy -net option and NICs need this.
244  */
245 static char *assign_name(NetClientState *nc1, const char *model)
246 {
247     NetClientState *nc;
248     int id = 0;
249
250     QTAILQ_FOREACH(nc, &net_clients, next) {
251         if (nc == nc1) {
252             continue;
253         }
254         if (strcmp(nc->model, model) == 0) {
255             id++;
256         }
257     }
258
259     return g_strdup_printf("%s.%d", model, id);
260 }
261
262 static void qemu_net_client_destructor(NetClientState *nc)
263 {
264     g_free(nc);
265 }
266
267 static void qemu_net_client_setup(NetClientState *nc,
268                                   NetClientInfo *info,
269                                   NetClientState *peer,
270                                   const char *model,
271                                   const char *name,
272                                   NetClientDestructor *destructor)
273 {
274     nc->info = info;
275     nc->model = g_strdup(model);
276     if (name) {
277         nc->name = g_strdup(name);
278     } else {
279         nc->name = assign_name(nc, model);
280     }
281
282     if (peer) {
283         assert(!peer->peer);
284         nc->peer = peer;
285         peer->peer = nc;
286     }
287     QTAILQ_INSERT_TAIL(&net_clients, nc, next);
288
289     nc->incoming_queue = qemu_new_net_queue(qemu_deliver_packet_iov, nc);
290     nc->destructor = destructor;
291     QTAILQ_INIT(&nc->filters);
292 }
293
294 NetClientState *qemu_new_net_client(NetClientInfo *info,
295                                     NetClientState *peer,
296                                     const char *model,
297                                     const char *name)
298 {
299     NetClientState *nc;
300
301     assert(info->size >= sizeof(NetClientState));
302
303     nc = g_malloc0(info->size);
304     qemu_net_client_setup(nc, info, peer, model, name,
305                           qemu_net_client_destructor);
306
307     return nc;
308 }
309
310 NICState *qemu_new_nic(NetClientInfo *info,
311                        NICConf *conf,
312                        const char *model,
313                        const char *name,
314                        void *opaque)
315 {
316     NetClientState **peers = conf->peers.ncs;
317     NICState *nic;
318     int i, queues = MAX(1, conf->peers.queues);
319
320     assert(info->type == NET_CLIENT_OPTIONS_KIND_NIC);
321     assert(info->size >= sizeof(NICState));
322
323     nic = g_malloc0(info->size + sizeof(NetClientState) * queues);
324     nic->ncs = (void *)nic + info->size;
325     nic->conf = conf;
326     nic->opaque = opaque;
327
328     for (i = 0; i < queues; i++) {
329         qemu_net_client_setup(&nic->ncs[i], info, peers[i], model, name,
330                               NULL);
331         nic->ncs[i].queue_index = i;
332     }
333
334     return nic;
335 }
336
337 NetClientState *qemu_get_subqueue(NICState *nic, int queue_index)
338 {
339     return nic->ncs + queue_index;
340 }
341
342 NetClientState *qemu_get_queue(NICState *nic)
343 {
344     return qemu_get_subqueue(nic, 0);
345 }
346
347 NICState *qemu_get_nic(NetClientState *nc)
348 {
349     NetClientState *nc0 = nc - nc->queue_index;
350
351     return (NICState *)((void *)nc0 - nc->info->size);
352 }
353
354 void *qemu_get_nic_opaque(NetClientState *nc)
355 {
356     NICState *nic = qemu_get_nic(nc);
357
358     return nic->opaque;
359 }
360
361 static void qemu_cleanup_net_client(NetClientState *nc)
362 {
363     QTAILQ_REMOVE(&net_clients, nc, next);
364
365     if (nc->info->cleanup) {
366         nc->info->cleanup(nc);
367     }
368 }
369
370 static void qemu_free_net_client(NetClientState *nc)
371 {
372     if (nc->incoming_queue) {
373         qemu_del_net_queue(nc->incoming_queue);
374     }
375     if (nc->peer) {
376         nc->peer->peer = NULL;
377     }
378     g_free(nc->name);
379     g_free(nc->model);
380     if (nc->destructor) {
381         nc->destructor(nc);
382     }
383 }
384
385 void qemu_del_net_client(NetClientState *nc)
386 {
387     NetClientState *ncs[MAX_QUEUE_NUM];
388     int queues, i;
389     NetFilterState *nf, *next;
390
391     assert(nc->info->type != NET_CLIENT_OPTIONS_KIND_NIC);
392
393     /* If the NetClientState belongs to a multiqueue backend, we will change all
394      * other NetClientStates also.
395      */
396     queues = qemu_find_net_clients_except(nc->name, ncs,
397                                           NET_CLIENT_OPTIONS_KIND_NIC,
398                                           MAX_QUEUE_NUM);
399     assert(queues != 0);
400
401     QTAILQ_FOREACH_SAFE(nf, &nc->filters, next, next) {
402         object_unparent(OBJECT(nf));
403     }
404
405     /* If there is a peer NIC, delete and cleanup client, but do not free. */
406     if (nc->peer && nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
407         NICState *nic = qemu_get_nic(nc->peer);
408         if (nic->peer_deleted) {
409             return;
410         }
411         nic->peer_deleted = true;
412
413         for (i = 0; i < queues; i++) {
414             ncs[i]->peer->link_down = true;
415         }
416
417         if (nc->peer->info->link_status_changed) {
418             nc->peer->info->link_status_changed(nc->peer);
419         }
420
421         for (i = 0; i < queues; i++) {
422             qemu_cleanup_net_client(ncs[i]);
423         }
424
425         return;
426     }
427
428     for (i = 0; i < queues; i++) {
429         qemu_cleanup_net_client(ncs[i]);
430         qemu_free_net_client(ncs[i]);
431     }
432 }
433
434 void qemu_del_nic(NICState *nic)
435 {
436     int i, queues = MAX(nic->conf->peers.queues, 1);
437
438     qemu_macaddr_set_free(&nic->conf->macaddr);
439
440     /* If this is a peer NIC and peer has already been deleted, free it now. */
441     if (nic->peer_deleted) {
442         for (i = 0; i < queues; i++) {
443             qemu_free_net_client(qemu_get_subqueue(nic, i)->peer);
444         }
445     }
446
447     for (i = queues - 1; i >= 0; i--) {
448         NetClientState *nc = qemu_get_subqueue(nic, i);
449
450         qemu_cleanup_net_client(nc);
451         qemu_free_net_client(nc);
452     }
453
454     g_free(nic);
455 }
456
457 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
458 {
459     NetClientState *nc;
460
461     QTAILQ_FOREACH(nc, &net_clients, next) {
462         if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
463             if (nc->queue_index == 0) {
464                 func(qemu_get_nic(nc), opaque);
465             }
466         }
467     }
468 }
469
470 bool qemu_has_ufo(NetClientState *nc)
471 {
472     if (!nc || !nc->info->has_ufo) {
473         return false;
474     }
475
476     return nc->info->has_ufo(nc);
477 }
478
479 bool qemu_has_vnet_hdr(NetClientState *nc)
480 {
481     if (!nc || !nc->info->has_vnet_hdr) {
482         return false;
483     }
484
485     return nc->info->has_vnet_hdr(nc);
486 }
487
488 bool qemu_has_vnet_hdr_len(NetClientState *nc, int len)
489 {
490     if (!nc || !nc->info->has_vnet_hdr_len) {
491         return false;
492     }
493
494     return nc->info->has_vnet_hdr_len(nc, len);
495 }
496
497 void qemu_using_vnet_hdr(NetClientState *nc, bool enable)
498 {
499     if (!nc || !nc->info->using_vnet_hdr) {
500         return;
501     }
502
503     nc->info->using_vnet_hdr(nc, enable);
504 }
505
506 void qemu_set_offload(NetClientState *nc, int csum, int tso4, int tso6,
507                           int ecn, int ufo)
508 {
509     if (!nc || !nc->info->set_offload) {
510         return;
511     }
512
513     nc->info->set_offload(nc, csum, tso4, tso6, ecn, ufo);
514 }
515
516 void qemu_set_vnet_hdr_len(NetClientState *nc, int len)
517 {
518     if (!nc || !nc->info->set_vnet_hdr_len) {
519         return;
520     }
521
522     nc->info->set_vnet_hdr_len(nc, len);
523 }
524
525 int qemu_set_vnet_le(NetClientState *nc, bool is_le)
526 {
527     if (!nc || !nc->info->set_vnet_le) {
528         return -ENOSYS;
529     }
530
531     return nc->info->set_vnet_le(nc, is_le);
532 }
533
534 int qemu_set_vnet_be(NetClientState *nc, bool is_be)
535 {
536     if (!nc || !nc->info->set_vnet_be) {
537         return -ENOSYS;
538     }
539
540     return nc->info->set_vnet_be(nc, is_be);
541 }
542
543 int qemu_can_send_packet(NetClientState *sender)
544 {
545     int vm_running = runstate_is_running();
546
547     if (!vm_running) {
548         return 0;
549     }
550
551     if (!sender->peer) {
552         return 1;
553     }
554
555     if (sender->peer->receive_disabled) {
556         return 0;
557     } else if (sender->peer->info->can_receive &&
558                !sender->peer->info->can_receive(sender->peer)) {
559         return 0;
560     }
561     return 1;
562 }
563
564 static ssize_t filter_receive_iov(NetClientState *nc,
565                                   NetFilterDirection direction,
566                                   NetClientState *sender,
567                                   unsigned flags,
568                                   const struct iovec *iov,
569                                   int iovcnt,
570                                   NetPacketSent *sent_cb)
571 {
572     ssize_t ret = 0;
573     NetFilterState *nf = NULL;
574
575     QTAILQ_FOREACH(nf, &nc->filters, next) {
576         ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
577                                      iovcnt, sent_cb);
578         if (ret) {
579             return ret;
580         }
581     }
582
583     return ret;
584 }
585
586 static ssize_t filter_receive(NetClientState *nc,
587                               NetFilterDirection direction,
588                               NetClientState *sender,
589                               unsigned flags,
590                               const uint8_t *data,
591                               size_t size,
592                               NetPacketSent *sent_cb)
593 {
594     struct iovec iov = {
595         .iov_base = (void *)data,
596         .iov_len = size
597     };
598
599     return filter_receive_iov(nc, direction, sender, flags, &iov, 1, sent_cb);
600 }
601
602 void qemu_purge_queued_packets(NetClientState *nc)
603 {
604     if (!nc->peer) {
605         return;
606     }
607
608     qemu_net_queue_purge(nc->peer->incoming_queue, nc);
609 }
610
611 static
612 void qemu_flush_or_purge_queued_packets(NetClientState *nc, bool purge)
613 {
614     nc->receive_disabled = 0;
615
616     if (nc->peer && nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_HUBPORT) {
617         if (net_hub_flush(nc->peer)) {
618             qemu_notify_event();
619         }
620     }
621     if (qemu_net_queue_flush(nc->incoming_queue)) {
622         /* We emptied the queue successfully, signal to the IO thread to repoll
623          * the file descriptor (for tap, for example).
624          */
625         qemu_notify_event();
626     } else if (purge) {
627         /* Unable to empty the queue, purge remaining packets */
628         qemu_net_queue_purge(nc->incoming_queue, nc);
629     }
630 }
631
632 void qemu_flush_queued_packets(NetClientState *nc)
633 {
634     qemu_flush_or_purge_queued_packets(nc, false);
635 }
636
637 static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
638                                                  unsigned flags,
639                                                  const uint8_t *buf, int size,
640                                                  NetPacketSent *sent_cb)
641 {
642     NetQueue *queue;
643     int ret;
644
645 #ifdef DEBUG_NET
646     printf("qemu_send_packet_async:\n");
647     hex_dump(stdout, buf, size);
648 #endif
649
650     if (sender->link_down || !sender->peer) {
651         return size;
652     }
653
654     /* Let filters handle the packet first */
655     ret = filter_receive(sender, NET_FILTER_DIRECTION_TX,
656                          sender, flags, buf, size, sent_cb);
657     if (ret) {
658         return ret;
659     }
660
661     ret = filter_receive(sender->peer, NET_FILTER_DIRECTION_RX,
662                          sender, flags, buf, size, sent_cb);
663     if (ret) {
664         return ret;
665     }
666
667     queue = sender->peer->incoming_queue;
668
669     return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
670 }
671
672 ssize_t qemu_send_packet_async(NetClientState *sender,
673                                const uint8_t *buf, int size,
674                                NetPacketSent *sent_cb)
675 {
676     return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
677                                              buf, size, sent_cb);
678 }
679
680 void qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size)
681 {
682     qemu_send_packet_async(nc, buf, size, NULL);
683 }
684
685 ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size)
686 {
687     return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW,
688                                              buf, size, NULL);
689 }
690
691 static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
692                                int iovcnt, unsigned flags)
693 {
694     uint8_t buf[NET_BUFSIZE];
695     uint8_t *buffer;
696     size_t offset;
697
698     if (iovcnt == 1) {
699         buffer = iov[0].iov_base;
700         offset = iov[0].iov_len;
701     } else {
702         buffer = buf;
703         offset = iov_to_buf(iov, iovcnt, 0, buffer, sizeof(buffer));
704     }
705
706     if (flags & QEMU_NET_PACKET_FLAG_RAW && nc->info->receive_raw) {
707         return nc->info->receive_raw(nc, buffer, offset);
708     } else {
709         return nc->info->receive(nc, buffer, offset);
710     }
711 }
712
713 ssize_t qemu_deliver_packet_iov(NetClientState *sender,
714                                 unsigned flags,
715                                 const struct iovec *iov,
716                                 int iovcnt,
717                                 void *opaque)
718 {
719     NetClientState *nc = opaque;
720     int ret;
721
722     if (nc->link_down) {
723         return iov_size(iov, iovcnt);
724     }
725
726     if (nc->receive_disabled) {
727         return 0;
728     }
729
730     if (nc->info->receive_iov) {
731         ret = nc->info->receive_iov(nc, iov, iovcnt);
732     } else {
733         ret = nc_sendv_compat(nc, iov, iovcnt, flags);
734     }
735
736     if (ret == 0) {
737         nc->receive_disabled = 1;
738     }
739
740     return ret;
741 }
742
743 ssize_t qemu_sendv_packet_async(NetClientState *sender,
744                                 const struct iovec *iov, int iovcnt,
745                                 NetPacketSent *sent_cb)
746 {
747     NetQueue *queue;
748     int ret;
749
750     if (sender->link_down || !sender->peer) {
751         return iov_size(iov, iovcnt);
752     }
753
754     /* Let filters handle the packet first */
755     ret = filter_receive_iov(sender, NET_FILTER_DIRECTION_TX, sender,
756                              QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
757     if (ret) {
758         return ret;
759     }
760
761     ret = filter_receive_iov(sender->peer, NET_FILTER_DIRECTION_RX, sender,
762                              QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
763     if (ret) {
764         return ret;
765     }
766
767     queue = sender->peer->incoming_queue;
768
769     return qemu_net_queue_send_iov(queue, sender,
770                                    QEMU_NET_PACKET_FLAG_NONE,
771                                    iov, iovcnt, sent_cb);
772 }
773
774 ssize_t
775 qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt)
776 {
777     return qemu_sendv_packet_async(nc, iov, iovcnt, NULL);
778 }
779
780 NetClientState *qemu_find_netdev(const char *id)
781 {
782     NetClientState *nc;
783
784     QTAILQ_FOREACH(nc, &net_clients, next) {
785         if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC)
786             continue;
787         if (!strcmp(nc->name, id)) {
788             return nc;
789         }
790     }
791
792     return NULL;
793 }
794
795 int qemu_find_net_clients_except(const char *id, NetClientState **ncs,
796                                  NetClientOptionsKind type, int max)
797 {
798     NetClientState *nc;
799     int ret = 0;
800
801     QTAILQ_FOREACH(nc, &net_clients, next) {
802         if (nc->info->type == type) {
803             continue;
804         }
805         if (!id || !strcmp(nc->name, id)) {
806             if (ret < max) {
807                 ncs[ret] = nc;
808             }
809             ret++;
810         }
811     }
812
813     return ret;
814 }
815
816 static int nic_get_free_idx(void)
817 {
818     int index;
819
820     for (index = 0; index < MAX_NICS; index++)
821         if (!nd_table[index].used)
822             return index;
823     return -1;
824 }
825
826 int qemu_show_nic_models(const char *arg, const char *const *models)
827 {
828     int i;
829
830     if (!arg || !is_help_option(arg)) {
831         return 0;
832     }
833
834     fprintf(stderr, "qemu: Supported NIC models: ");
835     for (i = 0 ; models[i]; i++)
836         fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
837     return 1;
838 }
839
840 void qemu_check_nic_model(NICInfo *nd, const char *model)
841 {
842     const char *models[2];
843
844     models[0] = model;
845     models[1] = NULL;
846
847     if (qemu_show_nic_models(nd->model, models))
848         exit(0);
849     if (qemu_find_nic_model(nd, models, model) < 0)
850         exit(1);
851 }
852
853 int qemu_find_nic_model(NICInfo *nd, const char * const *models,
854                         const char *default_model)
855 {
856     int i;
857
858     if (!nd->model)
859         nd->model = g_strdup(default_model);
860
861     for (i = 0 ; models[i]; i++) {
862         if (strcmp(nd->model, models[i]) == 0)
863             return i;
864     }
865
866     error_report("Unsupported NIC model: %s", nd->model);
867     return -1;
868 }
869
870 static int net_init_nic(const NetClientOptions *opts, const char *name,
871                         NetClientState *peer, Error **errp)
872 {
873     int idx;
874     NICInfo *nd;
875     const NetLegacyNicOptions *nic;
876
877     assert(opts->kind == NET_CLIENT_OPTIONS_KIND_NIC);
878     nic = opts->nic;
879
880     idx = nic_get_free_idx();
881     if (idx == -1 || nb_nics >= MAX_NICS) {
882         error_setg(errp, "too many NICs");
883         return -1;
884     }
885
886     nd = &nd_table[idx];
887
888     memset(nd, 0, sizeof(*nd));
889
890     if (nic->has_netdev) {
891         nd->netdev = qemu_find_netdev(nic->netdev);
892         if (!nd->netdev) {
893             error_setg(errp, "netdev '%s' not found", nic->netdev);
894             return -1;
895         }
896     } else {
897         assert(peer);
898         nd->netdev = peer;
899     }
900     nd->name = g_strdup(name);
901     if (nic->has_model) {
902         nd->model = g_strdup(nic->model);
903     }
904     if (nic->has_addr) {
905         nd->devaddr = g_strdup(nic->addr);
906     }
907
908     if (nic->has_macaddr &&
909         net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {
910         error_setg(errp, "invalid syntax for ethernet address");
911         return -1;
912     }
913     if (nic->has_macaddr &&
914         is_multicast_ether_addr(nd->macaddr.a)) {
915         error_setg(errp,
916                    "NIC cannot have multicast MAC address (odd 1st byte)");
917         return -1;
918     }
919     qemu_macaddr_default_if_unset(&nd->macaddr);
920
921     if (nic->has_vectors) {
922         if (nic->vectors > 0x7ffffff) {
923             error_setg(errp, "invalid # of vectors: %"PRIu32, nic->vectors);
924             return -1;
925         }
926         nd->nvectors = nic->vectors;
927     } else {
928         nd->nvectors = DEV_NVECTORS_UNSPECIFIED;
929     }
930
931     nd->used = 1;
932     nb_nics++;
933
934     return idx;
935 }
936
937
938 static int (* const net_client_init_fun[NET_CLIENT_OPTIONS_KIND_MAX])(
939     const NetClientOptions *opts,
940     const char *name,
941     NetClientState *peer, Error **errp) = {
942         [NET_CLIENT_OPTIONS_KIND_NIC]       = net_init_nic,
943 #ifdef CONFIG_SLIRP
944         [NET_CLIENT_OPTIONS_KIND_USER]      = net_init_slirp,
945 #endif
946         [NET_CLIENT_OPTIONS_KIND_TAP]       = net_init_tap,
947         [NET_CLIENT_OPTIONS_KIND_SOCKET]    = net_init_socket,
948 #ifdef CONFIG_VDE
949         [NET_CLIENT_OPTIONS_KIND_VDE]       = net_init_vde,
950 #endif
951 #ifdef CONFIG_NETMAP
952         [NET_CLIENT_OPTIONS_KIND_NETMAP]    = net_init_netmap,
953 #endif
954         [NET_CLIENT_OPTIONS_KIND_DUMP]      = net_init_dump,
955 #ifdef CONFIG_NET_BRIDGE
956         [NET_CLIENT_OPTIONS_KIND_BRIDGE]    = net_init_bridge,
957 #endif
958         [NET_CLIENT_OPTIONS_KIND_HUBPORT]   = net_init_hubport,
959 #ifdef CONFIG_VHOST_NET_USED
960         [NET_CLIENT_OPTIONS_KIND_VHOST_USER] = net_init_vhost_user,
961 #endif
962 #ifdef CONFIG_L2TPV3
963         [NET_CLIENT_OPTIONS_KIND_L2TPV3]    = net_init_l2tpv3,
964 #endif
965 };
966
967
968 static int net_client_init1(const void *object, int is_netdev, Error **errp)
969 {
970     const NetClientOptions *opts;
971     const char *name;
972     NetClientState *peer = NULL;
973
974     if (is_netdev) {
975         const Netdev *netdev = object;
976         opts = netdev->opts;
977         name = netdev->id;
978
979         if (opts->kind == NET_CLIENT_OPTIONS_KIND_DUMP ||
980             opts->kind == NET_CLIENT_OPTIONS_KIND_NIC ||
981             !net_client_init_fun[opts->kind]) {
982             error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
983                        "a netdev backend type");
984             return -1;
985         }
986     } else {
987         const NetLegacy *net = object;
988         opts = net->opts;
989         /* missing optional values have been initialized to "all bits zero" */
990         name = net->has_id ? net->id : net->name;
991
992         if (opts->kind == NET_CLIENT_OPTIONS_KIND_NONE) {
993             return 0; /* nothing to do */
994         }
995         if (opts->kind == NET_CLIENT_OPTIONS_KIND_HUBPORT) {
996             error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
997                        "a net type");
998             return -1;
999         }
1000
1001         if (!net_client_init_fun[opts->kind]) {
1002             error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
1003                        "a net backend type (maybe it is not compiled "
1004                        "into this binary)");
1005             return -1;
1006         }
1007
1008         /* Do not add to a vlan if it's a nic with a netdev= parameter. */
1009         if (opts->kind != NET_CLIENT_OPTIONS_KIND_NIC ||
1010             !opts->nic->has_netdev) {
1011             peer = net_hub_add_port(net->has_vlan ? net->vlan : 0, NULL);
1012         }
1013     }
1014
1015     if (net_client_init_fun[opts->kind](opts, name, peer, errp) < 0) {
1016         /* FIXME drop when all init functions store an Error */
1017         if (errp && !*errp) {
1018             error_setg(errp, QERR_DEVICE_INIT_FAILED,
1019                        NetClientOptionsKind_lookup[opts->kind]);
1020         }
1021         return -1;
1022     }
1023     return 0;
1024 }
1025
1026
1027 static void net_visit(Visitor *v, int is_netdev, void **object, Error **errp)
1028 {
1029     if (is_netdev) {
1030         visit_type_Netdev(v, (Netdev **)object, NULL, errp);
1031     } else {
1032         visit_type_NetLegacy(v, (NetLegacy **)object, NULL, errp);
1033     }
1034 }
1035
1036
1037 int net_client_init(QemuOpts *opts, int is_netdev, Error **errp)
1038 {
1039     void *object = NULL;
1040     Error *err = NULL;
1041     int ret = -1;
1042
1043     {
1044         OptsVisitor *ov = opts_visitor_new(opts);
1045
1046         net_visit(opts_get_visitor(ov), is_netdev, &object, &err);
1047         opts_visitor_cleanup(ov);
1048     }
1049
1050     if (!err) {
1051         ret = net_client_init1(object, is_netdev, &err);
1052     }
1053
1054     if (object) {
1055         QapiDeallocVisitor *dv = qapi_dealloc_visitor_new();
1056
1057         net_visit(qapi_dealloc_get_visitor(dv), is_netdev, &object, NULL);
1058         qapi_dealloc_visitor_cleanup(dv);
1059     }
1060
1061     error_propagate(errp, err);
1062     return ret;
1063 }
1064
1065
1066 static int net_host_check_device(const char *device)
1067 {
1068     int i;
1069     for (i = 0; host_net_devices[i]; i++) {
1070         if (!strncmp(host_net_devices[i], device,
1071                      strlen(host_net_devices[i]))) {
1072             return 1;
1073         }
1074     }
1075
1076     return 0;
1077 }
1078
1079 void hmp_host_net_add(Monitor *mon, const QDict *qdict)
1080 {
1081     const char *device = qdict_get_str(qdict, "device");
1082     const char *opts_str = qdict_get_try_str(qdict, "opts");
1083     Error *local_err = NULL;
1084     QemuOpts *opts;
1085
1086     if (!net_host_check_device(device)) {
1087         monitor_printf(mon, "invalid host network device %s\n", device);
1088         return;
1089     }
1090
1091     opts = qemu_opts_parse_noisily(qemu_find_opts("net"),
1092                                    opts_str ? opts_str : "", false);
1093     if (!opts) {
1094         return;
1095     }
1096
1097     qemu_opt_set(opts, "type", device, &error_abort);
1098
1099     net_client_init(opts, 0, &local_err);
1100     if (local_err) {
1101         error_report_err(local_err);
1102         monitor_printf(mon, "adding host network device %s failed\n", device);
1103     }
1104 }
1105
1106 void hmp_host_net_remove(Monitor *mon, const QDict *qdict)
1107 {
1108     NetClientState *nc;
1109     int vlan_id = qdict_get_int(qdict, "vlan_id");
1110     const char *device = qdict_get_str(qdict, "device");
1111
1112     nc = net_hub_find_client_by_name(vlan_id, device);
1113     if (!nc) {
1114         error_report("Host network device '%s' on hub '%d' not found",
1115                      device, vlan_id);
1116         return;
1117     }
1118     if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
1119         error_report("invalid host network device '%s'", device);
1120         return;
1121     }
1122
1123     qemu_del_net_client(nc->peer);
1124     qemu_del_net_client(nc);
1125 }
1126
1127 void netdev_add(QemuOpts *opts, Error **errp)
1128 {
1129     net_client_init(opts, 1, errp);
1130 }
1131
1132 void qmp_netdev_add(QDict *qdict, QObject **ret, Error **errp)
1133 {
1134     Error *local_err = NULL;
1135     QemuOptsList *opts_list;
1136     QemuOpts *opts;
1137
1138     opts_list = qemu_find_opts_err("netdev", &local_err);
1139     if (local_err) {
1140         goto out;
1141     }
1142
1143     opts = qemu_opts_from_qdict(opts_list, qdict, &local_err);
1144     if (local_err) {
1145         goto out;
1146     }
1147
1148     netdev_add(opts, &local_err);
1149     if (local_err) {
1150         qemu_opts_del(opts);
1151         goto out;
1152     }
1153
1154 out:
1155     error_propagate(errp, local_err);
1156 }
1157
1158 void qmp_netdev_del(const char *id, Error **errp)
1159 {
1160     NetClientState *nc;
1161     QemuOpts *opts;
1162
1163     nc = qemu_find_netdev(id);
1164     if (!nc) {
1165         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1166                   "Device '%s' not found", id);
1167         return;
1168     }
1169
1170     opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), id);
1171     if (!opts) {
1172         error_setg(errp, "Device '%s' is not a netdev", id);
1173         return;
1174     }
1175
1176     qemu_del_net_client(nc);
1177     qemu_opts_del(opts);
1178 }
1179
1180 void print_net_client(Monitor *mon, NetClientState *nc)
1181 {
1182     NetFilterState *nf;
1183
1184     monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
1185                    nc->queue_index,
1186                    NetClientOptionsKind_lookup[nc->info->type],
1187                    nc->info_str);
1188     if (!QTAILQ_EMPTY(&nc->filters)) {
1189         monitor_printf(mon, "filters:\n");
1190     }
1191     QTAILQ_FOREACH(nf, &nc->filters, next) {
1192         monitor_printf(mon, "  - %s: type=%s%s\n",
1193                        object_get_canonical_path_component(OBJECT(nf)),
1194                        object_get_typename(OBJECT(nf)),
1195                        nf->info_str);
1196     }
1197 }
1198
1199 RxFilterInfoList *qmp_query_rx_filter(bool has_name, const char *name,
1200                                       Error **errp)
1201 {
1202     NetClientState *nc;
1203     RxFilterInfoList *filter_list = NULL, *last_entry = NULL;
1204
1205     QTAILQ_FOREACH(nc, &net_clients, next) {
1206         RxFilterInfoList *entry;
1207         RxFilterInfo *info;
1208
1209         if (has_name && strcmp(nc->name, name) != 0) {
1210             continue;
1211         }
1212
1213         /* only query rx-filter information of NIC */
1214         if (nc->info->type != NET_CLIENT_OPTIONS_KIND_NIC) {
1215             if (has_name) {
1216                 error_setg(errp, "net client(%s) isn't a NIC", name);
1217                 return NULL;
1218             }
1219             continue;
1220         }
1221
1222         if (nc->info->query_rx_filter) {
1223             info = nc->info->query_rx_filter(nc);
1224             entry = g_malloc0(sizeof(*entry));
1225             entry->value = info;
1226
1227             if (!filter_list) {
1228                 filter_list = entry;
1229             } else {
1230                 last_entry->next = entry;
1231             }
1232             last_entry = entry;
1233         } else if (has_name) {
1234             error_setg(errp, "net client(%s) doesn't support"
1235                        " rx-filter querying", name);
1236             return NULL;
1237         }
1238
1239         if (has_name) {
1240             break;
1241         }
1242     }
1243
1244     if (filter_list == NULL && has_name) {
1245         error_setg(errp, "invalid net client name: %s", name);
1246     }
1247
1248     return filter_list;
1249 }
1250
1251 void hmp_info_network(Monitor *mon, const QDict *qdict)
1252 {
1253     NetClientState *nc, *peer;
1254     NetClientOptionsKind type;
1255
1256     net_hub_info(mon);
1257
1258     QTAILQ_FOREACH(nc, &net_clients, next) {
1259         peer = nc->peer;
1260         type = nc->info->type;
1261
1262         /* Skip if already printed in hub info */
1263         if (net_hub_id_for_client(nc, NULL) == 0) {
1264             continue;
1265         }
1266
1267         if (!peer || type == NET_CLIENT_OPTIONS_KIND_NIC) {
1268             print_net_client(mon, nc);
1269         } /* else it's a netdev connected to a NIC, printed with the NIC */
1270         if (peer && type == NET_CLIENT_OPTIONS_KIND_NIC) {
1271             monitor_printf(mon, " \\ ");
1272             print_net_client(mon, peer);
1273         }
1274     }
1275 }
1276
1277 void qmp_set_link(const char *name, bool up, Error **errp)
1278 {
1279     NetClientState *ncs[MAX_QUEUE_NUM];
1280     NetClientState *nc;
1281     int queues, i;
1282
1283     queues = qemu_find_net_clients_except(name, ncs,
1284                                           NET_CLIENT_OPTIONS_KIND_MAX,
1285                                           MAX_QUEUE_NUM);
1286
1287     if (queues == 0) {
1288         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1289                   "Device '%s' not found", name);
1290         return;
1291     }
1292     nc = ncs[0];
1293
1294     for (i = 0; i < queues; i++) {
1295         ncs[i]->link_down = !up;
1296     }
1297
1298     if (nc->info->link_status_changed) {
1299         nc->info->link_status_changed(nc);
1300     }
1301
1302     if (nc->peer) {
1303         /* Change peer link only if the peer is NIC and then notify peer.
1304          * If the peer is a HUBPORT or a backend, we do not change the
1305          * link status.
1306          *
1307          * This behavior is compatible with qemu vlans where there could be
1308          * multiple clients that can still communicate with each other in
1309          * disconnected mode. For now maintain this compatibility.
1310          */
1311         if (nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
1312             for (i = 0; i < queues; i++) {
1313                 ncs[i]->peer->link_down = !up;
1314             }
1315         }
1316         if (nc->peer->info->link_status_changed) {
1317             nc->peer->info->link_status_changed(nc->peer);
1318         }
1319     }
1320 }
1321
1322 static void net_vm_change_state_handler(void *opaque, int running,
1323                                         RunState state)
1324 {
1325     NetClientState *nc;
1326     NetClientState *tmp;
1327
1328     QTAILQ_FOREACH_SAFE(nc, &net_clients, next, tmp) {
1329         if (running) {
1330             /* Flush queued packets and wake up backends. */
1331             if (nc->peer && qemu_can_send_packet(nc)) {
1332                 qemu_flush_queued_packets(nc->peer);
1333             }
1334         } else {
1335             /* Complete all queued packets, to guarantee we don't modify
1336              * state later when VM is not running.
1337              */
1338             qemu_flush_or_purge_queued_packets(nc, true);
1339         }
1340     }
1341 }
1342
1343 void net_cleanup(void)
1344 {
1345     NetClientState *nc;
1346
1347     /* We may del multiple entries during qemu_del_net_client(),
1348      * so QTAILQ_FOREACH_SAFE() is also not safe here.
1349      */
1350     while (!QTAILQ_EMPTY(&net_clients)) {
1351         nc = QTAILQ_FIRST(&net_clients);
1352         if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
1353             qemu_del_nic(qemu_get_nic(nc));
1354         } else {
1355             qemu_del_net_client(nc);
1356         }
1357     }
1358
1359     qemu_del_vm_change_state_handler(net_change_state_entry);
1360 }
1361
1362 void net_check_clients(void)
1363 {
1364     NetClientState *nc;
1365     int i;
1366
1367     /* Don't warn about the default network setup that you get if
1368      * no command line -net or -netdev options are specified. There
1369      * are two cases that we would otherwise complain about:
1370      * (1) board doesn't support a NIC but the implicit "-net nic"
1371      * requested one
1372      * (2) CONFIG_SLIRP not set, in which case the implicit "-net nic"
1373      * sets up a nic that isn't connected to anything.
1374      */
1375     if (default_net) {
1376         return;
1377     }
1378
1379     net_hub_check_clients();
1380
1381     QTAILQ_FOREACH(nc, &net_clients, next) {
1382         if (!nc->peer) {
1383             fprintf(stderr, "Warning: %s %s has no peer\n",
1384                     nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC ?
1385                     "nic" : "netdev", nc->name);
1386         }
1387     }
1388
1389     /* Check that all NICs requested via -net nic actually got created.
1390      * NICs created via -device don't need to be checked here because
1391      * they are always instantiated.
1392      */
1393     for (i = 0; i < MAX_NICS; i++) {
1394         NICInfo *nd = &nd_table[i];
1395         if (nd->used && !nd->instantiated) {
1396             fprintf(stderr, "Warning: requested NIC (%s, model %s) "
1397                     "was not created (not supported by this machine?)\n",
1398                     nd->name ? nd->name : "anonymous",
1399                     nd->model ? nd->model : "unspecified");
1400         }
1401     }
1402 }
1403
1404 static int net_init_client(void *dummy, QemuOpts *opts, Error **errp)
1405 {
1406     Error *local_err = NULL;
1407
1408     net_client_init(opts, 0, &local_err);
1409     if (local_err) {
1410         error_report_err(local_err);
1411         return -1;
1412     }
1413
1414     return 0;
1415 }
1416
1417 static int net_init_netdev(void *dummy, QemuOpts *opts, Error **errp)
1418 {
1419     Error *local_err = NULL;
1420     int ret;
1421
1422     ret = net_client_init(opts, 1, &local_err);
1423     if (local_err) {
1424         error_report_err(local_err);
1425         return -1;
1426     }
1427
1428     return ret;
1429 }
1430
1431 int net_init_clients(void)
1432 {
1433     QemuOptsList *net = qemu_find_opts("net");
1434
1435     if (default_net) {
1436         /* if no clients, we use a default config */
1437         qemu_opts_set(net, NULL, "type", "nic", &error_abort);
1438 #ifdef CONFIG_SLIRP
1439         qemu_opts_set(net, NULL, "type", "user", &error_abort);
1440 #endif
1441     }
1442
1443     net_change_state_entry =
1444         qemu_add_vm_change_state_handler(net_vm_change_state_handler, NULL);
1445
1446     QTAILQ_INIT(&net_clients);
1447
1448     if (qemu_opts_foreach(qemu_find_opts("netdev"),
1449                           net_init_netdev, NULL, NULL)) {
1450         return -1;
1451     }
1452
1453     if (qemu_opts_foreach(net, net_init_client, NULL, NULL)) {
1454         return -1;
1455     }
1456
1457     return 0;
1458 }
1459
1460 int net_client_parse(QemuOptsList *opts_list, const char *optarg)
1461 {
1462 #if defined(CONFIG_SLIRP)
1463     int ret;
1464     if (net_slirp_parse_legacy(opts_list, optarg, &ret)) {
1465         return ret;
1466     }
1467 #endif
1468
1469     if (!qemu_opts_parse_noisily(opts_list, optarg, true)) {
1470         return -1;
1471     }
1472
1473     default_net = 0;
1474     return 0;
1475 }
1476
1477 /* From FreeBSD */
1478 /* XXX: optimize */
1479 unsigned compute_mcast_idx(const uint8_t *ep)
1480 {
1481     uint32_t crc;
1482     int carry, i, j;
1483     uint8_t b;
1484
1485     crc = 0xffffffff;
1486     for (i = 0; i < 6; i++) {
1487         b = *ep++;
1488         for (j = 0; j < 8; j++) {
1489             carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
1490             crc <<= 1;
1491             b >>= 1;
1492             if (carry) {
1493                 crc = ((crc ^ POLYNOMIAL) | carry);
1494             }
1495         }
1496     }
1497     return crc >> 26;
1498 }
1499
1500 QemuOptsList qemu_netdev_opts = {
1501     .name = "netdev",
1502     .implied_opt_name = "type",
1503     .head = QTAILQ_HEAD_INITIALIZER(qemu_netdev_opts.head),
1504     .desc = {
1505         /*
1506          * no elements => accept any params
1507          * validation will happen later
1508          */
1509         { /* end of list */ }
1510     },
1511 };
1512
1513 QemuOptsList qemu_net_opts = {
1514     .name = "net",
1515     .implied_opt_name = "type",
1516     .head = QTAILQ_HEAD_INITIALIZER(qemu_net_opts.head),
1517     .desc = {
1518         /*
1519          * no elements => accept any params
1520          * validation will happen later
1521          */
1522         { /* end of list */ }
1523     },
1524 };
This page took 0.110333 seconds and 4 git commands to generate.