dd7ea42f7a74b6317101429efef93585b1183476
[sliver-openvswitch.git] / vswitchd / ovs-brcompatd.c
1 /* Copyright (c) 2008, 2009, 2010 Nicira Networks
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <config.h>
17
18 #include <asm/param.h>
19 #include <assert.h>
20 #include <errno.h>
21 #include <getopt.h>
22 #include <inttypes.h>
23 #include <limits.h>
24 #include <net/if.h>
25 #include <linux/genetlink.h>
26 #include <linux/rtnetlink.h>
27 #include <signal.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <time.h>
33 #include <fcntl.h>
34 #include <unistd.h>
35
36 #include "command-line.h"
37 #include "coverage.h"
38 #include "daemon.h"
39 #include "dirs.h"
40 #include "dynamic-string.h"
41 #include "fatal-signal.h"
42 #include "leak-checker.h"
43 #include "netdev.h"
44 #include "netlink.h"
45 #include "ofpbuf.h"
46 #include "openvswitch/brcompat-netlink.h"
47 #include "ovsdb-idl.h"
48 #include "packets.h"
49 #include "poll-loop.h"
50 #include "process.h"
51 #include "signals.h"
52 #include "svec.h"
53 #include "timeval.h"
54 #include "unixctl.h"
55 #include "util.h"
56 #include "vswitchd/vswitch-idl.h"
57
58 #include "vlog.h"
59 #define THIS_MODULE VLM_brcompatd
60
61
62 /* xxx Just hangs if datapath is rmmod/insmod.  Learn to reconnect? */
63
64 /* Actions to modify bridge compatibility configuration. */
65 enum bmc_action {
66     BMC_ADD_DP,
67     BMC_DEL_DP,
68     BMC_ADD_PORT,
69     BMC_DEL_PORT
70 };
71
72 static const char *parse_options(int argc, char *argv[]);
73 static void usage(void) NO_RETURN;
74
75 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 60);
76
77 /* Maximum number of milliseconds to wait before pruning port entries that 
78  * no longer exist.  If set to zero, ports are never pruned. */
79 static int prune_timeout = 5000;
80
81 /* Shell command to execute (via popen()) to send a control command to the
82  * running ovs-vswitchd process.  The string must contain one instance of %s,
83  * which is replaced by the control command. */
84 static char *appctl_command;
85
86 /* Netlink socket to listen for interface changes. */
87 static struct nl_sock *rtnl_sock;
88
89 /* Netlink socket to bridge compatibility kernel module. */
90 static struct nl_sock *brc_sock;
91
92 /* The Generic Netlink family number used for bridge compatibility. */
93 static int brc_family;
94
95 static const struct nl_policy brc_multicast_policy[] = {
96     [BRC_GENL_A_MC_GROUP] = {.type = NL_A_U32 }
97 };
98
99 static const struct nl_policy rtnlgrp_link_policy[] = {
100     [IFLA_IFNAME] = { .type = NL_A_STRING, .optional = false },
101     [IFLA_MASTER] = { .type = NL_A_U32, .optional = true },
102 };
103
104 static int
105 lookup_brc_multicast_group(int *multicast_group)
106 {
107     struct nl_sock *sock;
108     struct ofpbuf request, *reply;
109     struct nlattr *attrs[ARRAY_SIZE(brc_multicast_policy)];
110     int retval;
111
112     retval = nl_sock_create(NETLINK_GENERIC, 0, 0, 0, &sock);
113     if (retval) {
114         return retval;
115     }
116     ofpbuf_init(&request, 0);
117     nl_msg_put_genlmsghdr(&request, sock, 0, brc_family,
118             NLM_F_REQUEST, BRC_GENL_C_QUERY_MC, 1);
119     retval = nl_sock_transact(sock, &request, &reply);
120     ofpbuf_uninit(&request);
121     if (retval) {
122         nl_sock_destroy(sock);
123         return retval;
124     }
125     if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
126                          brc_multicast_policy, attrs,
127                          ARRAY_SIZE(brc_multicast_policy))) {
128         nl_sock_destroy(sock);
129         ofpbuf_delete(reply);
130         return EPROTO;
131     }
132     *multicast_group = nl_attr_get_u32(attrs[BRC_GENL_A_MC_GROUP]);
133     nl_sock_destroy(sock);
134     ofpbuf_delete(reply);
135
136     return 0;
137 }
138
139 /* Opens a socket for brcompat notifications.  Returns 0 if successful,
140  * otherwise a positive errno value. */
141 static int
142 brc_open(struct nl_sock **sock)
143 {
144     int multicast_group = 0;
145     int retval;
146
147     retval = nl_lookup_genl_family(BRC_GENL_FAMILY_NAME, &brc_family);
148     if (retval) {
149         return retval;
150     }
151
152     retval = lookup_brc_multicast_group(&multicast_group);
153     if (retval) {
154         return retval;
155     }
156
157     retval = nl_sock_create(NETLINK_GENERIC, multicast_group, 0, 0, sock);
158     if (retval) {
159         return retval;
160     }
161
162     return 0;
163 }
164
165 static const struct nl_policy brc_dp_policy[] = {
166     [BRC_GENL_A_DP_NAME] = { .type = NL_A_STRING },
167 };
168
169 static struct ovsrec_bridge *
170 find_bridge(const struct ovsrec_open_vswitch *ovs, const char *br_name)
171 {
172     size_t i;
173
174     for (i = 0; i < ovs->n_bridges; i++) {
175         if (!strcmp(br_name, ovs->bridges[i]->name)) {
176             return ovs->bridges[i];
177         }
178     }
179
180     return NULL;
181 }
182
183 static int
184 execute_appctl_command(const char *unixctl_command, char **output)
185 {
186     char *stdout_log, *stderr_log;
187     int error, status;
188     char *argv[5];
189
190     argv[0] = "/bin/sh";
191     argv[1] = "-c";
192     argv[2] = xasprintf(appctl_command, unixctl_command);
193     argv[3] = NULL;
194
195     /* Run process and log status. */
196     error = process_run_capture(argv, &stdout_log, &stderr_log, &status);
197     if (error) {
198         VLOG_ERR("failed to execute %s command via ovs-appctl: %s",
199                  unixctl_command, strerror(error));
200     } else if (status) {
201         char *msg = process_status_msg(status);
202         VLOG_ERR("ovs-appctl exited with error (%s)", msg);
203         free(msg);
204         error = ECHILD;
205     }
206
207     /* Deal with stdout_log. */
208     if (output) {
209         *output = stdout_log;
210     } else {
211         free(stdout_log);
212     }
213
214     /* Deal with stderr_log */
215     if (stderr_log && *stderr_log) {
216         VLOG_INFO("ovs-appctl wrote to stderr:\n%s", stderr_log);
217     }
218     free(stderr_log);
219
220     free(argv[2]);
221
222     return error;
223 }
224
225 static void
226 do_get_bridge_parts(const struct ovsrec_bridge *br, struct svec *parts, 
227                     int vlan, bool break_down_bonds)
228 {
229     struct svec ports;
230     size_t i, j;
231
232     svec_init(&ports);
233     for (i = 0; i < br->n_ports; i++) {
234         const struct ovsrec_port *port = br->ports[i];
235
236         svec_add(&ports, port->name);
237         if (vlan >= 0) {
238             int port_vlan = port->n_tag ? *port->tag : 0;
239             if (vlan != port_vlan) {
240                 continue;
241             }
242         }
243         if (break_down_bonds) {
244             for (j = 0; j < port->n_interfaces; j++) {
245                 const struct ovsrec_interface *iface = port->interfaces[j];
246                 svec_add(parts, iface->name);
247             }
248         } else {
249             svec_add(parts, port->name);
250         }
251     }
252     svec_destroy(&ports);
253 }
254
255 /* Add all the interfaces for 'bridge' to 'ifaces', breaking bonded interfaces
256  * down into their constituent parts.
257  *
258  * If 'vlan' < 0, all interfaces on 'bridge' are reported.  If 'vlan' == 0,
259  * then only interfaces for trunk ports or ports with implicit VLAN 0 are
260  * reported.  If 'vlan' > 0, only interfaces with implicit VLAN 'vlan' are
261  * reported.  */
262 static void
263 get_bridge_ifaces(const struct ovsrec_bridge *br, struct svec *ifaces, 
264                   int vlan)
265 {
266     do_get_bridge_parts(br, ifaces, vlan, true);
267 }
268
269 /* Add all the ports for 'bridge' to 'ports'.  Bonded ports are reported under
270  * the bond name, not broken down into their constituent interfaces.
271  *
272  * If 'vlan' < 0, all ports on 'bridge' are reported.  If 'vlan' == 0, then
273  * only trunk ports or ports with implicit VLAN 0 are reported.  If 'vlan' > 0,
274  * only port with implicit VLAN 'vlan' are reported.  */
275 static void
276 get_bridge_ports(const struct ovsrec_bridge *br, struct svec *ports, 
277                  int vlan)
278 {
279     do_get_bridge_parts(br, ports, vlan, false);
280 }
281
282 #if 0
283 /* Go through the configuration file and remove any ports that no longer
284  * exist associated with a bridge. */
285 static void
286 prune_ports(void)
287 {
288     int i, j;
289     struct svec bridges, delete;
290
291     if (cfg_lock(NULL, 0)) {
292         /* Couldn't lock config file. */
293         return;
294     }
295
296     svec_init(&bridges);
297     svec_init(&delete);
298     cfg_get_subsections(&bridges, "bridge");
299     for (i=0; i<bridges.n; i++) {
300         const char *br_name = bridges.names[i];
301         struct svec ifaces;
302
303         /* Check that each bridge interface exists. */
304         svec_init(&ifaces);
305         get_bridge_ifaces(br_name, &ifaces, -1);
306         for (j = 0; j < ifaces.n; j++) {
307             const char *iface_name = ifaces.names[j];
308
309             /* The local port and internal ports are created and destroyed by
310              * ovs-vswitchd itself, so don't bother checking for them at all.
311              * In practice, they might not exist if ovs-vswitchd hasn't
312              * finished reloading since the configuration file was updated. */
313             if (!strcmp(iface_name, br_name)
314                 || cfg_get_bool(0, "iface.%s.internal", iface_name)) {
315                 continue;
316             }
317
318             if (!netdev_exists(iface_name)) {
319                 VLOG_INFO_RL(&rl, "removing dead interface %s from %s",
320                              iface_name, br_name);
321                 svec_add(&delete, iface_name);
322             }
323         }
324         svec_destroy(&ifaces);
325     }
326     svec_destroy(&bridges);
327
328     if (delete.n) {
329         size_t i;
330
331         for (i = 0; i < delete.n; i++) {
332             cfg_del_match("bridge.*.port=%s", delete.names[i]);
333             cfg_del_match("bonding.*.slave=%s", delete.names[i]);
334         }
335         reload_config();
336         cfg_unlock();
337     } else {
338         cfg_unlock();
339     }
340     svec_destroy(&delete);
341 }
342 #endif
343
344 static struct ovsdb_idl_txn *
345 txn_from_openvswitch(const struct ovsrec_open_vswitch *ovs)
346 {
347     return ovsdb_idl_txn_get(&ovs->header_);
348 }
349
350 static bool
351 port_is_fake_bridge(const struct ovsrec_port *port)
352 {
353     return (port->fake_bridge
354             && port->tag
355             && *port->tag >= 1 && *port->tag <= 4095);
356 }
357
358 static void
359 ovs_insert_bridge(const struct ovsrec_open_vswitch *ovs,
360                   struct ovsrec_bridge *bridge)
361 {
362     struct ovsrec_bridge **bridges;
363     size_t i;     
364
365     bridges = xmalloc(sizeof *ovs->bridges * (ovs->n_bridges + 1));
366     for (i = 0; i < ovs->n_bridges; i++) {
367         bridges[i] = ovs->bridges[i];
368     }
369     bridges[ovs->n_bridges] = bridge;
370     ovsrec_open_vswitch_set_bridges(ovs, bridges, ovs->n_bridges + 1);
371     free(bridges);
372 }   
373
374 static int
375 add_bridge(const struct ovsrec_open_vswitch *ovs, const char *br_name)
376 {
377     struct ovsrec_bridge *br;
378     struct ovsrec_port *port;
379     struct ovsrec_interface *iface;
380
381     if (find_bridge(ovs, br_name)) {
382         VLOG_WARN("addbr %s: bridge %s exists", br_name, br_name);
383         return EEXIST;
384     } else if (netdev_exists(br_name)) {
385         size_t i;
386
387         for (i = 0; i < ovs->n_bridges; i++) {
388             size_t j;
389             struct ovsrec_bridge *br_cfg = ovs->bridges[i];
390
391             for (j = 0; j < br_cfg->n_ports; j++) {
392                 if (port_is_fake_bridge(br_cfg->ports[j])) {
393                     VLOG_WARN("addbr %s: %s exists as a fake bridge",
394                               br_name, br_name);
395                     return 0;
396                 }
397             }
398         }
399
400         VLOG_WARN("addbr %s: cannot create bridge %s because a network "
401                   "device named %s already exists",
402                   br_name, br_name, br_name);
403         return EEXIST;
404     }
405
406     iface = ovsrec_interface_insert(txn_from_openvswitch(ovs));
407     ovsrec_interface_set_name(iface, br_name);
408
409     port = ovsrec_port_insert(txn_from_openvswitch(ovs));
410     ovsrec_port_set_name(port, br_name);
411     ovsrec_port_set_interfaces(port, &iface, 1);
412     
413     br = ovsrec_bridge_insert(txn_from_openvswitch(ovs));
414     ovsrec_bridge_set_name(br, br_name);
415     ovsrec_bridge_set_ports(br, &port, 1);
416     
417     ovs_insert_bridge(ovs, br);
418
419     VLOG_INFO("addbr %s: success", br_name);
420
421     return 0;
422 }
423
424 static void
425 add_port(const struct ovsrec_open_vswitch *ovs, 
426          const struct ovsrec_bridge *br, const char *port_name)
427 {
428     struct ovsrec_interface *iface;
429     struct ovsrec_port *port;
430     struct ovsrec_port **ports;
431     size_t i;
432
433     /* xxx Check conflicts? */
434     iface = ovsrec_interface_insert(txn_from_openvswitch(ovs));
435     ovsrec_interface_set_name(iface, port_name);
436
437     port = ovsrec_port_insert(txn_from_openvswitch(ovs));
438     ovsrec_port_set_name(port, port_name);
439     ovsrec_port_set_interfaces(port, &iface, 1);
440
441     ports = xmalloc(sizeof *br->ports * (br->n_ports + 1));
442     for (i = 0; i < br->n_ports; i++) {
443         ports[i] = br->ports[i];
444     }
445     ports[br->n_ports] = port;
446     ovsrec_bridge_set_ports(br, ports, br->n_ports + 1);
447     free(ports);
448 }
449
450 static void
451 del_port(const struct ovsrec_bridge *br, const char *port_name)
452 {
453     size_t i, j;
454     struct ovsrec_port *port_rec = NULL;
455
456     for (i = 0; i < br->n_ports; i++) {
457         struct ovsrec_port *port = br->ports[i];
458         if (!strcmp(port_name, port->name)) {
459             port_rec = port;
460         }
461         for (j = 0; j < port->n_interfaces; j++) {
462             struct ovsrec_interface *iface = port->interfaces[j];
463             if (!strcmp(port_name, iface->name)) {
464                 ovsrec_interface_delete(iface);
465             }
466         }
467     }
468
469     /* xxx Probably can move this into the "for" loop. */
470     if (port_rec) {
471         struct ovsrec_port **ports;
472         size_t n;
473
474         ports = xmalloc(sizeof *br->ports * br->n_ports);
475         for (i = n = 0; i < br->n_ports; i++) {
476             if (br->ports[i] != port_rec) {
477                 ports[n++] = br->ports[i];
478             }
479         }
480         ovsrec_bridge_set_ports(br, ports, n);
481         free(ports);
482
483         ovsrec_port_delete(port_rec);
484     }
485 }
486
487 static int 
488 del_bridge(const struct ovsrec_open_vswitch *ovs, const char *br_name)
489 {
490     struct ovsrec_bridge *br = find_bridge(ovs, br_name);
491     struct ovsrec_bridge **bridges;
492     size_t i, n;
493
494     if (!br) {
495         VLOG_WARN("delbr %s: no bridge named %s", br_name, br_name);
496         return ENXIO;
497     }
498
499     del_port(br, br_name);
500
501     bridges = xmalloc(sizeof *ovs->bridges * ovs->n_bridges);
502     for (i = n = 0; i < ovs->n_bridges; i++) {
503         if (ovs->bridges[i] != br) {
504             bridges[n++] = ovs->bridges[i];
505         }
506     }
507     ovsrec_open_vswitch_set_bridges(ovs, bridges, n);
508     free(bridges);
509
510     /* Delete the bridge itself. */
511     ovsrec_bridge_delete(br);
512
513     VLOG_INFO("delbr %s: success", br_name);
514
515     return 0;
516 }
517
518 static int
519 parse_command(struct ofpbuf *buffer, uint32_t *seq, const char **br_name,
520               const char **port_name, uint64_t *count, uint64_t *skip)
521 {
522     static const struct nl_policy policy[] = {
523         [BRC_GENL_A_DP_NAME] = { .type = NL_A_STRING, .optional = true },
524         [BRC_GENL_A_PORT_NAME] = { .type = NL_A_STRING, .optional = true },
525         [BRC_GENL_A_FDB_COUNT] = { .type = NL_A_U64, .optional = true },
526         [BRC_GENL_A_FDB_SKIP] = { .type = NL_A_U64, .optional = true },
527     };
528     struct nlattr *attrs[ARRAY_SIZE(policy)];
529
530     if (!nl_policy_parse(buffer, NLMSG_HDRLEN + GENL_HDRLEN, policy,
531                          attrs, ARRAY_SIZE(policy))
532         || (br_name && !attrs[BRC_GENL_A_DP_NAME])
533         || (port_name && !attrs[BRC_GENL_A_PORT_NAME])
534         || (count && !attrs[BRC_GENL_A_FDB_COUNT])
535         || (skip && !attrs[BRC_GENL_A_FDB_SKIP])) {
536         return EINVAL;
537     }
538
539     *seq = ((struct nlmsghdr *) buffer->data)->nlmsg_seq;
540     if (br_name) {
541         *br_name = nl_attr_get_string(attrs[BRC_GENL_A_DP_NAME]);
542     }
543     if (port_name) {
544         *port_name = nl_attr_get_string(attrs[BRC_GENL_A_PORT_NAME]);
545     }
546     if (count) {
547         *count = nl_attr_get_u64(attrs[BRC_GENL_A_FDB_COUNT]);
548     }
549     if (skip) {
550         *skip = nl_attr_get_u64(attrs[BRC_GENL_A_FDB_SKIP]);
551     }
552     return 0;
553 }
554
555 /* Composes and returns a reply to a request made by the datapath with Netlink
556  * sequence number 'seq' and error code 'error'.  The caller may add additional
557  * attributes to the message, then it may send it with send_reply(). */
558 static struct ofpbuf *
559 compose_reply(uint32_t seq, int error)
560 {
561     struct ofpbuf *reply = ofpbuf_new(4096);
562     nl_msg_put_genlmsghdr(reply, brc_sock, 32, brc_family, NLM_F_REQUEST,
563                           BRC_GENL_C_DP_RESULT, 1);
564     ((struct nlmsghdr *) reply->data)->nlmsg_seq = seq;
565     nl_msg_put_u32(reply, BRC_GENL_A_ERR_CODE, error);
566     return reply;
567 }
568
569 /* Sends 'reply' to the datapath and frees it. */
570 static void
571 send_reply(struct ofpbuf *reply)
572 {
573     int retval = nl_sock_send(brc_sock, reply, false);
574     if (retval) {
575         VLOG_WARN_RL(&rl, "replying to brcompat request: %s",
576                      strerror(retval));
577     }
578     ofpbuf_delete(reply);
579 }
580
581 /* Composes and sends a reply to a request made by the datapath with Netlink
582  * sequence number 'seq' and error code 'error'. */
583 static void
584 send_simple_reply(uint32_t seq, int error)
585 {
586     send_reply(compose_reply(seq, error));
587 }
588
589 static int
590 handle_bridge_cmd(const struct ovsrec_open_vswitch *ovs, 
591                   struct ofpbuf *buffer, bool add)
592 {
593     const char *br_name;
594     uint32_t seq;
595     int error;
596
597     error = parse_command(buffer, &seq, &br_name, NULL, NULL, NULL);
598     if (!error) {
599         error = add ? add_bridge(ovs, br_name) : del_bridge(ovs, br_name);
600         send_simple_reply(seq, error);
601     }
602     return error;
603 }
604
605 static const struct nl_policy brc_port_policy[] = {
606     [BRC_GENL_A_DP_NAME] = { .type = NL_A_STRING },
607     [BRC_GENL_A_PORT_NAME] = { .type = NL_A_STRING },
608 };
609
610 static int
611 handle_port_cmd(const struct ovsrec_open_vswitch *ovs,
612                 struct ofpbuf *buffer, bool add)
613 {
614     const char *cmd_name = add ? "add-if" : "del-if";
615     const char *br_name, *port_name;
616     uint32_t seq;
617     int error;
618
619     error = parse_command(buffer, &seq, &br_name, &port_name, NULL, NULL);
620     if (!error) {
621         struct ovsrec_bridge *br = find_bridge(ovs, br_name);
622
623         if (!br) {
624             VLOG_WARN("%s %s %s: no bridge named %s",
625                       cmd_name, br_name, port_name, br_name);
626             error = EINVAL;
627         } else if (!netdev_exists(port_name)) {
628             VLOG_WARN("%s %s %s: no network device named %s",
629                       cmd_name, br_name, port_name, port_name);
630             error = EINVAL;
631         } else {
632             if (add) {
633                 add_port(ovs, br, port_name);
634             } else {
635                 del_port(br, port_name);
636             }
637             VLOG_INFO("%s %s %s: success", cmd_name, br_name, port_name);
638         }
639         send_simple_reply(seq, error);
640     }
641
642     return error;
643 }
644
645 /* The caller is responsible for freeing '*ovs_name' if the call is
646  * successful. */
647 static int
648 linux_bridge_to_ovs_bridge(const struct ovsrec_open_vswitch *ovs,
649                            const char *linux_name,
650                            const struct ovsrec_bridge **ovs_bridge,
651                            int *br_vlan)
652 {
653     *ovs_bridge = find_bridge(ovs, linux_name);
654     if (*ovs_bridge) {
655         /* Bridge name is the same.  We are interested in VLAN 0. */
656         *br_vlan = 0;
657         return 0;
658     } else {
659         /* No such Open vSwitch bridge 'linux_name', but there might be an
660          * internal port named 'linux_name' on some other bridge
661          * 'ovs_bridge'.  If so then we are interested in the VLAN assigned to
662          * port 'linux_name' on the bridge named 'ovs_bridge'. */
663         size_t i, j;
664
665         for (i = 0; i < ovs->n_bridges; i++) {
666             const struct ovsrec_bridge *br = ovs->bridges[i];
667
668             for (j = 0; j < br->n_ports; j++) {
669                 const struct ovsrec_port *port = br->ports[j];
670
671                 if (!strcmp(port->name, linux_name)) {
672                     *ovs_bridge = br;
673                     *br_vlan = port->n_tag ? *port->tag : -1;
674                     return 0;
675                 }
676             }
677
678         }
679         return ENODEV;
680     }
681 }
682
683 static int
684 handle_fdb_query_cmd(const struct ovsrec_open_vswitch *ovs,
685                      struct ofpbuf *buffer)
686 {
687     /* This structure is copied directly from the Linux 2.6.30 header files.
688      * It would be more straightforward to #include <linux/if_bridge.h>, but
689      * the 'port_hi' member was only introduced in Linux 2.6.26 and so systems
690      * with old header files won't have it. */
691     struct __fdb_entry {
692         __u8 mac_addr[6];
693         __u8 port_no;
694         __u8 is_local;
695         __u32 ageing_timer_value;
696         __u8 port_hi;
697         __u8 pad0;
698         __u16 unused;
699     };
700
701     struct mac {
702         uint8_t addr[6];
703     };
704     struct mac *local_macs;
705     int n_local_macs;
706     int i;
707
708     /* Impedance matching between the vswitchd and Linux kernel notions of what
709      * a bridge is.  The kernel only handles a single VLAN per bridge, but
710      * vswitchd can deal with all the VLANs on a single bridge.  We have to
711      * pretend that the former is the case even though the latter is the
712      * implementation. */
713     const char *linux_name;   /* Name used by brctl. */
714     const struct ovsrec_bridge *ovs_bridge;  /* Bridge used by ovs-vswitchd. */
715     int br_vlan;                /* VLAN tag. */
716     struct svec ifaces;
717
718     struct ofpbuf query_data;
719     struct ofpbuf *reply;
720     char *unixctl_command;
721     uint64_t count, skip;
722     char *output;
723     char *save_ptr;
724     uint32_t seq;
725     int error;
726
727     /* Parse the command received from brcompat_mod. */
728     error = parse_command(buffer, &seq, &linux_name, NULL, &count, &skip);
729     if (error) {
730         return error;
731     }
732
733     /* Figure out vswitchd bridge and VLAN. */
734     error = linux_bridge_to_ovs_bridge(ovs, linux_name, 
735                                        &ovs_bridge, &br_vlan);
736     if (error) {
737         send_simple_reply(seq, error);
738         return error;
739     }
740
741     /* Fetch the forwarding database using ovs-appctl. */
742     unixctl_command = xasprintf("fdb/show %s", ovs_bridge->name);
743     error = execute_appctl_command(unixctl_command, &output);
744     free(unixctl_command);
745     if (error) {
746         send_simple_reply(seq, error);
747         return error;
748     }
749
750     /* Fetch the MAC address for each interface on the bridge, so that we can
751      * fill in the is_local field in the response. */
752     svec_init(&ifaces);
753     get_bridge_ifaces(ovs_bridge, &ifaces, br_vlan);
754     local_macs = xmalloc(ifaces.n * sizeof *local_macs);
755     n_local_macs = 0;
756     for (i = 0; i < ifaces.n; i++) {
757         const char *iface_name = ifaces.names[i];
758         struct mac *mac = &local_macs[n_local_macs];
759         struct netdev *netdev;
760
761         error = netdev_open_default(iface_name, &netdev);
762         if (!error) {
763             if (!netdev_get_etheraddr(netdev, mac->addr)) {
764                 n_local_macs++;
765             }
766             netdev_close(netdev);
767         }
768     }
769     svec_destroy(&ifaces);
770
771     /* Parse the response from ovs-appctl and convert it to binary format to
772      * pass back to the kernel. */
773     ofpbuf_init(&query_data, sizeof(struct __fdb_entry) * 8);
774     save_ptr = NULL;
775     strtok_r(output, "\n", &save_ptr); /* Skip header line. */
776     while (count > 0) {
777         struct __fdb_entry *entry;
778         int port, vlan, age;
779         uint8_t mac[ETH_ADDR_LEN];
780         char *line;
781         bool is_local;
782
783         line = strtok_r(NULL, "\n", &save_ptr);
784         if (!line) {
785             break;
786         }
787
788         if (sscanf(line, "%d %d "ETH_ADDR_SCAN_FMT" %d",
789                    &port, &vlan, ETH_ADDR_SCAN_ARGS(mac), &age)
790             != 2 + ETH_ADDR_SCAN_COUNT + 1) {
791             struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
792             VLOG_INFO_RL(&rl, "fdb/show output has invalid format: %s", line);
793             continue;
794         }
795
796         if (vlan != br_vlan) {
797             continue;
798         }
799
800         if (skip > 0) {
801             skip--;
802             continue;
803         }
804
805         /* Is this the MAC address of an interface on the bridge? */
806         is_local = false;
807         for (i = 0; i < n_local_macs; i++) {
808             if (eth_addr_equals(local_macs[i].addr, mac)) {
809                 is_local = true;
810                 break;
811             }
812         }
813
814         entry = ofpbuf_put_uninit(&query_data, sizeof *entry);
815         memcpy(entry->mac_addr, mac, ETH_ADDR_LEN);
816         entry->port_no = port & 0xff;
817         entry->is_local = is_local;
818         entry->ageing_timer_value = age * HZ;
819         entry->port_hi = (port & 0xff00) >> 8;
820         entry->pad0 = 0;
821         entry->unused = 0;
822         count--;
823     }
824     free(output);
825
826     /* Compose and send reply to datapath. */
827     reply = compose_reply(seq, 0);
828     nl_msg_put_unspec(reply, BRC_GENL_A_FDB_DATA,
829                       query_data.data, query_data.size);
830     send_reply(reply);
831
832     /* Free memory. */
833     ofpbuf_uninit(&query_data);
834
835     return 0;
836 }
837
838 static void
839 send_ifindex_reply(uint32_t seq, struct svec *ifaces)
840 {
841     struct ofpbuf *reply;
842     const char *iface;
843     size_t n_indices;
844     int *indices;
845     size_t i;
846
847     /* Make sure that any given interface only occurs once.  This shouldn't
848      * happen, but who knows what people put into their configuration files. */
849     svec_sort_unique(ifaces);
850
851     /* Convert 'ifaces' into ifindexes. */
852     n_indices = 0;
853     indices = xmalloc(ifaces->n * sizeof *indices);
854     SVEC_FOR_EACH (i, iface, ifaces) {
855         int ifindex = if_nametoindex(iface);
856         if (ifindex) {
857             indices[n_indices++] = ifindex;
858         }
859     }
860
861     /* Compose and send reply. */
862     reply = compose_reply(seq, 0);
863     nl_msg_put_unspec(reply, BRC_GENL_A_IFINDEXES,
864                       indices, n_indices * sizeof *indices);
865     send_reply(reply);
866
867     /* Free memory. */
868     free(indices);
869 }
870
871 static int
872 handle_get_bridges_cmd(const struct ovsrec_open_vswitch *ovs,
873                        struct ofpbuf *buffer)
874 {
875     struct svec bridges;
876     size_t i, j;
877
878     uint32_t seq;
879
880     int error;
881
882     /* Parse Netlink command.
883      *
884      * The command doesn't actually have any arguments, but we need the
885      * sequence number to send the reply. */
886     error = parse_command(buffer, &seq, NULL, NULL, NULL, NULL);
887     if (error) {
888         return error;
889     }
890
891     /* Get all the real bridges and all the fake ones. */
892     svec_init(&bridges);
893     for (i = 0; i < ovs->n_bridges; i++) {
894         const struct ovsrec_bridge *br = ovs->bridges[i];
895
896         svec_add(&bridges, br->name);
897         for (j = 0; j < br->n_ports; j++) {
898             const struct ovsrec_port *port = br->ports[j];
899
900             if (port->fake_bridge) {
901                 svec_add(&bridges, port->name);
902             }
903         }
904     }
905
906     send_ifindex_reply(seq, &bridges);
907     svec_destroy(&bridges);
908
909     return 0;
910 }
911
912 static int
913 handle_get_ports_cmd(const struct ovsrec_open_vswitch *ovs,
914                      struct ofpbuf *buffer)
915 {
916     uint32_t seq;
917
918     const char *linux_name;
919     const struct ovsrec_bridge *ovs_bridge;
920     int br_vlan;
921
922     struct svec ports;
923
924     int error;
925
926     /* Parse Netlink command. */
927     error = parse_command(buffer, &seq, &linux_name, NULL, NULL, NULL);
928     if (error) {
929         return error;
930     }
931
932     error = linux_bridge_to_ovs_bridge(ovs, linux_name, 
933                                        &ovs_bridge, &br_vlan);
934     if (error) {
935         send_simple_reply(seq, error);
936         return error;
937     }
938
939     svec_init(&ports);
940     get_bridge_ports(ovs_bridge, &ports, br_vlan);
941     svec_sort(&ports);
942     svec_del(&ports, linux_name);
943     send_ifindex_reply(seq, &ports); /* XXX bonds won't show up */
944     svec_destroy(&ports);
945
946     return 0;
947 }
948
949 static void
950 brc_recv_update(const struct ovsrec_open_vswitch *ovs)
951 {
952     int retval;
953     struct ofpbuf *buffer;
954     struct genlmsghdr *genlmsghdr;
955
956
957     buffer = NULL;
958     do {
959         ofpbuf_delete(buffer);
960         retval = nl_sock_recv(brc_sock, &buffer, false);
961     } while (retval == ENOBUFS
962             || (!retval
963                 && (nl_msg_nlmsgerr(buffer, NULL)
964                     || nl_msg_nlmsghdr(buffer)->nlmsg_type == NLMSG_DONE)));
965     if (retval) {
966         if (retval != EAGAIN) {
967             VLOG_WARN_RL(&rl, "brc_recv_update: %s", strerror(retval));
968         }
969         return;
970     }
971
972     genlmsghdr = nl_msg_genlmsghdr(buffer);
973     if (!genlmsghdr) {
974         VLOG_WARN_RL(&rl, "received packet too short for generic NetLink");
975         goto error;
976     }
977
978     if (nl_msg_nlmsghdr(buffer)->nlmsg_type != brc_family) {
979         VLOG_DBG_RL(&rl, "received type (%"PRIu16") != brcompat family (%d)",
980                 nl_msg_nlmsghdr(buffer)->nlmsg_type, brc_family);
981         goto error;
982     }
983
984     /* Just drop the request on the floor if a valid configuration
985      * doesn't exist.  We don't immediately do this check, because we
986      * want to drain pending netlink messages. */
987     if (!ovs) {
988         VLOG_WARN_RL(&rl, "could not find valid configuration to update");
989         goto error;
990     }
991
992     switch (genlmsghdr->cmd) {
993     case BRC_GENL_C_DP_ADD:
994         handle_bridge_cmd(ovs, buffer, true);
995         break;
996
997     case BRC_GENL_C_DP_DEL:
998         handle_bridge_cmd(ovs, buffer, false);
999         break;
1000
1001     case BRC_GENL_C_PORT_ADD:
1002         handle_port_cmd(ovs, buffer, true);
1003         break;
1004
1005     case BRC_GENL_C_PORT_DEL:
1006         handle_port_cmd(ovs, buffer, false);
1007         break;
1008
1009     case BRC_GENL_C_FDB_QUERY:
1010         handle_fdb_query_cmd(ovs, buffer);
1011         break;
1012
1013     case BRC_GENL_C_GET_BRIDGES:
1014         handle_get_bridges_cmd(ovs, buffer);
1015         break;
1016
1017     case BRC_GENL_C_GET_PORTS:
1018         handle_get_ports_cmd(ovs, buffer);
1019         break;
1020
1021     default:
1022         VLOG_WARN_RL(&rl, "received unknown brc netlink command: %d\n",
1023                 genlmsghdr->cmd);
1024         break;
1025     }
1026
1027 error:
1028     ofpbuf_delete(buffer);
1029     return;
1030 }
1031
1032 /* Check for interface configuration changes announced through RTNL. */
1033 static void
1034 rtnl_recv_update(const struct ovsrec_open_vswitch *ovs)
1035 {
1036     struct ofpbuf *buf;
1037
1038     int error = nl_sock_recv(rtnl_sock, &buf, false);
1039     if (error == EAGAIN) {
1040         /* Nothing to do. */
1041     } else if (error == ENOBUFS) {
1042         VLOG_WARN_RL(&rl, "network monitor socket overflowed");
1043     } else if (error) {
1044         VLOG_WARN_RL(&rl, "error on network monitor socket: %s", 
1045                 strerror(error));
1046     } else {
1047         struct nlattr *attrs[ARRAY_SIZE(rtnlgrp_link_policy)];
1048         struct nlmsghdr *nlh;
1049         struct ifinfomsg *iim;
1050
1051         nlh = ofpbuf_at(buf, 0, NLMSG_HDRLEN);
1052         iim = ofpbuf_at(buf, NLMSG_HDRLEN, sizeof *iim);
1053         if (!iim) {
1054             VLOG_WARN_RL(&rl, "received bad rtnl message (no ifinfomsg)");
1055             ofpbuf_delete(buf);
1056             return;
1057         } 
1058     
1059         if (!nl_policy_parse(buf, NLMSG_HDRLEN + sizeof(struct ifinfomsg),
1060                              rtnlgrp_link_policy,
1061                              attrs, ARRAY_SIZE(rtnlgrp_link_policy))) {
1062             VLOG_WARN_RL(&rl,"received bad rtnl message (policy)");
1063             ofpbuf_delete(buf);
1064             return;
1065         }
1066         if (nlh->nlmsg_type == RTM_DELLINK && attrs[IFLA_MASTER]) {
1067             const char *port_name = nl_attr_get_string(attrs[IFLA_IFNAME]);
1068             char br_name[IFNAMSIZ];
1069             uint32_t br_idx = nl_attr_get_u32(attrs[IFLA_MASTER]);
1070
1071             if (!if_indextoname(br_idx, br_name)) {
1072                 ofpbuf_delete(buf);
1073                 return;
1074             }
1075
1076             if (!netdev_exists(port_name)) {
1077                 /* Network device is really gone. */
1078                 struct ovsrec_bridge *br = find_bridge(ovs, br_name);
1079
1080                 VLOG_INFO("network device %s destroyed, "
1081                           "removing from bridge %s", port_name, br_name);
1082
1083                 if (!br) {
1084                     VLOG_WARN("no bridge named %s from which to remove %s", 
1085                             br_name, port_name);
1086                     ofpbuf_delete(buf);
1087                     return;
1088                 }
1089
1090                 del_port(br, port_name);
1091             } else {
1092                 /* A network device by that name exists even though the kernel
1093                  * told us it had disappeared.  Probably, what happened was
1094                  * this:
1095                  *
1096                  *      1. Device destroyed.
1097                  *      2. Notification sent to us.
1098                  *      3. New device created with same name as old one.
1099                  *      4. ovs-brcompatd notified, removes device from bridge.
1100                  *
1101                  * There's no a priori reason that in this situation that the
1102                  * new device with the same name should remain in the bridge;
1103                  * on the contrary, that would be unexpected.  *But* there is
1104                  * one important situation where, if we do this, bad things
1105                  * happen.  This is the case of XenServer Tools version 5.0.0,
1106                  * which on boot of a Windows VM cause something like this to
1107                  * happen on the Xen host:
1108                  *
1109                  *      i. Create tap1.0 and vif1.0.
1110                  *      ii. Delete tap1.0.
1111                  *      iii. Delete vif1.0.
1112                  *      iv. Re-create vif1.0.
1113                  *
1114                  * (XenServer Tools 5.5.0 does not exhibit this behavior, and
1115                  * neither does a VM without Tools installed at all.@.)
1116                  *
1117                  * Steps iii and iv happen within a few seconds of each other.
1118                  * Step iv causes /etc/xensource/scripts/vif to run, which in
1119                  * turn calls ovs-cfg-mod to add the new device to the bridge.
1120                  * If step iv happens after step 4 (in our first list of
1121                  * steps), then all is well, but if it happens between 3 and 4
1122                  * (which can easily happen if ovs-brcompatd has to wait to
1123                  * lock the configuration file), then we will remove the new
1124                  * incarnation from the bridge instead of the old one!
1125                  *
1126                  * So, to avoid this problem, we do nothing here.  This is
1127                  * strictly incorrect except for this one particular case, and
1128                  * perhaps that will bite us someday.  If that happens, then we
1129                  * will have to somehow track network devices by ifindex, since
1130                  * a new device will have a new ifindex even if it has the same
1131                  * name as an old device.
1132                  */
1133                 VLOG_INFO("kernel reported network device %s removed but "
1134                           "a device by that name exists (XS Tools 5.0.0?)",
1135                           port_name);
1136             }
1137         }
1138         ofpbuf_delete(buf);
1139     }
1140 }
1141
1142 int
1143 main(int argc, char *argv[])
1144 {
1145     struct unixctl_server *unixctl;
1146     const char *remote;
1147     struct ovsdb_idl *idl;
1148     int retval;
1149
1150     proctitle_init(argc, argv);
1151     set_program_name(argv[0]);
1152     time_init();
1153     vlog_init();
1154     vlog_set_levels(VLM_ANY_MODULE, VLF_CONSOLE, VLL_WARN);
1155     vlog_set_levels(VLM_reconnect, VLF_ANY_FACILITY, VLL_WARN);
1156
1157     remote = parse_options(argc, argv);
1158     signal(SIGPIPE, SIG_IGN);
1159     process_init();
1160     ovsrec_init();
1161
1162     die_if_already_running();
1163     daemonize_start();
1164
1165     retval = unixctl_server_create(NULL, &unixctl);
1166     if (retval) {
1167         exit(EXIT_FAILURE);
1168     }
1169
1170     if (brc_open(&brc_sock)) {
1171         ovs_fatal(0, "could not open brcompat socket.  Check "
1172                 "\"brcompat\" kernel module.");
1173     }
1174
1175     if (prune_timeout) {
1176         if (nl_sock_create(NETLINK_ROUTE, RTNLGRP_LINK, 0, 0, &rtnl_sock)) {
1177             ovs_fatal(0, "could not create rtnetlink socket");
1178         }
1179     }
1180
1181     daemonize_complete();
1182
1183     idl = ovsdb_idl_create(remote, &ovsrec_idl_class);
1184
1185     for (;;) {
1186         const struct ovsrec_open_vswitch *ovs;
1187         struct ovsdb_idl_txn *txn;
1188         enum ovsdb_idl_txn_status status;
1189
1190         ovsdb_idl_run(idl);
1191
1192         txn = ovsdb_idl_txn_create(idl);
1193
1194         unixctl_server_run(unixctl);
1195         ovs = ovsrec_open_vswitch_first(idl);
1196         brc_recv_update(ovs);
1197
1198         if (!ovs && ovsdb_idl_has_ever_connected(idl)) {
1199             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
1200             VLOG_WARN_RL(&rl, "%s: database does not contain any Open vSwitch "
1201                          "configuration", remote);
1202         }
1203         netdev_run();
1204
1205         /* If 'prune_timeout' is non-zero, we actively prune from the
1206          * configuration of port entries that are no longer valid.  We 
1207          * use two methods: 
1208          *
1209          *   1) The kernel explicitly notifies us of removed ports
1210          *      through the RTNL messages.
1211          *
1212          *   2) We periodically check all ports associated with bridges
1213          *      to see if they no longer exist.
1214          */
1215         if (ovs && prune_timeout) {
1216             rtnl_recv_update(ovs);
1217 #if 0
1218             prune_ports();
1219 #endif
1220
1221             nl_sock_wait(rtnl_sock, POLLIN);
1222             poll_timer_wait(prune_timeout);
1223         }
1224
1225         while ((status = ovsdb_idl_txn_commit(txn)) == TXN_INCOMPLETE) {
1226             ovsdb_idl_run(idl);
1227             ovsdb_idl_wait(idl);
1228             ovsdb_idl_txn_wait(txn);
1229             poll_block();
1230         }
1231             
1232         switch (status) {
1233         case TXN_INCOMPLETE:
1234             NOT_REACHED();
1235         
1236         case TXN_ABORTED:
1237             /* Should not happen--we never call ovsdb_idl_txn_abort(). */
1238             ovs_fatal(0, "transaction aborted");
1239         
1240         case TXN_SUCCESS:
1241         case TXN_UNCHANGED:
1242             break;
1243         
1244         case TXN_TRY_AGAIN:
1245             /* xxx Handle this better! */
1246             VLOG_ERR("OVSDB transaction needs retry");
1247             break;
1248
1249         case TXN_ERROR:
1250             /* xxx Handle this better! */
1251             VLOG_ERR("OVSDB transaction failed: %s",
1252                      ovsdb_idl_txn_get_error(txn));
1253             break;
1254
1255         default:
1256             NOT_REACHED();
1257         }
1258         ovsdb_idl_txn_destroy(txn);
1259
1260         nl_sock_wait(brc_sock, POLLIN);
1261         ovsdb_idl_wait(idl);
1262         unixctl_server_wait(unixctl);
1263         netdev_wait();
1264         poll_block();
1265     }
1266
1267     ovsdb_idl_destroy(idl);
1268
1269     return 0;
1270 }
1271
1272 static void
1273 validate_appctl_command(void)
1274 {
1275     const char *p;
1276     int n;
1277
1278     n = 0;
1279     for (p = strchr(appctl_command, '%'); p; p = strchr(p + 2, '%')) {
1280         if (p[1] == '%') {
1281             /* Nothing to do. */
1282         } else if (p[1] == 's') {
1283             n++;
1284         } else {
1285             ovs_fatal(0, "only '%%s' and '%%%%' allowed in --appctl-command");
1286         }
1287     }
1288     if (n != 1) {
1289         ovs_fatal(0, "'%%s' must appear exactly once in --appctl-command");
1290     }
1291 }
1292
1293 static const char *
1294 parse_options(int argc, char *argv[])
1295 {
1296     enum {
1297         OPT_PRUNE_TIMEOUT,
1298         OPT_APPCTL_COMMAND,
1299         VLOG_OPTION_ENUMS,
1300         LEAK_CHECKER_OPTION_ENUMS
1301     };
1302     static struct option long_options[] = {
1303         {"help",             no_argument, 0, 'h'},
1304         {"version",          no_argument, 0, 'V'},
1305         {"prune-timeout",    required_argument, 0, OPT_PRUNE_TIMEOUT},
1306         {"appctl-command",   required_argument, 0, OPT_APPCTL_COMMAND},
1307         DAEMON_LONG_OPTIONS,
1308         VLOG_LONG_OPTIONS,
1309         LEAK_CHECKER_LONG_OPTIONS,
1310         {0, 0, 0, 0},
1311     };
1312     char *short_options = long_options_to_short_options(long_options);
1313
1314     appctl_command = xasprintf("%s/ovs-appctl %%s", ovs_bindir);
1315     for (;;) {
1316         int c;
1317
1318         c = getopt_long(argc, argv, short_options, long_options, NULL);
1319         if (c == -1) {
1320             break;
1321         }
1322
1323         switch (c) {
1324         case 'H':
1325         case 'h':
1326             usage();
1327
1328         case 'V':
1329             OVS_PRINT_VERSION(0, 0);
1330             exit(EXIT_SUCCESS);
1331
1332         case OPT_PRUNE_TIMEOUT:
1333             prune_timeout = atoi(optarg) * 1000;
1334             break;
1335
1336         case OPT_APPCTL_COMMAND:
1337             appctl_command = optarg;
1338             break;
1339
1340         VLOG_OPTION_HANDLERS
1341         DAEMON_OPTION_HANDLERS
1342         LEAK_CHECKER_OPTION_HANDLERS
1343
1344         case '?':
1345             exit(EXIT_FAILURE);
1346
1347         default:
1348             abort();
1349         }
1350     }
1351     free(short_options);
1352
1353     validate_appctl_command();
1354
1355     argc -= optind;
1356     argv += optind;
1357
1358     if (argc != 1) {
1359         ovs_fatal(0, "database socket is non-option argument; "
1360                 "use --help for usage");
1361     }
1362
1363     return argv[0];
1364 }
1365
1366 static void
1367 usage(void)
1368 {
1369     printf("%s: bridge compatibility front-end for ovs-vswitchd\n"
1370            "usage: %s [OPTIONS] CONFIG\n"
1371            "CONFIG is the configuration file used by ovs-vswitchd.\n",
1372            program_name, program_name);
1373     printf("\nConfiguration options:\n"
1374            "  --appctl-command=COMMAND  shell command to run ovs-appctl\n"
1375            "  --prune-timeout=SECS    wait at most SECS before pruning ports\n"
1376           );
1377     daemon_usage();
1378     vlog_usage();
1379     printf("\nOther options:\n"
1380            "  -h, --help              display this help message\n"
1381            "  -V, --version           display version information\n");
1382     leak_checker_usage();
1383     printf("\nThe default appctl command is:\n%s\n", appctl_command);
1384     exit(EXIT_SUCCESS);
1385 }