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.
39 #include <netinet/in.h>
49 #include "command-line.h"
53 #include "dhcp-client.h"
54 #include "dynamic-string.h"
57 #include "learning-switch.h"
59 #include "mac-learning.h"
63 #include "poll-loop.h"
68 #include "vconn-ssl.h"
70 #include "vlog-socket.h"
73 #define THIS_MODULE VLM_secchan
75 /* Behavior when the connection to the controller fails. */
77 FAIL_OPEN, /* Act as learning switch. */
78 FAIL_CLOSED /* Drop all packets. */
81 /* Maximum number of management connection listeners. */
84 /* Settings that may be configured by the user. */
86 /* Overall mode of operation. */
87 bool discovery; /* Discover the controller automatically? */
88 bool in_band; /* Connect to controller in-band? */
90 /* Related vconns and network devices. */
91 const char *nl_name; /* Local datapath (must be "nl:" vconn). */
92 char *of_name; /* ofX network device name. */
93 const char *controller_name; /* Controller (if not discovery mode). */
94 const char *listener_names[MAX_MGMT]; /* Listen for mgmt connections. */
95 size_t n_listeners; /* Number of mgmt connection listeners. */
96 const char *monitor_name; /* Listen for traffic monitor connections. */
98 /* Failure behavior. */
99 enum fail_mode fail_mode; /* Act as learning switch if no controller? */
100 int max_idle; /* Idle time for flows in fail-open mode. */
101 int probe_interval; /* # seconds idle before sending echo request. */
102 int max_backoff; /* Max # seconds between connection attempts. */
104 /* Packet-in rate-limiting. */
105 int rate_limit; /* Tokens added to bucket per second. */
106 int burst_limit; /* Maximum number token bucket size. */
108 /* Discovery behavior. */
109 regex_t accept_controller_regex; /* Controller vconns to accept. */
110 const char *accept_controller_re; /* String version of regex. */
111 bool update_resolv_conf; /* Update /etc/resolv.conf? */
113 /* Spanning tree protocol. */
114 bool stp; /* Enable spanning tree protocol? */
119 struct buffer *rxbuf;
120 int n_txq; /* No. of packets queued for tx on 'rconn'. */
127 #define HALF_REMOTE 1
128 struct half halves[2];
134 bool (*packet_cb[2])(struct relay *, void *aux);
135 void (*periodic_cb)(void *aux);
136 void (*wait_cb)(void *aux);
140 static struct vlog_rate_limit vrl = VLOG_RATE_LIMIT_INIT(60, 60);
142 static void parse_options(int argc, char *argv[], struct settings *);
143 static void usage(void) NO_RETURN;
145 static struct vconn *open_passive_vconn(const char *name);
146 static struct vconn *accept_vconn(struct vconn *vconn);
148 static struct relay *relay_create(struct rconn *local, struct rconn *remote,
150 static struct relay *relay_accept(const struct settings *, struct vconn *);
151 static void relay_run(struct relay *, const struct hook[], size_t n_hooks);
152 static void relay_wait(struct relay *);
153 static void relay_destroy(struct relay *);
155 static struct hook make_hook(bool (*local_packet_cb)(struct relay *, void *),
156 bool (*remote_packet_cb)(struct relay *, void *),
157 void (*periodic_cb)(void *),
158 void (*wait_cb)(void *),
160 static struct ofp_packet_in *get_ofp_packet_in(struct relay *);
161 static bool get_ofp_packet_eth_header(struct relay *, struct ofp_packet_in **,
162 struct eth_header **);
163 static void get_ofp_packet_payload(struct ofp_packet_in *, struct buffer *);
165 struct switch_status;
167 static struct hook switch_status_hook_create(const struct settings *,
168 struct switch_status **);
169 static void switch_status_register_category(struct switch_status *,
170 const char *category,
171 void (*cb)(struct status_reply *,
174 static void status_reply_put(struct status_reply *, const char *, ...)
177 static void rconn_status_cb(struct status_reply *, void *rconn_);
179 static struct discovery *discovery_init(const struct settings *,
180 struct switch_status *);
181 static void discovery_question_connectivity(struct discovery *);
182 static bool discovery_run(struct discovery *, char **controller_name);
183 static void discovery_wait(struct discovery *);
185 static struct hook in_band_hook_create(const struct settings *,
186 struct switch_status *,
187 struct rconn *remote);
190 static struct hook port_watcher_create(struct rconn *local,
191 struct rconn *remote,
192 struct port_watcher **);
193 static uint32_t port_watcher_get_flags(const struct port_watcher *,
195 static void port_watcher_set_flags(struct port_watcher *,
196 int port_no, uint32_t flags, uint32_t mask);
198 static struct hook stp_hook_create(const struct settings *,
199 struct port_watcher *,
200 struct rconn *local, struct rconn *remote);
202 static struct hook fail_open_hook_create(const struct settings *,
203 struct switch_status *,
205 struct rconn *remote);
206 static struct hook rate_limit_hook_create(const struct settings *,
207 struct switch_status *,
209 struct rconn *remote);
212 static void modify_dhcp_request(struct dhcp_msg *, void *aux);
213 static bool validate_dhcp_offer(const struct dhcp_msg *, void *aux);
216 main(int argc, char *argv[])
220 struct list relays = LIST_INITIALIZER(&relays);
222 struct hook hooks[8];
225 struct vconn *monitor;
227 struct vconn *listeners[MAX_MGMT];
230 struct rconn *local_rconn, *remote_rconn;
231 struct relay *controller_relay;
232 struct discovery *discovery;
233 struct switch_status *switch_status;
237 set_program_name(argv[0]);
238 register_fault_handlers();
241 parse_options(argc, argv, &s);
242 signal(SIGPIPE, SIG_IGN);
244 /* Start listening for management and monitoring connections. */
246 for (i = 0; i < s.n_listeners; i++) {
247 listeners[n_listeners++] = open_passive_vconn(s.listener_names[i]);
249 monitor = s.monitor_name ? open_passive_vconn(s.monitor_name) : NULL;
251 /* Initialize switch status hook. */
252 hooks[n_hooks++] = switch_status_hook_create(&s, &switch_status);
254 /* Start controller discovery. */
255 discovery = s.discovery ? discovery_init(&s, switch_status) : NULL;
257 /* Start listening for vlogconf requests. */
258 retval = vlog_server_listen(NULL, NULL);
260 fatal(retval, "Could not listen for vlog connections");
263 die_if_already_running();
266 VLOG_WARN("OpenFlow reference implementation version %s", VERSION);
267 VLOG_WARN("OpenFlow protocol version 0x%02x", OFP_VERSION);
269 /* Connect to datapath. */
270 local_rconn = rconn_create(0, s.max_backoff);
271 rconn_connect(local_rconn, s.nl_name);
272 switch_status_register_category(switch_status, "local",
273 rconn_status_cb, local_rconn);
275 /* Connect to controller. */
276 remote_rconn = rconn_create(s.probe_interval, s.max_backoff);
277 if (s.controller_name) {
278 retval = rconn_connect(remote_rconn, s.controller_name);
279 if (retval == EAFNOSUPPORT) {
280 fatal(0, "No support for %s vconn", s.controller_name);
283 switch_status_register_category(switch_status, "remote",
284 rconn_status_cb, remote_rconn);
286 /* Start relaying. */
287 controller_relay = relay_create(local_rconn, remote_rconn, false);
288 list_push_back(&relays, &controller_relay->node);
292 struct port_watcher *pw;
293 hooks[n_hooks++] = port_watcher_create(local_rconn, remote_rconn, &pw);
294 hooks[n_hooks++] = stp_hook_create(&s, pw, local_rconn, remote_rconn);
297 hooks[n_hooks++] = in_band_hook_create(&s, switch_status,
300 if (s.fail_mode == FAIL_OPEN) {
301 hooks[n_hooks++] = fail_open_hook_create(&s, switch_status,
302 local_rconn, remote_rconn);
305 hooks[n_hooks++] = rate_limit_hook_create(&s, switch_status,
306 local_rconn, remote_rconn);
308 assert(n_hooks <= ARRAY_SIZE(hooks));
315 LIST_FOR_EACH_SAFE (r, n, struct relay, node, &relays) {
316 relay_run(r, hooks, n_hooks);
318 for (i = 0; i < n_listeners; i++) {
320 struct relay *r = relay_accept(&s, listeners[i]);
324 list_push_back(&relays, &r->node);
328 struct vconn *new = accept_vconn(monitor);
330 rconn_add_monitor(local_rconn, new);
333 for (i = 0; i < n_hooks; i++) {
334 if (hooks[i].periodic_cb) {
335 hooks[i].periodic_cb(hooks[i].aux);
339 char *controller_name;
340 if (rconn_is_connectivity_questionable(remote_rconn)) {
341 discovery_question_connectivity(discovery);
343 if (discovery_run(discovery, &controller_name)) {
344 if (controller_name) {
345 rconn_connect(remote_rconn, controller_name);
347 rconn_disconnect(remote_rconn);
352 /* Wait for something to happen. */
353 LIST_FOR_EACH (r, struct relay, node, &relays) {
356 for (i = 0; i < n_listeners; i++) {
357 vconn_accept_wait(listeners[i]);
360 vconn_accept_wait(monitor);
362 for (i = 0; i < n_hooks; i++) {
363 if (hooks[i].wait_cb) {
364 hooks[i].wait_cb(hooks[i].aux);
368 discovery_wait(discovery);
376 static struct vconn *
377 open_passive_vconn(const char *name)
382 retval = vconn_open(name, &vconn);
383 if (retval && retval != EAGAIN) {
384 fatal(retval, "opening %s", name);
386 if (!vconn_is_passive(vconn)) {
387 fatal(0, "%s is not a passive vconn", name);
392 static struct vconn *
393 accept_vconn(struct vconn *vconn)
398 retval = vconn_accept(vconn, &new);
399 if (retval && retval != EAGAIN) {
400 VLOG_WARN_RL(&vrl, "accept failed (%s)", strerror(retval));
406 make_hook(bool (*local_packet_cb)(struct relay *, void *aux),
407 bool (*remote_packet_cb)(struct relay *, void *aux),
408 void (*periodic_cb)(void *aux),
409 void (*wait_cb)(void *aux),
413 h.packet_cb[HALF_LOCAL] = local_packet_cb;
414 h.packet_cb[HALF_REMOTE] = remote_packet_cb;
415 h.periodic_cb = periodic_cb;
421 static struct ofp_packet_in *
422 get_ofp_packet_in(struct relay *r)
424 struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
425 struct ofp_header *oh = msg->data;
426 if (oh->type == OFPT_PACKET_IN) {
427 if (msg->size >= offsetof (struct ofp_packet_in, data)) {
430 VLOG_WARN("packet too short (%zu bytes) for packet_in",
438 get_ofp_packet_eth_header(struct relay *r, struct ofp_packet_in **opip,
439 struct eth_header **ethp)
441 const int min_len = offsetof(struct ofp_packet_in, data) + ETH_HEADER_LEN;
442 struct ofp_packet_in *opi = get_ofp_packet_in(r);
443 if (opi && ntohs(opi->header.length) >= min_len) {
445 *ethp = (void *) opi->data;
452 /* OpenFlow message relaying. */
454 static struct relay *
455 relay_accept(const struct settings *s, struct vconn *listen_vconn)
457 struct vconn *new_remote, *new_local;
458 char *nl_name_without_subscription;
459 struct rconn *r1, *r2;
462 new_remote = accept_vconn(listen_vconn);
467 /* nl:123 or nl:123:1 opens a netlink connection to local datapath 123. We
468 * only accept the former syntax in main().
470 * nl:123:0 opens a netlink connection to local datapath 123 without
471 * obtaining a subscription for ofp_packet_in or ofp_flow_expired
473 nl_name_without_subscription = xasprintf("%s:0", s->nl_name);
474 retval = vconn_open(nl_name_without_subscription, &new_local);
476 VLOG_ERR_RL(&vrl, "could not connect to %s (%s)",
477 nl_name_without_subscription, strerror(retval));
478 vconn_close(new_remote);
479 free(nl_name_without_subscription);
483 /* Create and return relay. */
484 r1 = rconn_create(0, 0);
485 rconn_connect_unreliably(r1, nl_name_without_subscription, new_local);
486 free(nl_name_without_subscription);
488 r2 = rconn_create(0, 0);
489 rconn_connect_unreliably(r2, "passive", new_remote);
491 return relay_create(r1, r2, true);
494 static struct relay *
495 relay_create(struct rconn *local, struct rconn *remote, bool is_mgmt_conn)
497 struct relay *r = xcalloc(1, sizeof *r);
498 r->halves[HALF_LOCAL].rconn = local;
499 r->halves[HALF_REMOTE].rconn = remote;
500 r->is_mgmt_conn = is_mgmt_conn;
505 relay_run(struct relay *r, const struct hook hooks[], size_t n_hooks)
510 for (i = 0; i < 2; i++) {
511 rconn_run(r->halves[i].rconn);
514 /* Limit the number of iterations to prevent other tasks from starving. */
515 for (iteration = 0; iteration < 50; iteration++) {
516 bool progress = false;
517 for (i = 0; i < 2; i++) {
518 struct half *this = &r->halves[i];
519 struct half *peer = &r->halves[!i];
522 this->rxbuf = rconn_recv(this->rconn);
523 if (this->rxbuf && (i == HALF_REMOTE || !r->is_mgmt_conn)) {
524 const struct hook *h;
525 for (h = hooks; h < &hooks[n_hooks]; h++) {
526 if (h->packet_cb[i] && h->packet_cb[i](r, h->aux)) {
527 buffer_delete(this->rxbuf);
536 if (this->rxbuf && !this->n_txq) {
537 int retval = rconn_send(peer->rconn, this->rxbuf,
539 if (retval != EAGAIN) {
543 buffer_delete(this->rxbuf);
554 if (r->is_mgmt_conn) {
555 for (i = 0; i < 2; i++) {
556 struct half *this = &r->halves[i];
557 if (!rconn_is_alive(this->rconn)) {
566 relay_wait(struct relay *r)
570 for (i = 0; i < 2; i++) {
571 struct half *this = &r->halves[i];
573 rconn_run_wait(this->rconn);
575 rconn_recv_wait(this->rconn);
581 relay_destroy(struct relay *r)
585 list_remove(&r->node);
586 for (i = 0; i < 2; i++) {
587 struct half *this = &r->halves[i];
588 rconn_destroy(this->rconn);
589 buffer_delete(this->rxbuf);
594 /* Port status watcher. */
596 typedef void port_watcher_cb_func(uint16_t port_no,
597 const struct ofp_phy_port *old,
598 const struct ofp_phy_port *new,
601 struct port_watcher_cb {
602 port_watcher_cb_func *function;
606 struct port_watcher {
607 struct rconn *local_rconn;
608 struct rconn *remote_rconn;
609 struct ofp_phy_port ports[OFPP_MAX + 1];
610 time_t last_feature_request;
611 bool got_feature_reply;
613 struct port_watcher_cb cbs[2];
617 /* Returns the number of fields that differ from 'a' to 'b'. */
619 opp_differs(const struct ofp_phy_port *a, const struct ofp_phy_port *b)
621 BUILD_ASSERT_DECL(sizeof *a == 36); /* Trips when we add or remove fields. */
622 return ((a->port_no != b->port_no)
623 + (memcmp(a->hw_addr, b->hw_addr, sizeof a->hw_addr) != 0)
624 + (memcmp(a->name, b->name, sizeof a->name) != 0)
625 + (a->flags != b->flags)
626 + (a->speed != b->speed)
627 + (a->features != b->features));
631 sanitize_opp(struct ofp_phy_port *opp)
635 for (i = 0; i < sizeof opp->name; i++) {
636 char c = opp->name[i];
637 if (c && (c < 0x20 || c > 0x7e)) {
641 opp->name[sizeof opp->name - 1] = '\0';
645 port_no_to_pw_idx(int port_no)
647 return (port_no < OFPP_MAX ? port_no
648 : port_no == OFPP_LOCAL ? OFPP_MAX
653 call_pw_callbacks(struct port_watcher *pw, int port_no,
654 const struct ofp_phy_port *old,
655 const struct ofp_phy_port *new)
657 if (opp_differs(old, new)) {
659 for (i = 0; i < pw->n_cbs; i++) {
660 pw->cbs[i].function(port_no, old, new, pw->cbs[i].aux);
666 update_phy_port(struct port_watcher *pw, struct ofp_phy_port *opp,
667 uint8_t reason, bool seen[OFPP_MAX + 1])
669 struct ofp_phy_port *pw_opp;
670 struct ofp_phy_port old;
674 port_no = ntohs(opp->port_no);
675 idx = port_no_to_pw_idx(port_no);
684 pw_opp = &pw->ports[idx];
686 if (reason == OFPPR_DELETE) {
687 memset(pw_opp, 0, sizeof *pw_opp);
688 pw_opp->port_no = htons(OFPP_NONE);
689 } else if (reason == OFPPR_MOD || reason == OFPPR_ADD) {
691 sanitize_opp(pw_opp);
693 call_pw_callbacks(pw, port_no, &old, pw_opp);
697 port_watcher_local_packet_cb(struct relay *r, void *pw_)
699 struct port_watcher *pw = pw_;
700 struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
701 struct ofp_header *oh = msg->data;
703 if (oh->type == OFPT_FEATURES_REPLY
704 && msg->size >= offsetof(struct ofp_switch_features, ports)) {
705 struct ofp_switch_features *osf = msg->data;
706 bool seen[ARRAY_SIZE(pw->ports)];
710 pw->got_feature_reply = true;
712 /* Update each port included in the message. */
713 memset(seen, 0, sizeof seen);
714 n_ports = ((msg->size - offsetof(struct ofp_switch_features, ports))
715 / sizeof *osf->ports);
716 for (i = 0; i < n_ports; i++) {
717 update_phy_port(pw, &osf->ports[i], OFPPR_MOD, seen);
720 /* Delete all the ports not included in the message. */
721 for (i = 0; i < ARRAY_SIZE(pw->ports); i++) {
723 update_phy_port(pw, &pw->ports[i], OFPPR_DELETE, NULL);
726 } else if (oh->type == OFPT_PORT_STATUS
727 && msg->size >= sizeof(struct ofp_port_status)) {
728 struct ofp_port_status *ops = msg->data;
729 update_phy_port(pw, &ops->desc, ops->reason, NULL);
735 port_watcher_periodic_cb(void *pw_)
737 struct port_watcher *pw = pw_;
739 if (!pw->got_feature_reply && time_now() >= pw->last_feature_request + 5) {
741 make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &b);
742 rconn_send_with_limit(pw->local_rconn, b, &pw->n_txq, 1);
743 pw->last_feature_request = time_now();
748 put_duplexes(struct ds *ds, const char *name, uint32_t features,
749 uint32_t hd_bit, uint32_t fd_bit)
751 if (features & (hd_bit | fd_bit)) {
752 ds_put_format(ds, " %s", name);
753 if (features & hd_bit) {
754 ds_put_cstr(ds, "(HD)");
756 if (features & fd_bit) {
757 ds_put_cstr(ds, "(FD)");
763 log_port_status(uint16_t port_no,
764 const struct ofp_phy_port *old,
765 const struct ofp_phy_port *new,
768 if (VLOG_IS_DBG_ENABLED()) {
769 bool was_enabled = old->port_no != htons(OFPP_NONE);
770 bool now_enabled = new->port_no != htons(OFPP_NONE);
771 uint32_t features = ntohl(new->features);
774 if (old->flags != new->flags && opp_differs(old, new) == 1) {
775 /* Don't care if only flags changed. */
780 ds_put_format(&ds, "\"%s\", "ETH_ADDR_FMT, new->name,
781 ETH_ADDR_ARGS(new->hw_addr));
782 if (ntohl(new->speed)) {
783 ds_put_format(&ds, ", speed %"PRIu32, ntohl(new->speed));
785 if (features & (OFPPF_10MB_HD | OFPPF_10MB_FD
786 | OFPPF_100MB_HD | OFPPF_100MB_FD
787 | OFPPF_1GB_HD | OFPPF_1GB_FD | OFPPF_10GB_FD)) {
788 ds_put_cstr(&ds, ", supports");
789 put_duplexes(&ds, "10M", features, OFPPF_10MB_HD, OFPPF_10MB_FD);
790 put_duplexes(&ds, "100M", features,
791 OFPPF_100MB_HD, OFPPF_100MB_FD);
792 put_duplexes(&ds, "1G", features, OFPPF_100MB_HD, OFPPF_100MB_FD);
793 if (features & OFPPF_10GB_FD) {
794 ds_put_cstr(&ds, " 10G");
797 if (was_enabled != now_enabled) {
799 VLOG_DBG("Port %d added: %s", port_no, ds_cstr(&ds));
801 VLOG_DBG("Port %d deleted", port_no);
804 VLOG_DBG("Port %d changed: %s", port_no, ds_cstr(&ds));
811 port_watcher_register_callback(struct port_watcher *pw,
812 port_watcher_cb_func *function,
815 assert(pw->n_cbs < ARRAY_SIZE(pw->cbs));
816 pw->cbs[pw->n_cbs].function = function;
817 pw->cbs[pw->n_cbs].aux = aux;
822 port_watcher_get_flags(const struct port_watcher *pw, int port_no)
824 int idx = port_no_to_pw_idx(port_no);
825 return idx >= 0 ? ntohl(pw->ports[idx].flags) : 0;
829 port_watcher_set_flags(struct port_watcher *pw,
830 int port_no, uint32_t flags, uint32_t mask)
832 struct ofp_phy_port old;
833 struct ofp_phy_port *p;
834 struct ofp_port_mod *opm;
835 struct ofp_port_status *ops;
839 idx = port_no_to_pw_idx(port_no);
845 if (!((ntohl(p->flags) ^ flags) & mask)) {
850 /* Update our idea of the flags. */
851 p->flags = ntohl(flags);
852 call_pw_callbacks(pw, port_no, &old, p);
854 /* Change the flags in the datapath. */
855 opm = make_openflow(sizeof *opm, OFPT_PORT_MOD, &b);
856 opm->mask = htonl(mask);
858 rconn_send(pw->local_rconn, b, NULL);
860 /* Notify the controller that the flags changed. */
861 ops = make_openflow(sizeof *ops, OFPT_PORT_STATUS, &b);
862 ops->reason = OFPPR_MOD;
864 rconn_send(pw->remote_rconn, b, NULL);
868 port_watcher_is_ready(const struct port_watcher *pw)
870 return pw->got_feature_reply;
874 port_watcher_create(struct rconn *local_rconn, struct rconn *remote_rconn,
875 struct port_watcher **pwp)
877 struct port_watcher *pw;
880 pw = *pwp = xcalloc(1, sizeof *pw);
881 pw->local_rconn = local_rconn;
882 pw->remote_rconn = remote_rconn;
883 pw->last_feature_request = TIME_MIN;
884 for (i = 0; i < OFPP_MAX; i++) {
885 pw->ports[i].port_no = htons(OFPP_NONE);
887 port_watcher_register_callback(pw, log_port_status, NULL);
888 return make_hook(port_watcher_local_packet_cb, NULL,
889 port_watcher_periodic_cb, NULL, pw);
892 /* Spanning tree protocol. */
894 /* Extra time, in seconds, at boot before going into fail-open, to give the
895 * spanning tree protocol time to figure out the network layout. */
896 #define STP_EXTRA_BOOT_TIME 30
900 struct port_watcher *pw;
901 struct rconn *local_rconn;
902 struct rconn *remote_rconn;
903 uint8_t dpid[ETH_ADDR_LEN];
904 long long int last_tick_256ths;
909 stp_local_packet_cb(struct relay *r, void *stp_)
911 struct stp_data *stp = stp_;
912 struct ofp_packet_in *opi;
913 struct eth_header *eth;
914 struct llc_header *llc;
915 struct buffer payload;
919 if (!get_ofp_packet_eth_header(r, &opi, ð)
920 || !eth_addr_equals(eth->eth_dst, stp_eth_addr)) {
924 port_no = ntohs(opi->in_port);
925 if (port_no >= STP_MAX_PORTS) {
926 /* STP only supports 255 ports. */
929 if (port_watcher_get_flags(stp->pw, port_no) & OFPPFL_NO_STP) {
930 /* We're not doing STP on this port. */
934 if (opi->reason == OFPR_ACTION) {
935 /* The controller set up a flow for this, so we won't intercept it. */
939 get_ofp_packet_payload(opi, &payload);
940 flow_extract(&payload, port_no, &flow);
941 if (flow.dl_type != htons(OFP_DL_TYPE_NOT_ETH_TYPE)) {
942 VLOG_DBG("non-LLC frame received on STP multicast address");
945 llc = buffer_at_assert(&payload, sizeof *eth, sizeof *llc);
946 if (llc->llc_dsap != STP_LLC_DSAP) {
947 VLOG_DBG("bad DSAP 0x%02"PRIx8" received on STP multicast address",
952 /* Trim off padding on payload. */
953 if (payload.size > ntohs(eth->eth_type) + ETH_HEADER_LEN) {
954 payload.size = ntohs(eth->eth_type) + ETH_HEADER_LEN;
956 if (buffer_try_pull(&payload, ETH_HEADER_LEN + LLC_HEADER_LEN)) {
957 struct stp_port *p = stp_get_port(stp->stp, port_no);
958 stp_received_bpdu(p, payload.data, payload.size);
967 return time_msec() * 256 / 1000;
971 stp_periodic_cb(void *stp_)
973 struct stp_data *stp = stp_;
974 long long int now_256ths = time_256ths();
975 long long int elapsed_256ths = now_256ths - stp->last_tick_256ths;
978 if (!port_watcher_is_ready(stp->pw)) {
979 /* Can't start STP until we know port flags, because port flags can
983 if (elapsed_256ths <= 0) {
987 stp_tick(stp->stp, MIN(INT_MAX, elapsed_256ths));
988 stp->last_tick_256ths = now_256ths;
990 while (stp_get_changed_port(stp->stp, &p)) {
991 int port_no = stp_port_no(p);
992 enum stp_state state = stp_port_get_state(p);
994 if (state != STP_DISABLED) {
995 VLOG_WARN("STP: Port %d entered %s state",
996 port_no, stp_state_name(state));
998 if (!(port_watcher_get_flags(stp->pw, port_no) & OFPPFL_NO_STP)) {
1002 flags = OFPPFL_STP_LISTEN;
1005 flags = OFPPFL_STP_LEARN;
1008 case STP_FORWARDING:
1009 flags = OFPPFL_STP_FORWARD;
1012 flags = OFPPFL_STP_BLOCK;
1015 VLOG_DBG_RL(&vrl, "STP: Port %d has bad state %x",
1017 flags = OFPPFL_STP_FORWARD;
1020 if (!stp_forward_in_state(state)) {
1021 flags |= OFPPFL_NO_FLOOD;
1023 port_watcher_set_flags(stp->pw, port_no, flags,
1024 OFPPFL_STP_MASK | OFPPFL_NO_FLOOD);
1026 /* We don't own those flags. */
1032 stp_wait_cb(void *stp_ UNUSED)
1034 poll_timer_wait(1000);
1038 send_bpdu(const void *bpdu, size_t bpdu_size, int port_no, void *stp_)
1040 struct stp_data *stp = stp_;
1041 struct eth_header *eth;
1042 struct llc_header *llc;
1043 struct buffer pkt, *opo;
1045 /* Packet skeleton. */
1046 buffer_init(&pkt, ETH_HEADER_LEN + LLC_HEADER_LEN + bpdu_size);
1047 eth = buffer_put_uninit(&pkt, sizeof *eth);
1048 llc = buffer_put_uninit(&pkt, sizeof *llc);
1049 buffer_put(&pkt, bpdu, bpdu_size);
1052 memcpy(eth->eth_dst, stp_eth_addr, ETH_ADDR_LEN);
1053 memcpy(eth->eth_src, stp->pw->ports[port_no].hw_addr, ETH_ADDR_LEN);
1054 eth->eth_type = htons(pkt.size - ETH_HEADER_LEN);
1057 llc->llc_dsap = STP_LLC_DSAP;
1058 llc->llc_ssap = STP_LLC_SSAP;
1059 llc->llc_cntl = STP_LLC_CNTL;
1061 opo = make_unbuffered_packet_out(&pkt, OFPP_NONE, port_no);
1062 buffer_uninit(&pkt);
1063 rconn_send_with_limit(stp->local_rconn, opo, &stp->n_txq, OFPP_MAX);
1067 stp_port_watcher_cb(uint16_t port_no,
1068 const struct ofp_phy_port *old,
1069 const struct ofp_phy_port *new,
1072 struct stp_data *stp = stp_;
1075 /* STP only supports a maximum of 255 ports, one less than OpenFlow. We
1076 * don't support STP on OFPP_LOCAL, either. */
1077 if (port_no >= STP_MAX_PORTS) {
1081 p = stp_get_port(stp->stp, port_no);
1082 if (new->port_no == htons(OFPP_NONE)
1083 || new->flags & htonl(OFPPFL_NO_STP)) {
1084 stp_port_disable(p);
1087 stp_port_set_speed(p, new->speed);
1092 stp_hook_create(const struct settings *s, struct port_watcher *pw,
1093 struct rconn *local, struct rconn *remote)
1095 uint8_t dpid[ETH_ADDR_LEN];
1096 struct netdev *netdev;
1097 struct stp_data *stp;
1100 retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
1102 fatal(retval, "Could not open %s device", s->of_name);
1104 memcpy(dpid, netdev_get_etheraddr(netdev), ETH_ADDR_LEN);
1105 netdev_close(netdev);
1107 stp = xcalloc(1, sizeof *stp);
1108 stp->stp = stp_create("stp", eth_addr_to_uint64(dpid), send_bpdu, stp);
1110 memcpy(stp->dpid, dpid, ETH_ADDR_LEN);
1111 stp->local_rconn = local;
1112 stp->remote_rconn = remote;
1113 stp->last_tick_256ths = time_256ths();
1115 port_watcher_register_callback(pw, stp_port_watcher_cb, stp);
1116 return make_hook(stp_local_packet_cb, NULL,
1117 stp_periodic_cb, stp_wait_cb, stp);
1120 /* In-band control. */
1122 struct in_band_data {
1123 const struct settings *s;
1124 struct mac_learning *ml;
1125 struct netdev *of_device;
1126 struct rconn *controller;
1127 uint8_t mac[ETH_ADDR_LEN];
1132 queue_tx(struct rconn *rc, struct in_band_data *in_band, struct buffer *b)
1134 rconn_send_with_limit(rc, b, &in_band->n_queued, 10);
1137 static const uint8_t *
1138 get_controller_mac(struct in_band_data *in_band)
1140 static uint32_t ip, last_nonzero_ip;
1141 static uint8_t mac[ETH_ADDR_LEN], last_nonzero_mac[ETH_ADDR_LEN];
1142 static time_t next_refresh = 0;
1144 uint32_t last_ip = ip;
1146 time_t now = time_now();
1148 ip = rconn_get_ip(in_band->controller);
1149 if (last_ip != ip || !next_refresh || now >= next_refresh) {
1152 /* Look up MAC address. */
1153 memset(mac, 0, sizeof mac);
1155 int retval = netdev_arp_lookup(in_band->of_device, ip, mac);
1157 VLOG_DBG("cannot look up controller hw address ("IP_FMT"): %s",
1158 IP_ARGS(&ip), strerror(retval));
1161 have_mac = !eth_addr_is_zero(mac);
1163 /* Log changes in IP, MAC addresses. */
1164 if (ip && ip != last_nonzero_ip) {
1165 VLOG_DBG("controller IP address changed from "IP_FMT
1166 " to "IP_FMT, IP_ARGS(&last_nonzero_ip), IP_ARGS(&ip));
1167 last_nonzero_ip = ip;
1169 if (have_mac && memcmp(last_nonzero_mac, mac, ETH_ADDR_LEN)) {
1170 VLOG_DBG("controller MAC address changed from "ETH_ADDR_FMT" to "
1172 ETH_ADDR_ARGS(last_nonzero_mac), ETH_ADDR_ARGS(mac));
1173 memcpy(last_nonzero_mac, mac, ETH_ADDR_LEN);
1176 /* Schedule next refresh.
1178 * If we have an IP address but not a MAC address, then refresh
1179 * quickly, since we probably will get a MAC address soon (via ARP).
1180 * Otherwise, we can afford to wait a little while. */
1181 next_refresh = now + (!ip || have_mac ? 10 : 1);
1183 return !eth_addr_is_zero(mac) ? mac : NULL;
1187 is_controller_mac(const uint8_t dl_addr[ETH_ADDR_LEN],
1188 struct in_band_data *in_band)
1190 const uint8_t *mac = get_controller_mac(in_band);
1191 return mac && eth_addr_equals(mac, dl_addr);
1195 in_band_learn_mac(struct in_band_data *in_band,
1196 uint16_t in_port, const uint8_t src_mac[ETH_ADDR_LEN])
1198 if (mac_learning_learn(in_band->ml, src_mac, in_port)) {
1199 VLOG_DBG_RL(&vrl, "learned that "ETH_ADDR_FMT" is on port %"PRIu16,
1200 ETH_ADDR_ARGS(src_mac), in_port);
1205 in_band_local_packet_cb(struct relay *r, void *in_band_)
1207 struct in_band_data *in_band = in_band_;
1208 struct rconn *rc = r->halves[HALF_LOCAL].rconn;
1209 struct ofp_packet_in *opi;
1210 struct eth_header *eth;
1211 struct buffer payload;
1216 if (!get_ofp_packet_eth_header(r, &opi, ð)) {
1219 in_port = ntohs(opi->in_port);
1221 /* Deal with local stuff. */
1222 if (in_port == OFPP_LOCAL) {
1223 /* Sent by secure channel. */
1224 out_port = mac_learning_lookup(in_band->ml, eth->eth_dst);
1225 } else if (eth_addr_equals(eth->eth_dst, in_band->mac)) {
1226 /* Sent to secure channel. */
1227 out_port = OFPP_LOCAL;
1228 in_band_learn_mac(in_band, in_port, eth->eth_src);
1229 } else if (eth->eth_type == htons(ETH_TYPE_ARP)
1230 && eth_addr_is_broadcast(eth->eth_dst)
1231 && is_controller_mac(eth->eth_src, in_band)) {
1232 /* ARP sent by controller. */
1233 out_port = OFPP_FLOOD;
1234 } else if (is_controller_mac(eth->eth_dst, in_band)
1235 || is_controller_mac(eth->eth_src, in_band)) {
1236 /* Traffic to or from controller. Switch it by hand. */
1237 in_band_learn_mac(in_band, in_port, eth->eth_src);
1238 out_port = mac_learning_lookup(in_band->ml, eth->eth_dst);
1240 const uint8_t *controller_mac;
1241 controller_mac = get_controller_mac(in_band);
1242 if (eth->eth_type == htons(ETH_TYPE_ARP)
1243 && eth_addr_is_broadcast(eth->eth_dst)
1244 && is_controller_mac(eth->eth_src, in_band)) {
1245 /* ARP sent by controller. */
1246 out_port = OFPP_FLOOD;
1247 } else if (is_controller_mac(eth->eth_dst, in_band)
1248 && in_port == mac_learning_lookup(in_band->ml,
1250 /* Drop controller traffic that arrives on the controller port. */
1257 get_ofp_packet_payload(opi, &payload);
1258 flow_extract(&payload, in_port, &flow);
1259 if (in_port == out_port) {
1260 /* The input and output port match. Set up a flow to drop packets. */
1261 queue_tx(rc, in_band, make_add_flow(&flow, ntohl(opi->buffer_id),
1262 in_band->s->max_idle, 0));
1263 } else if (out_port != OFPP_FLOOD) {
1264 /* The output port is known, so add a new flow. */
1265 queue_tx(rc, in_band,
1266 make_add_simple_flow(&flow, ntohl(opi->buffer_id),
1267 out_port, in_band->s->max_idle));
1269 /* If the switch didn't buffer the packet, we need to send a copy. */
1270 if (ntohl(opi->buffer_id) == UINT32_MAX) {
1271 queue_tx(rc, in_band,
1272 make_unbuffered_packet_out(&payload, in_port, out_port));
1275 /* We don't know that MAC. Send along the packet without setting up a
1278 if (ntohl(opi->buffer_id) == UINT32_MAX) {
1279 b = make_unbuffered_packet_out(&payload, in_port, out_port);
1281 b = make_buffered_packet_out(ntohl(opi->buffer_id),
1284 queue_tx(rc, in_band, b);
1290 in_band_status_cb(struct status_reply *sr, void *in_band_)
1292 struct in_band_data *in_band = in_band_;
1293 struct in_addr local_ip;
1294 uint32_t controller_ip;
1295 const uint8_t *controller_mac;
1297 if (netdev_get_in4(in_band->of_device, &local_ip)) {
1298 status_reply_put(sr, "local-ip="IP_FMT, IP_ARGS(&local_ip.s_addr));
1300 status_reply_put(sr, "local-mac="ETH_ADDR_FMT,
1301 ETH_ADDR_ARGS(in_band->mac));
1303 controller_ip = rconn_get_ip(in_band->controller);
1304 if (controller_ip) {
1305 status_reply_put(sr, "controller-ip="IP_FMT,
1306 IP_ARGS(&controller_ip));
1308 controller_mac = get_controller_mac(in_band);
1309 if (controller_mac) {
1310 status_reply_put(sr, "controller-mac="ETH_ADDR_FMT,
1311 ETH_ADDR_ARGS(controller_mac));
1316 get_ofp_packet_payload(struct ofp_packet_in *opi, struct buffer *payload)
1318 payload->data = opi->data;
1319 payload->size = ntohs(opi->header.length) - offsetof(struct ofp_packet_in,
1324 in_band_hook_create(const struct settings *s, struct switch_status *ss,
1325 struct rconn *remote)
1327 struct in_band_data *in_band;
1330 in_band = xcalloc(1, sizeof *in_band);
1332 in_band->ml = mac_learning_create();
1333 retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE,
1334 &in_band->of_device);
1336 fatal(retval, "Could not open %s device", s->of_name);
1338 memcpy(in_band->mac, netdev_get_etheraddr(in_band->of_device),
1340 in_band->controller = remote;
1341 switch_status_register_category(ss, "in-band", in_band_status_cb, in_band);
1342 return make_hook(in_band_local_packet_cb, NULL, NULL, NULL, in_band);
1345 /* Fail open support. */
1347 struct fail_open_data {
1348 const struct settings *s;
1349 struct rconn *local_rconn;
1350 struct rconn *remote_rconn;
1351 struct lswitch *lswitch;
1352 int last_disconn_secs;
1353 time_t boot_deadline;
1356 /* Causes 'r' to enter or leave fail-open mode, if appropriate. */
1358 fail_open_periodic_cb(void *fail_open_)
1360 struct fail_open_data *fail_open = fail_open_;
1364 if (time_now() < fail_open->boot_deadline) {
1367 disconn_secs = rconn_disconnected_duration(fail_open->remote_rconn);
1368 open = disconn_secs >= fail_open->s->probe_interval * 3;
1369 if (open != (fail_open->lswitch != NULL)) {
1371 VLOG_WARN("No longer in fail-open mode");
1372 lswitch_destroy(fail_open->lswitch);
1373 fail_open->lswitch = NULL;
1375 VLOG_WARN("Could not connect to controller for %d seconds, "
1376 "failing open", disconn_secs);
1377 fail_open->lswitch = lswitch_create(fail_open->local_rconn, true,
1378 fail_open->s->max_idle);
1379 fail_open->last_disconn_secs = disconn_secs;
1381 } else if (open && disconn_secs > fail_open->last_disconn_secs + 60) {
1382 VLOG_WARN("Still in fail-open mode after %d seconds disconnected "
1383 "from controller", disconn_secs);
1384 fail_open->last_disconn_secs = disconn_secs;
1389 fail_open_local_packet_cb(struct relay *r, void *fail_open_)
1391 struct fail_open_data *fail_open = fail_open_;
1392 if (!fail_open->lswitch) {
1395 lswitch_process_packet(fail_open->lswitch, fail_open->local_rconn,
1396 r->halves[HALF_LOCAL].rxbuf);
1397 rconn_run(fail_open->local_rconn);
1403 fail_open_status_cb(struct status_reply *sr, void *fail_open_)
1405 struct fail_open_data *fail_open = fail_open_;
1406 const struct settings *s = fail_open->s;
1407 int trigger_duration = s->probe_interval * 3;
1408 int cur_duration = rconn_disconnected_duration(fail_open->remote_rconn);
1410 status_reply_put(sr, "trigger-duration=%d", trigger_duration);
1411 status_reply_put(sr, "current-duration=%d", cur_duration);
1412 status_reply_put(sr, "triggered=%s",
1413 cur_duration >= trigger_duration ? "true" : "false");
1414 status_reply_put(sr, "max-idle=%d", s->max_idle);
1418 fail_open_hook_create(const struct settings *s, struct switch_status *ss,
1419 struct rconn *local_rconn, struct rconn *remote_rconn)
1421 struct fail_open_data *fail_open = xmalloc(sizeof *fail_open);
1423 fail_open->local_rconn = local_rconn;
1424 fail_open->remote_rconn = remote_rconn;
1425 fail_open->lswitch = NULL;
1426 fail_open->boot_deadline = time_now() + s->probe_interval * 3;
1428 fail_open->boot_deadline += STP_EXTRA_BOOT_TIME;
1430 switch_status_register_category(ss, "fail-open",
1431 fail_open_status_cb, fail_open);
1432 return make_hook(fail_open_local_packet_cb, NULL,
1433 fail_open_periodic_cb, NULL, fail_open);
1436 struct rate_limiter {
1437 const struct settings *s;
1438 struct rconn *remote_rconn;
1440 /* One queue per physical port. */
1441 struct queue queues[OFPP_MAX];
1442 int n_queued; /* Sum over queues[*].n. */
1443 int next_tx_port; /* Next port to check in round-robin. */
1447 * It costs 1000 tokens to send a single packet_in message. A single token
1448 * per message would be more straightforward, but this choice lets us avoid
1449 * round-off error in refill_bucket()'s calculation of how many tokens to
1450 * add to the bucket, since no division step is needed. */
1451 long long int last_fill; /* Time at which we last added tokens. */
1452 int tokens; /* Current number of tokens. */
1454 /* Transmission queue. */
1455 int n_txq; /* No. of packets waiting in rconn for tx. */
1457 /* Statistics reporting. */
1458 unsigned long long n_normal; /* # txed w/o rate limit queuing. */
1459 unsigned long long n_limited; /* # queued for rate limiting. */
1460 unsigned long long n_queue_dropped; /* # dropped due to queue overflow. */
1461 unsigned long long n_tx_dropped; /* # dropped due to tx overflow. */
1464 /* Drop a packet from the longest queue in 'rl'. */
1466 drop_packet(struct rate_limiter *rl)
1468 struct queue *longest; /* Queue currently selected as longest. */
1469 int n_longest; /* # of queues of same length as 'longest'. */
1472 longest = &rl->queues[0];
1474 for (q = &rl->queues[0]; q < &rl->queues[OFPP_MAX]; q++) {
1475 if (longest->n < q->n) {
1478 } else if (longest->n == q->n) {
1481 /* Randomly select one of the longest queues, with a uniform
1482 * distribution (Knuth algorithm 3.4.2R). */
1483 if (!random_range(n_longest)) {
1489 /* FIXME: do we want to pop the tail instead? */
1490 buffer_delete(queue_pop_head(longest));
1494 /* Remove and return the next packet to transmit (in round-robin order). */
1495 static struct buffer *
1496 dequeue_packet(struct rate_limiter *rl)
1500 for (i = 0; i < OFPP_MAX; i++) {
1501 unsigned int port = (rl->next_tx_port + i) % OFPP_MAX;
1502 struct queue *q = &rl->queues[port];
1504 rl->next_tx_port = (port + 1) % OFPP_MAX;
1506 return queue_pop_head(q);
1512 /* Add tokens to the bucket based on elapsed time. */
1514 refill_bucket(struct rate_limiter *rl)
1516 const struct settings *s = rl->s;
1517 long long int now = time_msec();
1518 long long int tokens = (now - rl->last_fill) * s->rate_limit + rl->tokens;
1519 if (tokens >= 1000) {
1520 rl->last_fill = now;
1521 rl->tokens = MIN(tokens, s->burst_limit * 1000);
1525 /* Attempts to remove enough tokens from 'rl' to transmit a packet. Returns
1526 * true if successful, false otherwise. (In the latter case no tokens are
1529 get_token(struct rate_limiter *rl)
1531 if (rl->tokens >= 1000) {
1540 rate_limit_local_packet_cb(struct relay *r, void *rl_)
1542 struct rate_limiter *rl = rl_;
1543 const struct settings *s = rl->s;
1544 struct ofp_packet_in *opi;
1546 opi = get_ofp_packet_in(r);
1551 if (!rl->n_queued && get_token(rl)) {
1552 /* In the common case where we are not constrained by the rate limit,
1553 * let the packet take the normal path. */
1557 /* Otherwise queue it up for the periodic callback to drain out. */
1558 struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
1559 int port = ntohs(opi->in_port) % OFPP_MAX;
1560 if (rl->n_queued >= s->burst_limit) {
1563 queue_push_tail(&rl->queues[port], buffer_clone(msg));
1571 rate_limit_status_cb(struct status_reply *sr, void *rl_)
1573 struct rate_limiter *rl = rl_;
1575 status_reply_put(sr, "normal=%llu", rl->n_normal);
1576 status_reply_put(sr, "limited=%llu", rl->n_limited);
1577 status_reply_put(sr, "queue-dropped=%llu", rl->n_queue_dropped);
1578 status_reply_put(sr, "tx-dropped=%llu", rl->n_tx_dropped);
1582 rate_limit_periodic_cb(void *rl_)
1584 struct rate_limiter *rl = rl_;
1587 /* Drain some packets out of the bucket if possible, but limit the number
1588 * of iterations to allow other code to get work done too. */
1590 for (i = 0; rl->n_queued && get_token(rl) && i < 50; i++) {
1591 /* Use a small, arbitrary limit for the amount of queuing to do here,
1592 * because the TCP connection is responsible for buffering and there is
1593 * no point in trying to transmit faster than the TCP connection can
1595 struct buffer *b = dequeue_packet(rl);
1596 if (rconn_send_with_limit(rl->remote_rconn, b, &rl->n_txq, 10)) {
1603 rate_limit_wait_cb(void *rl_)
1605 struct rate_limiter *rl = rl_;
1607 if (rl->tokens >= 1000) {
1608 /* We can transmit more packets as soon as we're called again. */
1609 poll_immediate_wake();
1611 /* We have to wait for the bucket to re-fill. We could calculate
1612 * the exact amount of time here for increased smoothness. */
1613 poll_timer_wait(TIME_UPDATE_INTERVAL / 2);
1619 rate_limit_hook_create(const struct settings *s, struct switch_status *ss,
1620 struct rconn *local, struct rconn *remote)
1622 struct rate_limiter *rl;
1625 rl = xcalloc(1, sizeof *rl);
1627 rl->remote_rconn = remote;
1628 for (i = 0; i < ARRAY_SIZE(rl->queues); i++) {
1629 queue_init(&rl->queues[i]);
1631 rl->last_fill = time_msec();
1632 rl->tokens = s->rate_limit * 100;
1633 switch_status_register_category(ss, "rate-limit",
1634 rate_limit_status_cb, rl);
1635 return make_hook(rate_limit_local_packet_cb, NULL, rate_limit_periodic_cb,
1636 rate_limit_wait_cb, rl);
1639 /* OFPST_SWITCH statistics. */
1641 struct switch_status_category {
1643 void (*cb)(struct status_reply *, void *aux);
1647 struct switch_status {
1648 const struct settings *s;
1650 struct switch_status_category categories[8];
1654 struct status_reply {
1655 struct switch_status_category *category;
1661 switch_status_remote_packet_cb(struct relay *r, void *ss_)
1663 struct switch_status *ss = ss_;
1664 struct rconn *rc = r->halves[HALF_REMOTE].rconn;
1665 struct buffer *msg = r->halves[HALF_REMOTE].rxbuf;
1666 struct switch_status_category *c;
1667 struct ofp_stats_request *osr;
1668 struct ofp_stats_reply *reply;
1669 struct status_reply sr;
1670 struct ofp_header *oh;
1675 if (oh->type != OFPT_STATS_REQUEST) {
1678 if (msg->size < sizeof(struct ofp_stats_request)) {
1679 VLOG_WARN_RL(&vrl, "packet too short (%zu bytes) for stats_request",
1685 if (osr->type != htons(OFPST_SWITCH)) {
1689 sr.request.string = (void *) (osr + 1);
1690 sr.request.length = msg->size - sizeof *osr;
1691 ds_init(&sr.output);
1692 for (c = ss->categories; c < &ss->categories[ss->n_categories]; c++) {
1693 if (!memcmp(c->name, sr.request.string,
1694 MIN(strlen(c->name), sr.request.length))) {
1699 reply = make_openflow_xid((offsetof(struct ofp_stats_reply, body)
1700 + sr.output.length),
1701 OFPT_STATS_REPLY, osr->header.xid, &b);
1702 reply->type = htons(OFPST_SWITCH);
1704 memcpy(reply->body, sr.output.string, sr.output.length);
1705 retval = rconn_send(rc, b, NULL);
1706 if (retval && retval != EAGAIN) {
1707 VLOG_WARN("send failed (%s)", strerror(retval));
1709 ds_destroy(&sr.output);
1714 rconn_status_cb(struct status_reply *sr, void *rconn_)
1716 struct rconn *rconn = rconn_;
1717 time_t now = time_now();
1719 status_reply_put(sr, "name=%s", rconn_get_name(rconn));
1720 status_reply_put(sr, "state=%s", rconn_get_state(rconn));
1721 status_reply_put(sr, "backoff=%d", rconn_get_backoff(rconn));
1722 status_reply_put(sr, "is-connected=%s",
1723 rconn_is_connected(rconn) ? "true" : "false");
1724 status_reply_put(sr, "sent-msgs=%u", rconn_packets_sent(rconn));
1725 status_reply_put(sr, "received-msgs=%u", rconn_packets_received(rconn));
1726 status_reply_put(sr, "attempted-connections=%u",
1727 rconn_get_attempted_connections(rconn));
1728 status_reply_put(sr, "successful-connections=%u",
1729 rconn_get_successful_connections(rconn));
1730 status_reply_put(sr, "last-connection=%ld",
1731 (long int) (now - rconn_get_last_connection(rconn)));
1732 status_reply_put(sr, "time-connected=%lu",
1733 rconn_get_total_time_connected(rconn));
1734 status_reply_put(sr, "state-elapsed=%u", rconn_get_state_elapsed(rconn));
1738 config_status_cb(struct status_reply *sr, void *s_)
1740 const struct settings *s = s_;
1743 for (i = 0; i < s->n_listeners; i++) {
1744 status_reply_put(sr, "management%zu=%s", i, s->listener_names[i]);
1746 if (s->probe_interval) {
1747 status_reply_put(sr, "probe-interval=%d", s->probe_interval);
1749 if (s->max_backoff) {
1750 status_reply_put(sr, "max-backoff=%d", s->max_backoff);
1755 switch_status_cb(struct status_reply *sr, void *ss_)
1757 struct switch_status *ss = ss_;
1758 time_t now = time_now();
1760 status_reply_put(sr, "now=%ld", (long int) now);
1761 status_reply_put(sr, "uptime=%ld", (long int) (now - ss->booted));
1762 status_reply_put(sr, "pid=%ld", (long int) getpid());
1766 switch_status_hook_create(const struct settings *s, struct switch_status **ssp)
1768 struct switch_status *ss = xcalloc(1, sizeof *ss);
1770 ss->booted = time_now();
1771 switch_status_register_category(ss, "config",
1772 config_status_cb, (void *) s);
1773 switch_status_register_category(ss, "switch", switch_status_cb, ss);
1775 return make_hook(NULL, switch_status_remote_packet_cb, NULL, NULL, ss);
1779 switch_status_register_category(struct switch_status *ss,
1780 const char *category,
1781 void (*cb)(struct status_reply *,
1785 struct switch_status_category *c;
1786 assert(ss->n_categories < ARRAY_SIZE(ss->categories));
1787 c = &ss->categories[ss->n_categories++];
1790 c->name = xstrdup(category);
1794 status_reply_put(struct status_reply *sr, const char *content, ...)
1796 size_t old_length = sr->output.length;
1800 /* Append the status reply to the output. */
1801 ds_put_format(&sr->output, "%s.", sr->category->name);
1802 va_start(args, content);
1803 ds_put_format_valist(&sr->output, content, args);
1805 if (ds_last(&sr->output) != '\n') {
1806 ds_put_char(&sr->output, '\n');
1809 /* Drop what we just added if it doesn't match the request. */
1810 added = sr->output.length - old_length;
1811 if (added < sr->request.length
1812 || memcmp(&sr->output.string[old_length],
1813 sr->request.string, sr->request.length)) {
1814 ds_truncate(&sr->output, old_length);
1819 /* Controller discovery. */
1823 const struct settings *s;
1824 struct dhclient *dhcp;
1829 discovery_status_cb(struct status_reply *sr, void *d_)
1831 struct discovery *d = d_;
1833 status_reply_put(sr, "accept-remote=%s", d->s->accept_controller_re);
1834 status_reply_put(sr, "n-changes=%d", d->n_changes);
1835 status_reply_put(sr, "state=%s", dhclient_get_state(d->dhcp));
1836 status_reply_put(sr, "state-elapsed=%u",
1837 dhclient_get_state_elapsed(d->dhcp));
1838 if (dhclient_is_bound(d->dhcp)) {
1839 uint32_t ip = dhclient_get_ip(d->dhcp);
1840 uint32_t netmask = dhclient_get_netmask(d->dhcp);
1841 uint32_t router = dhclient_get_router(d->dhcp);
1843 const struct dhcp_msg *cfg = dhclient_get_config(d->dhcp);
1844 uint32_t dns_server;
1848 status_reply_put(sr, "ip="IP_FMT, IP_ARGS(&ip));
1849 status_reply_put(sr, "netmask="IP_FMT, IP_ARGS(&netmask));
1851 status_reply_put(sr, "router="IP_FMT, IP_ARGS(&router));
1854 for (i = 0; dhcp_msg_get_ip(cfg, DHCP_CODE_DNS_SERVER, i, &dns_server);
1856 status_reply_put(sr, "dns%d="IP_FMT, i, IP_ARGS(&dns_server));
1859 domain_name = dhcp_msg_get_string(cfg, DHCP_CODE_DOMAIN_NAME);
1861 status_reply_put(sr, "domain=%s", domain_name);
1865 status_reply_put(sr, "lease-remaining=%u",
1866 dhclient_get_lease_remaining(d->dhcp));
1870 static struct discovery *
1871 discovery_init(const struct settings *s, struct switch_status *ss)
1873 struct netdev *netdev;
1874 struct discovery *d;
1875 struct dhclient *dhcp;
1878 /* Bring ofX network device up. */
1879 retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
1881 fatal(retval, "Could not open %s device", s->of_name);
1883 retval = netdev_turn_flags_on(netdev, NETDEV_UP, true);
1885 fatal(retval, "Could not bring %s device up", s->of_name);
1887 netdev_close(netdev);
1889 /* Initialize DHCP client. */
1890 retval = dhclient_create(s->of_name, modify_dhcp_request,
1891 validate_dhcp_offer, (void *) s, &dhcp);
1893 fatal(retval, "Failed to initialize DHCP client");
1895 dhclient_init(dhcp, 0);
1897 d = xmalloc(sizeof *d);
1902 switch_status_register_category(ss, "discovery", discovery_status_cb, d);
1908 discovery_question_connectivity(struct discovery *d)
1910 dhclient_force_renew(d->dhcp, 15);
1914 discovery_run(struct discovery *d, char **controller_name)
1916 dhclient_run(d->dhcp);
1917 if (!dhclient_changed(d->dhcp)) {
1921 dhclient_configure_netdev(d->dhcp);
1922 if (d->s->update_resolv_conf) {
1923 dhclient_update_resolv_conf(d->dhcp);
1926 if (dhclient_is_bound(d->dhcp)) {
1927 *controller_name = dhcp_msg_get_string(dhclient_get_config(d->dhcp),
1928 DHCP_CODE_OFP_CONTROLLER_VCONN);
1929 VLOG_WARN("%s: discovered controller", *controller_name);
1932 *controller_name = NULL;
1934 VLOG_WARN("discovered controller no longer available");
1942 discovery_wait(struct discovery *d)
1944 dhclient_wait(d->dhcp);
1948 modify_dhcp_request(struct dhcp_msg *msg, void *aux)
1950 dhcp_msg_put_string(msg, DHCP_CODE_VENDOR_CLASS, "OpenFlow");
1954 validate_dhcp_offer(const struct dhcp_msg *msg, void *s_)
1956 const struct settings *s = s_;
1960 vconn_name = dhcp_msg_get_string(msg, DHCP_CODE_OFP_CONTROLLER_VCONN);
1962 VLOG_WARN_RL(&vrl, "rejecting DHCP offer missing controller vconn");
1965 accept = !regexec(&s->accept_controller_regex, vconn_name, 0, NULL, 0);
1967 VLOG_WARN_RL(&vrl, "rejecting controller vconn that fails to match %s",
1968 s->accept_controller_re);
1974 /* User interface. */
1977 parse_options(int argc, char *argv[], struct settings *s)
1980 OPT_ACCEPT_VCONN = UCHAR_MAX + 1,
1982 OPT_INACTIVITY_PROBE,
1988 static struct option long_options[] = {
1989 {"accept-vconn", required_argument, 0, OPT_ACCEPT_VCONN},
1990 {"no-resolv-conf", no_argument, 0, OPT_NO_RESOLV_CONF},
1991 {"fail", required_argument, 0, 'F'},
1992 {"inactivity-probe", required_argument, 0, OPT_INACTIVITY_PROBE},
1993 {"max-idle", required_argument, 0, OPT_MAX_IDLE},
1994 {"max-backoff", required_argument, 0, OPT_MAX_BACKOFF},
1995 {"listen", required_argument, 0, 'l'},
1996 {"monitor", required_argument, 0, 'm'},
1997 {"rate-limit", optional_argument, 0, OPT_RATE_LIMIT},
1998 {"burst-limit", required_argument, 0, OPT_BURST_LIMIT},
1999 {"detach", no_argument, 0, 'D'},
2000 {"force", no_argument, 0, 'f'},
2001 {"pidfile", optional_argument, 0, 'P'},
2002 {"verbose", optional_argument, 0, 'v'},
2003 {"help", no_argument, 0, 'h'},
2004 {"version", no_argument, 0, 'V'},
2005 VCONN_SSL_LONG_OPTIONS
2008 char *short_options = long_options_to_short_options(long_options);
2009 char *accept_re = NULL;
2012 /* Set defaults that we can figure out before parsing options. */
2014 s->monitor_name = NULL;
2015 s->fail_mode = FAIL_OPEN;
2017 s->probe_interval = 15;
2018 s->max_backoff = 15;
2019 s->update_resolv_conf = true;
2025 c = getopt_long(argc, argv, short_options, long_options, NULL);
2031 case OPT_ACCEPT_VCONN:
2032 accept_re = optarg[0] == '^' ? optarg : xasprintf("^%s", optarg);
2035 case OPT_NO_RESOLV_CONF:
2036 s->update_resolv_conf = false;
2040 if (!strcmp(optarg, "open")) {
2041 s->fail_mode = FAIL_OPEN;
2042 } else if (!strcmp(optarg, "closed")) {
2043 s->fail_mode = FAIL_CLOSED;
2046 "-f or --fail argument must be \"open\" or \"closed\"");
2050 case OPT_INACTIVITY_PROBE:
2051 s->probe_interval = atoi(optarg);
2052 if (s->probe_interval < 5) {
2053 fatal(0, "--inactivity-probe argument must be at least 5");
2058 if (!strcmp(optarg, "permanent")) {
2059 s->max_idle = OFP_FLOW_PERMANENT;
2061 s->max_idle = atoi(optarg);
2062 if (s->max_idle < 1 || s->max_idle > 65535) {
2063 fatal(0, "--max-idle argument must be between 1 and "
2064 "65535 or the word 'permanent'");
2069 case OPT_MAX_BACKOFF:
2070 s->max_backoff = atoi(optarg);
2071 if (s->max_backoff < 1) {
2072 fatal(0, "--max-backoff argument must be at least 1");
2073 } else if (s->max_backoff > 3600) {
2074 s->max_backoff = 3600;
2078 case OPT_RATE_LIMIT:
2080 s->rate_limit = atoi(optarg);
2081 if (s->rate_limit < 1) {
2082 fatal(0, "--rate-limit argument must be at least 1");
2085 s->rate_limit = 1000;
2089 case OPT_BURST_LIMIT:
2090 s->burst_limit = atoi(optarg);
2091 if (s->burst_limit < 1) {
2092 fatal(0, "--burst-limit argument must be at least 1");
2101 set_pidfile(optarg);
2105 ignore_existing_pidfile();
2109 if (s->n_listeners >= MAX_MGMT) {
2110 fatal(0, "-l or --listen may be specified at most %d times",
2113 s->listener_names[s->n_listeners++] = optarg;
2117 if (s->monitor_name) {
2118 fatal(0, "-m or --monitor may only be specified once");
2120 s->monitor_name = optarg;
2127 printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
2131 vlog_set_verbosity(optarg);
2134 VCONN_SSL_OPTION_HANDLERS
2143 free(short_options);
2147 if (argc < 1 || argc > 2) {
2148 fatal(0, "need one or two non-option arguments; use --help for usage");
2151 /* Local and remote vconns. */
2152 s->nl_name = argv[0];
2153 if (strncmp(s->nl_name, "nl:", 3)
2154 || strlen(s->nl_name) < 4
2155 || s->nl_name[strspn(s->nl_name + 3, "0123456789") + 3]) {
2156 fatal(0, "%s: argument is not of the form \"nl:DP_IDX\"", s->nl_name);
2158 s->of_name = xasprintf("of%s", s->nl_name + 3);
2159 s->controller_name = argc > 1 ? xstrdup(argv[1]) : NULL;
2161 /* Set accept_controller_regex. */
2163 accept_re = vconn_ssl_is_configured() ? "^ssl:.*" : ".*";
2165 retval = regcomp(&s->accept_controller_regex, accept_re,
2166 REG_NOSUB | REG_EXTENDED);
2168 size_t length = regerror(retval, &s->accept_controller_regex, NULL, 0);
2169 char *buffer = xmalloc(length);
2170 regerror(retval, &s->accept_controller_regex, buffer, length);
2171 fatal(0, "%s: %s", accept_re, buffer);
2173 s->accept_controller_re = accept_re;
2175 /* Mode of operation. */
2176 s->discovery = s->controller_name == NULL;
2180 enum netdev_flags flags;
2181 struct netdev *netdev;
2183 retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
2185 fatal(retval, "Could not open %s device", s->of_name);
2188 retval = netdev_get_flags(netdev, &flags);
2190 fatal(retval, "Could not get flags for %s device", s->of_name);
2193 s->in_band = (flags & NETDEV_UP) != 0;
2194 if (s->in_band && netdev_get_in6(netdev, NULL)) {
2195 VLOG_WARN("Ignoring IPv6 address on %s device: IPv6 not supported",
2199 netdev_close(netdev);
2202 /* Rate limiting. */
2203 if (s->rate_limit) {
2204 if (s->rate_limit < 100) {
2205 VLOG_WARN("Rate limit set to unusually low value %d",
2208 if (!s->burst_limit) {
2209 s->burst_limit = s->rate_limit / 4;
2211 s->burst_limit = MAX(s->burst_limit, 1);
2212 s->burst_limit = MIN(s->burst_limit, INT_MAX / 1000);
2219 printf("%s: secure channel, a relay for OpenFlow messages.\n"
2220 "usage: %s [OPTIONS] nl:DP_IDX [CONTROLLER]\n"
2221 "where nl:DP_IDX is a datapath that has been added with dpctl.\n"
2222 "CONTROLLER is an active OpenFlow connection method; if it is\n"
2223 "omitted, then secchan performs controller discovery.\n",
2224 program_name, program_name);
2225 vconn_usage(true, true);
2226 printf("\nController discovery options:\n"
2227 " --accept-vconn=REGEX accept matching discovered controllers\n"
2228 " --no-resolv-conf do not update /etc/resolv.conf\n"
2229 "\nNetworking options:\n"
2230 " -F, --fail=open|closed when controller connection fails:\n"
2231 " closed: drop all packets\n"
2232 " open (default): act as learning switch\n"
2233 " --inactivity-probe=SECS time between inactivity probes\n"
2234 " --max-idle=SECS max idle for flows set up by secchan\n"
2235 " --max-backoff=SECS max time between controller connection\n"
2236 " attempts (default: 15 seconds)\n"
2237 " -l, --listen=METHOD allow management connections on METHOD\n"
2238 " (a passive OpenFlow connection method)\n"
2239 " -m, --monitor=METHOD copy traffic to/from kernel to METHOD\n"
2240 " (a passive OpenFlow connection method)\n"
2241 "\nRate-limiting of \"packet-in\" messages to the controller:\n"
2242 " --rate-limit[=PACKETS] max rate, in packets/s (default: 1000)\n"
2243 " --burst-limit=BURST limit on packet credit for idle time\n"
2244 "\nOther options:\n"
2245 " -D, --detach run in background as daemon\n"
2246 " -P, --pidfile[=FILE] create pidfile (default: %s/secchan.pid)\n"
2247 " -f, --force with -P, start even if already running\n"
2248 " -v, --verbose=MODULE[:FACILITY[:LEVEL]] set logging levels\n"
2249 " -v, --verbose set maximum verbosity level\n"
2250 " -h, --help display this help message\n"
2251 " -V, --version display version information\n",