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