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