1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
4 * We are making the OpenFlow specification and associated documentation
5 * (Software) available for public use and benefit with the expectation
6 * that others will use, modify and enhance the Software and contribute
7 * those enhancements back to the community. However, since we would
8 * like to make the Software available for broadest use, with as few
9 * restrictions as possible permission is hereby granted, free of
10 * charge, to any person obtaining a copy of this Software to deal in
11 * the Software under the copyrights without restriction, including
12 * without limitation the rights to use, copy, modify, merge, publish,
13 * distribute, sublicense, and/or sell copies of the Software, and to
14 * permit persons to whom the Software is furnished to do so, subject to
15 * the following conditions:
17 * The above copyright notice and this permission notice shall be
18 * included in all copies or substantial portions of the Software.
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 * The name and trademarks of copyright holder(s) may NOT be used in
30 * advertising or publicity pertaining to the Software or any
31 * derivatives without specific, written prior permission.
37 #include <netinet/in.h>
46 #include "command-line.h"
50 #include "dhcp-client.h"
53 #include "learning-switch.h"
55 #include "mac-learning.h"
59 #include "poll-loop.h"
62 #include "vconn-ssl.h"
64 #include "vlog-socket.h"
67 #define THIS_MODULE VLM_secchan
69 #include "ofp-print.h"
71 static const char *listen_vconn_name;
78 /* Behavior when the connection to the controller fails. */
80 FAIL_OPEN, /* Act as learning switch. */
81 FAIL_CLOSED /* Drop all packets. */
89 struct half halves[2];
92 struct lswitch *lswitch;
95 static struct list relays = LIST_INITIALIZER(&relays);
97 /* Mode of operation. Note that autodiscovery implies in-band
99 static bool autodiscovery; /* Discover the controller automatically? */
100 static bool in_band; /* Connect to controller in-band? */
102 /* MAC address of local port. */
103 static uint8_t local_mac[ETH_ADDR_LEN];
105 /* MAC learning table for local port. */
106 static struct mac_learning *local_ml;
108 /* Controller vconn name, or null to perform controller autodiscovery. */
109 static char *controller_name = NULL;
111 /* -f, --fail: Behavior when the connection to the controller fails. */
112 static enum fail_mode fail_mode = FAIL_OPEN;
114 /* The OpenFlow virtual network device ofX. */
115 static struct netdev *of_device;
117 /* --inactivity-probe: Number of seconds without receiving a message from the
118 controller before sending an inactivity probe. */
119 static int probe_interval = 15;
121 /* --max-idle: Idle time to assign to flows created by learning switch when in
123 static int max_idle = 15;
125 /* --max-backoff: Maximum interval between controller connection attempts, in
127 static int max_backoff = 15;
129 /* DHCP client, for controller autodiscovery. */
130 static struct dhclient *dhcp;
132 /* --accept-vconn: Regular expression specifying the class of controller vconns
133 * that we will accept during autodiscovery. */
134 static const char *accept_controller_re;
135 static regex_t accept_controller_regex;
137 static void parse_options(int argc, char *argv[]);
138 static void usage(void) NO_RETURN;
140 static void new_management_connection(const char *nl_name, struct vconn *new_remote);
141 static struct relay *relay_create(struct rconn *local, struct rconn *remote,
143 static void relay_run(struct relay *);
144 static void relay_wait(struct relay *);
145 static void relay_destroy(struct relay *);
147 static bool local_hook(struct relay *r);
148 static bool failing_open(struct relay *r);
149 static bool fail_open_hook(struct relay *r);
151 static void modify_dhcp_request(struct dhcp_msg *, void *aux);
152 static bool validate_dhcp_offer(const struct dhcp_msg *, void *aux);
155 main(int argc, char *argv[])
157 struct rconn *local_rconn, *remote_rconn;
158 struct vconn *listen_vconn;
159 struct relay *controller_relay;
164 set_program_name(argv[0]);
165 register_fault_handlers();
167 parse_options(argc, argv);
171 if (argc < 1 || argc > 2) {
172 fatal(0, "need one or two non-option arguments; use --help for usage");
175 if (strncmp(nl_name, "nl:", 3)
176 || strlen(nl_name) < 4
177 || nl_name[strspn(nl_name + 3, "0123456789") + 3]) {
178 fatal(0, "%s: argument is not of the form \"nl:DP_IDX\"", nl_name);
180 controller_name = argc > 1 ? xstrdup(argv[1]) : NULL;
181 autodiscovery = controller_name == NULL;
183 if (!accept_controller_re) {
184 accept_controller_re = vconn_ssl_is_configured() ? "^ssl:.*" : ".*";
186 retval = regcomp(&accept_controller_regex, accept_controller_re,
187 REG_NOSUB | REG_EXTENDED);
189 size_t length = regerror(retval, &accept_controller_regex, NULL, 0);
190 char *buffer = xmalloc(length);
191 regerror(retval, &accept_controller_regex, buffer, length);
192 fatal(0, "%s: %s", accept_controller_re, buffer);
195 if (listen_vconn_name) {
196 retval = vconn_open(listen_vconn_name, &listen_vconn);
197 if (retval && retval != EAGAIN) {
198 fatal(retval, "opening %s", listen_vconn_name);
200 if (!vconn_is_passive(listen_vconn)) {
201 fatal(0, "%s is not a passive vconn", listen_vconn_name);
207 snprintf(of_name, sizeof of_name, "of%s", nl_name + 3);
208 retval = netdev_open(of_name, NETDEV_ETH_TYPE_NONE, &of_device);
210 enum netdev_flags flags;
213 retval = netdev_turn_flags_on(of_device, NETDEV_UP, true);
215 fatal(retval, "Could not bring %s device up", of_name);
219 retval = netdev_get_flags(of_device, &flags);
221 if (flags & NETDEV_UP) {
225 memcpy(local_mac, netdev_get_etheraddr(of_device),
227 if (netdev_get_in6(of_device, &in6)) {
228 VLOG_WARN("Ignoring IPv6 address on %s device: "
229 "IPv6 not supported", of_name);
231 local_ml = mac_learning_create();
234 error(retval, "Could not get flags for %s device", of_name);
237 error(retval, "Could not open %s device", of_name);
239 if (autodiscovery && !in_band) {
240 fatal(retval, "In autodiscovery mode but failed to configure "
245 retval = dhclient_create(of_name, modify_dhcp_request,
246 validate_dhcp_offer, NULL, &dhcp);
248 fatal(retval, "Failed to initialize DHCP client");
250 dhclient_init(dhcp, 0);
253 retval = vlog_server_listen(NULL, NULL);
255 fatal(retval, "Could not listen for vlog connections");
260 local_rconn = rconn_create(1, 0, max_backoff);
261 rconn_connect(local_rconn, nl_name);
263 remote_rconn = rconn_create(1, probe_interval, max_backoff);
264 if (controller_name) {
265 retval = rconn_connect(remote_rconn, controller_name);
266 if (retval == EAFNOSUPPORT) {
267 fatal(0, "No support for %s vconn", controller_name);
270 controller_relay = relay_create(local_rconn, remote_rconn, false);
275 LIST_FOR_EACH_SAFE (r, n, struct relay, node, &relays) {
280 struct vconn *new_remote;
281 retval = vconn_accept(listen_vconn, &new_remote);
283 if (retval != EAGAIN) {
284 VLOG_WARN("accept failed (%s)", strerror(retval));
288 new_management_connection(nl_name, new_remote);
291 if (controller_relay) {
292 /* FIXME: should also fail open when controller_relay is NULL. */
293 failing_open(controller_relay);
296 if (rconn_is_connectivity_questionable(remote_rconn)) {
297 dhclient_force_renew(dhcp, 15);
300 if (dhclient_changed(dhcp)) {
301 free(controller_name);
302 if (dhclient_is_bound(dhcp)) {
303 controller_name = dhcp_msg_get_string(
304 dhclient_get_config(dhcp),
305 DHCP_CODE_OFP_CONTROLLER_VCONN);
306 VLOG_WARN("%s: discovered controller",
308 rconn_connect(remote_rconn, controller_name);
309 } else if (controller_name) {
310 VLOG_WARN("%s: discover controller no longer available",
312 controller_name = NULL;
313 rconn_disconnect(remote_rconn);
318 /* Wait for something to happen. */
319 LIST_FOR_EACH (r, struct relay, node, &relays) {
323 vconn_accept_wait(listen_vconn);
335 new_management_connection(const char *nl_name, struct vconn *new_remote)
337 char *nl_name_without_subscription;
338 struct vconn *new_local;
339 struct rconn *r1, *r2;
342 /* nl:123 or nl:123:1 opens a netlink connection to local datapath 123. We
343 * only accept the former syntax in main().
345 * nl:123:0 opens a netlink connection to local datapath 123 without
346 * obtaining a subscription for ofp_packet_in or ofp_flow_expired
348 nl_name_without_subscription = xasprintf("%s:0", nl_name);
349 retval = vconn_open(nl_name_without_subscription, &new_local);
351 VLOG_ERR("could not connect to %s (%s)",
352 nl_name_without_subscription, strerror(retval));
353 vconn_close(new_remote);
354 free(nl_name_without_subscription);
358 /* Add it to the relay list. */
359 r1 = rconn_create(1, 0, 0);
360 rconn_connect_unreliably(r1, nl_name_without_subscription, new_local);
361 r2 = rconn_create(1, 0, 0);
362 rconn_connect_unreliably(r2, "passive", new_remote);
363 relay_create(r1, r2, true);
365 free(nl_name_without_subscription);
368 static struct relay *
369 relay_create(struct rconn *local, struct rconn *remote, bool is_mgmt_conn)
374 r = xmalloc(sizeof *r);
375 r->halves[HALF_LOCAL].rconn = local;
376 r->halves[HALF_REMOTE].rconn = remote;
377 for (i = 0; i < 2; i++) {
378 r->halves[i].rxbuf = NULL;
380 r->is_mgmt_conn = is_mgmt_conn;
382 list_push_back(&relays, &r->node);
387 relay_run(struct relay *r)
392 for (i = 0; i < 2; i++) {
393 rconn_run(r->halves[i].rconn);
396 /* Limit the number of iterations to prevent other tasks from starving. */
397 for (iteration = 0; iteration < 50; iteration++) {
398 bool progress = false;
399 for (i = 0; i < 2; i++) {
400 struct half *this = &r->halves[i];
401 struct half *peer = &r->halves[!i];
404 this->rxbuf = rconn_recv(this->rconn);
405 if (this->rxbuf && !r->is_mgmt_conn && i == HALF_LOCAL
406 && (local_hook(r) || fail_open_hook(r))) {
407 buffer_delete(this->rxbuf);
413 int retval = rconn_send(peer->rconn, this->rxbuf);
414 if (retval != EAGAIN) {
418 buffer_delete(this->rxbuf);
429 if (r->is_mgmt_conn) {
430 for (i = 0; i < 2; i++) {
431 struct half *this = &r->halves[i];
432 if (!rconn_is_alive(this->rconn)) {
441 relay_wait(struct relay *r)
445 for (i = 0; i < 2; i++) {
446 struct half *this = &r->halves[i];
448 rconn_run_wait(this->rconn);
450 rconn_recv_wait(this->rconn);
456 relay_destroy(struct relay *r)
460 list_remove(&r->node);
461 for (i = 0; i < 2; i++) {
462 struct half *this = &r->halves[i];
463 rconn_destroy(this->rconn);
464 buffer_delete(this->rxbuf);
470 queue_tx(struct rconn *rc, struct buffer *b)
472 if (rconn_force_send(rc, b)) {
478 is_controller_mac(const uint8_t dl_addr[ETH_ADDR_LEN],
479 struct rconn *controller)
481 static uint32_t ip, last_nonzero_ip;
482 static uint8_t mac[ETH_ADDR_LEN], last_nonzero_mac[ETH_ADDR_LEN];
483 static time_t next_refresh = 0;
485 uint32_t last_ip = ip;
487 time_t now = time(0);
489 ip = rconn_get_ip(controller);
490 if (last_ip != ip || !next_refresh || now >= next_refresh) {
493 /* Look up MAC address. */
494 memset(mac, 0, sizeof mac);
496 int retval = netdev_arp_lookup(of_device, ip, mac);
498 VLOG_DBG("cannot look up controller hw address ("IP_FMT"): %s",
499 IP_ARGS(&ip), strerror(retval));
502 have_mac = !eth_addr_is_zero(mac);
504 /* Log changes in IP, MAC addresses. */
505 if (ip && ip != last_nonzero_ip) {
506 VLOG_DBG("controller IP address changed from "IP_FMT
507 " to "IP_FMT, IP_ARGS(&last_nonzero_ip), IP_ARGS(&ip));
508 last_nonzero_ip = ip;
510 if (have_mac && memcmp(last_nonzero_mac, mac, ETH_ADDR_LEN)) {
511 VLOG_DBG("controller MAC address changed from "ETH_ADDR_FMT" to "
513 ETH_ADDR_ARGS(last_nonzero_mac), ETH_ADDR_ARGS(mac));
514 memcpy(last_nonzero_mac, mac, ETH_ADDR_LEN);
517 /* Schedule next refresh.
519 * If we have an IP address but not a MAC address, then refresh
520 * quickly, since we probably will get a MAC address soon (via ARP).
521 * Otherwise, we can afford to wait a little while. */
522 next_refresh = now + (!ip || have_mac ? 10 : 1);
524 return !eth_addr_is_zero(mac) && eth_addr_equals(mac, dl_addr);
528 local_hook(struct relay *r)
530 struct rconn *rc = r->halves[HALF_LOCAL].rconn;
531 struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
532 struct ofp_packet_in *opi;
533 struct ofp_header *oh;
534 size_t pkt_ofs, pkt_len;
537 uint16_t in_port, out_port;
544 if (oh->type != OFPT_PACKET_IN) {
547 if (msg->size < offsetof (struct ofp_packet_in, data)) {
548 VLOG_WARN("packet too short (%zu bytes) for packet_in", msg->size);
552 /* Extract flow data from 'opi' into 'flow'. */
554 in_port = ntohs(opi->in_port);
555 pkt_ofs = offsetof(struct ofp_packet_in, data);
556 pkt_len = ntohs(opi->header.length) - pkt_ofs;
557 pkt.data = opi->data;
559 flow_extract(&pkt, in_port, &flow);
561 /* Deal with local stuff. */
562 if (in_port == OFPP_LOCAL) {
563 out_port = mac_learning_lookup(local_ml, flow.dl_dst);
564 } else if (eth_addr_equals(flow.dl_dst, local_mac)) {
565 out_port = OFPP_LOCAL;
566 if (mac_learning_learn(local_ml, flow.dl_src, in_port)) {
567 VLOG_DBG("learned that "ETH_ADDR_FMT" is on port %"PRIu16,
568 ETH_ADDR_ARGS(flow.dl_src), in_port);
570 } else if (flow.dl_type == htons(ETH_TYPE_ARP)
571 && eth_addr_is_broadcast(flow.dl_dst)
572 && is_controller_mac(flow.dl_src,
573 r->halves[HALF_REMOTE].rconn)) {
574 out_port = OFPP_FLOOD;
579 if (out_port != OFPP_FLOOD) {
580 /* The output port is known, so add a new flow. */
581 queue_tx(rc, make_add_simple_flow(&flow, ntohl(opi->buffer_id),
582 out_port, max_idle));
584 /* If the switch didn't buffer the packet, we need to send a copy. */
585 if (ntohl(opi->buffer_id) == UINT32_MAX) {
586 queue_tx(rc, make_unbuffered_packet_out(&pkt, in_port, out_port));
589 /* We don't know that MAC. Send along the packet without setting up a
592 if (ntohl(opi->buffer_id) == UINT32_MAX) {
593 b = make_unbuffered_packet_out(&pkt, in_port, out_port);
595 b = make_buffered_packet_out(ntohl(opi->buffer_id),
603 /* Causess 'r' to enter or leave fail-open mode, if appropriate. Returns true
604 * if 'r' is in fail-open fail, false otherwise. */
606 failing_open(struct relay *r)
608 struct rconn *local = r->halves[HALF_LOCAL].rconn;
609 struct rconn *remote = r->halves[HALF_REMOTE].rconn;
610 int disconnected_duration;
612 if (fail_mode == FAIL_CLOSED) {
613 /* We fail closed, so there's never anything to do. */
617 disconnected_duration = rconn_disconnected_duration(remote);
618 if (disconnected_duration < probe_interval * 3) {
619 /* It's not time to fail open yet. */
620 if (r->lswitch && rconn_is_connected(remote)) {
621 /* We're connected, so drop the learning switch. */
622 VLOG_WARN("No longer in fail-open mode");
623 lswitch_destroy(r->lswitch);
630 VLOG_WARN("Could not connect to controller for %d seconds, "
631 "failing open", disconnected_duration);
632 r->lswitch = lswitch_create(local, true, max_idle);
638 fail_open_hook(struct relay *r)
640 if (!failing_open(r)) {
643 struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
644 struct rconn *local = r->halves[HALF_LOCAL].rconn;
645 lswitch_process_packet(r->lswitch, local, msg);
652 modify_dhcp_request(struct dhcp_msg *msg, void *aux)
654 dhcp_msg_put_string(msg, DHCP_CODE_VENDOR_CLASS, "OpenFlow");
658 validate_dhcp_offer(const struct dhcp_msg *msg, void *aux)
663 vconn_name = dhcp_msg_get_string(msg, DHCP_CODE_OFP_CONTROLLER_VCONN);
665 VLOG_WARN("rejecting DHCP offer missing controller vconn");
668 accept = !regexec(&accept_controller_regex, vconn_name, 0, NULL, 0);
674 parse_options(int argc, char *argv[])
677 OPT_ACCEPT_VCONN = UCHAR_MAX + 1,
678 OPT_INACTIVITY_PROBE,
682 static struct option long_options[] = {
683 {"accept-vconn", required_argument, 0, OPT_ACCEPT_VCONN},
684 {"fail", required_argument, 0, 'f'},
685 {"inactivity-probe", required_argument, 0, OPT_INACTIVITY_PROBE},
686 {"max-idle", required_argument, 0, OPT_MAX_IDLE},
687 {"max-backoff", required_argument, 0, OPT_MAX_BACKOFF},
688 {"listen", required_argument, 0, 'l'},
689 {"detach", no_argument, 0, 'D'},
690 {"pidfile", optional_argument, 0, 'P'},
691 {"verbose", optional_argument, 0, 'v'},
692 {"help", no_argument, 0, 'h'},
693 {"version", no_argument, 0, 'V'},
694 VCONN_SSL_LONG_OPTIONS
697 char *short_options = long_options_to_short_options(long_options);
702 c = getopt_long(argc, argv, short_options, long_options, NULL);
708 case OPT_ACCEPT_VCONN:
709 accept_controller_re = (optarg[0] == '^'
711 : xasprintf("^%s", optarg));
715 if (!strcmp(optarg, "open")) {
716 fail_mode = FAIL_OPEN;
717 } else if (!strcmp(optarg, "closed")) {
718 fail_mode = FAIL_CLOSED;
721 "-f or --fail argument must be \"open\" or \"closed\"");
725 case OPT_INACTIVITY_PROBE:
726 probe_interval = atoi(optarg);
727 if (probe_interval < 5) {
728 fatal(0, "--inactivity-probe argument must be at least 5");
733 if (!strcmp(optarg, "permanent")) {
734 max_idle = OFP_FLOW_PERMANENT;
736 max_idle = atoi(optarg);
737 if (max_idle < 1 || max_idle > 65535) {
738 fatal(0, "--max-idle argument must be between 1 and "
739 "65535 or the word 'permanent'");
744 case OPT_MAX_BACKOFF:
745 max_backoff = atoi(optarg);
746 if (max_backoff < 1) {
747 fatal(0, "--max-backoff argument must be at least 1");
748 } else if (max_backoff > 3600) {
758 set_pidfile(optarg ? optarg : "secchan.pid");
762 if (listen_vconn_name) {
763 fatal(0, "-l or --listen may be only specified once");
765 listen_vconn_name = optarg;
772 printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
776 vlog_set_verbosity(optarg);
779 VCONN_SSL_OPTION_HANDLERS
794 printf("%s: secure channel, a relay for OpenFlow messages.\n"
795 "usage: %s [OPTIONS] nl:DP_IDX [CONTROLLER]\n"
796 "where nl:DP_IDX is a datapath that has been added with dpctl.\n"
797 "CONTROLLER is an active OpenFlow connection method; if it is\n"
798 "omitted, then secchan performs controller autodiscovery.\n",
799 program_name, program_name);
800 vconn_usage(true, true);
801 printf("\nNetworking options:\n"
802 " --accept-vconn=REGEX accept matching discovered controllers\n"
803 " -f, --fail=open|closed when controller connection fails:\n"
804 " closed: drop all packets\n"
805 " open (default): act as learning switch\n"
806 " --inactivity-probe=SECS time between inactivity probes\n"
807 " --max-idle=SECS max idle for flows set up by secchan\n"
808 " --max-backoff=SECS max time between controller connection\n"
809 " attempts (default: 15 seconds)\n"
810 " -l, --listen=METHOD allow management connections on METHOD\n"
811 " (a passive OpenFlow connection method)\n"
813 " -D, --detach run in background as daemon\n"
814 " -P, --pidfile[=FILE] create pidfile (default: %s/secchan.pid)\n"
815 " -v, --verbose=MODULE[:FACILITY[:LEVEL]] set logging levels\n"
816 " -v, --verbose set maximum verbosity level\n"
817 " -h, --help display this help message\n"
818 " -V, --version display version information\n",