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