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>
48 #include "command-line.h"
51 #include "dhcp-client.h"
53 #include "dynamic-string.h"
56 #include "learning-switch.h"
58 #include "mac-learning.h"
60 #include "nicira-ext.h"
64 #include "poll-loop.h"
69 #include "vconn-ssl.h"
71 #include "vlog-socket.h"
74 #define THIS_MODULE VLM_secchan
76 /* Behavior when the connection to the controller fails. */
78 FAIL_OPEN, /* Act as learning switch. */
79 FAIL_CLOSED /* Drop all packets. */
82 /* Maximum number of management connection listeners. */
85 /* Settings that may be configured by the user. */
87 /* Overall mode of operation. */
88 bool discovery; /* Discover the controller automatically? */
89 bool in_band; /* Connect to controller in-band? */
91 /* Related vconns and network devices. */
92 const char *nl_name; /* Local datapath (must be "nl:" vconn). */
93 char *of_name; /* ofX network device name. */
94 const char *controller_name; /* Controller (if not discovery mode). */
95 const char *listener_names[MAX_MGMT]; /* Listen for mgmt connections. */
96 size_t n_listeners; /* Number of mgmt connection listeners. */
97 const char *monitor_name; /* Listen for traffic monitor connections. */
99 /* Failure behavior. */
100 enum fail_mode fail_mode; /* Act as learning switch if no controller? */
101 int max_idle; /* Idle time for flows in fail-open mode. */
102 int probe_interval; /* # seconds idle before sending echo request. */
103 int max_backoff; /* Max # seconds between connection attempts. */
105 /* Packet-in rate-limiting. */
106 int rate_limit; /* Tokens added to bucket per second. */
107 int burst_limit; /* Maximum number token bucket size. */
109 /* Discovery behavior. */
110 regex_t accept_controller_regex; /* Controller vconns to accept. */
111 const char *accept_controller_re; /* String version of regex. */
112 bool update_resolv_conf; /* Update /etc/resolv.conf? */
114 /* Spanning tree protocol. */
120 struct ofpbuf *rxbuf;
121 int n_txq; /* No. of packets queued for tx on 'rconn'. */
128 #define HALF_REMOTE 1
129 struct half halves[2];
135 bool (*packet_cb[2])(struct relay *, void *aux);
136 void (*periodic_cb)(void *aux);
137 void (*wait_cb)(void *aux);
141 static struct vlog_rate_limit vrl = VLOG_RATE_LIMIT_INIT(60, 60);
143 static void parse_options(int argc, char *argv[], struct settings *);
144 static void usage(void) NO_RETURN;
146 static struct pvconn *open_passive_vconn(const char *name);
147 static struct vconn *accept_vconn(struct pvconn *pvconn);
149 static struct relay *relay_create(struct rconn *local, struct rconn *remote,
151 static struct relay *relay_accept(const struct settings *, struct pvconn *);
152 static void relay_run(struct relay *, const struct hook[], size_t n_hooks);
153 static void relay_wait(struct relay *);
154 static void relay_destroy(struct relay *);
156 static struct hook make_hook(bool (*local_packet_cb)(struct relay *, void *),
157 bool (*remote_packet_cb)(struct relay *, void *),
158 void (*periodic_cb)(void *),
159 void (*wait_cb)(void *),
161 static struct ofp_packet_in *get_ofp_packet_in(struct relay *);
162 static bool get_ofp_packet_eth_header(struct relay *, struct ofp_packet_in **,
163 struct eth_header **);
164 static void get_ofp_packet_payload(struct ofp_packet_in *, struct ofpbuf *);
166 struct switch_status;
168 static struct hook switch_status_hook_create(const struct settings *,
169 struct switch_status **);
170 static void switch_status_register_category(struct switch_status *,
171 const char *category,
172 void (*cb)(struct status_reply *,
175 static void status_reply_put(struct status_reply *, const char *, ...)
178 static void rconn_status_cb(struct status_reply *, void *rconn_);
180 static struct discovery *discovery_init(const struct settings *,
181 struct switch_status *);
182 static void discovery_question_connectivity(struct discovery *);
183 static bool discovery_run(struct discovery *, char **controller_name);
184 static void discovery_wait(struct discovery *);
186 static struct hook in_band_hook_create(const struct settings *,
187 struct switch_status *,
188 struct rconn *remote);
191 static struct hook port_watcher_create(struct rconn *local,
192 struct rconn *remote,
193 struct port_watcher **);
194 static uint32_t port_watcher_get_flags(const struct port_watcher *,
196 static void port_watcher_set_flags(struct port_watcher *,
197 int port_no, uint32_t flags, uint32_t mask);
199 static struct hook stp_hook_create(const struct settings *,
200 struct port_watcher *,
201 struct rconn *local, struct rconn *remote);
203 static struct hook fail_open_hook_create(const struct settings *,
204 struct switch_status *,
206 struct rconn *remote);
207 static struct hook rate_limit_hook_create(const struct settings *,
208 struct switch_status *,
210 struct rconn *remote);
213 static void modify_dhcp_request(struct dhcp_msg *, void *aux);
214 static bool validate_dhcp_offer(const struct dhcp_msg *, void *aux);
217 main(int argc, char *argv[])
221 struct list relays = LIST_INITIALIZER(&relays);
223 struct hook hooks[8];
226 struct pvconn *monitor;
228 struct pvconn *listeners[MAX_MGMT];
231 struct rconn *local_rconn, *remote_rconn;
232 struct relay *controller_relay;
233 struct discovery *discovery;
234 struct switch_status *switch_status;
235 struct port_watcher *pw;
239 set_program_name(argv[0]);
240 register_fault_handlers();
243 parse_options(argc, argv, &s);
244 signal(SIGPIPE, SIG_IGN);
246 /* Start listening for management and monitoring connections. */
248 for (i = 0; i < s.n_listeners; i++) {
249 listeners[n_listeners++] = open_passive_vconn(s.listener_names[i]);
251 monitor = s.monitor_name ? open_passive_vconn(s.monitor_name) : NULL;
253 /* Initialize switch status hook. */
254 hooks[n_hooks++] = switch_status_hook_create(&s, &switch_status);
256 /* Start controller discovery. */
257 discovery = s.discovery ? discovery_init(&s, switch_status) : NULL;
259 /* Start listening for vlogconf requests. */
260 retval = vlog_server_listen(NULL, NULL);
262 ofp_fatal(retval, "Could not listen for vlog connections");
265 die_if_already_running();
268 VLOG_WARN("OpenFlow reference implementation version %s", VERSION);
269 VLOG_WARN("OpenFlow protocol version 0x%02x", OFP_VERSION);
271 /* Connect to datapath. */
272 local_rconn = rconn_create(0, s.max_backoff);
273 rconn_connect(local_rconn, s.nl_name);
274 switch_status_register_category(switch_status, "local",
275 rconn_status_cb, local_rconn);
277 /* Connect to controller. */
278 remote_rconn = rconn_create(s.probe_interval, s.max_backoff);
279 if (s.controller_name) {
280 retval = rconn_connect(remote_rconn, s.controller_name);
281 if (retval == EAFNOSUPPORT) {
282 ofp_fatal(0, "No support for %s vconn", s.controller_name);
285 switch_status_register_category(switch_status, "remote",
286 rconn_status_cb, remote_rconn);
288 /* Start relaying. */
289 controller_relay = relay_create(local_rconn, remote_rconn, false);
290 list_push_back(&relays, &controller_relay->node);
293 hooks[n_hooks++] = port_watcher_create(local_rconn, remote_rconn, &pw);
295 hooks[n_hooks++] = stp_hook_create(&s, pw, local_rconn, remote_rconn);
298 hooks[n_hooks++] = in_band_hook_create(&s, switch_status,
301 if (s.fail_mode == FAIL_OPEN) {
302 hooks[n_hooks++] = fail_open_hook_create(&s, switch_status,
303 local_rconn, remote_rconn);
306 hooks[n_hooks++] = rate_limit_hook_create(&s, switch_status,
307 local_rconn, remote_rconn);
309 assert(n_hooks <= ARRAY_SIZE(hooks));
316 LIST_FOR_EACH_SAFE (r, n, struct relay, node, &relays) {
317 relay_run(r, hooks, n_hooks);
319 for (i = 0; i < n_listeners; i++) {
321 struct relay *r = relay_accept(&s, listeners[i]);
325 list_push_back(&relays, &r->node);
329 struct vconn *new = accept_vconn(monitor);
331 rconn_add_monitor(local_rconn, new);
334 for (i = 0; i < n_hooks; i++) {
335 if (hooks[i].periodic_cb) {
336 hooks[i].periodic_cb(hooks[i].aux);
340 char *controller_name;
341 if (rconn_is_connectivity_questionable(remote_rconn)) {
342 discovery_question_connectivity(discovery);
344 if (discovery_run(discovery, &controller_name)) {
345 if (controller_name) {
346 rconn_connect(remote_rconn, controller_name);
348 rconn_disconnect(remote_rconn);
353 /* Wait for something to happen. */
354 LIST_FOR_EACH (r, struct relay, node, &relays) {
357 for (i = 0; i < n_listeners; i++) {
358 pvconn_wait(listeners[i]);
361 pvconn_wait(monitor);
363 for (i = 0; i < n_hooks; i++) {
364 if (hooks[i].wait_cb) {
365 hooks[i].wait_cb(hooks[i].aux);
369 discovery_wait(discovery);
377 static struct pvconn *
378 open_passive_vconn(const char *name)
380 struct pvconn *pvconn;
383 retval = pvconn_open(name, &pvconn);
384 if (retval && retval != EAGAIN) {
385 ofp_fatal(retval, "opening %s", name);
390 static struct vconn *
391 accept_vconn(struct pvconn *pvconn)
396 retval = pvconn_accept(pvconn, OFP_VERSION, &new);
397 if (retval && retval != EAGAIN) {
398 VLOG_WARN_RL(&vrl, "accept failed (%s)", strerror(retval));
404 make_hook(bool (*local_packet_cb)(struct relay *, void *aux),
405 bool (*remote_packet_cb)(struct relay *, void *aux),
406 void (*periodic_cb)(void *aux),
407 void (*wait_cb)(void *aux),
411 h.packet_cb[HALF_LOCAL] = local_packet_cb;
412 h.packet_cb[HALF_REMOTE] = remote_packet_cb;
413 h.periodic_cb = periodic_cb;
419 static struct ofp_packet_in *
420 get_ofp_packet_in(struct relay *r)
422 struct ofpbuf *msg = r->halves[HALF_LOCAL].rxbuf;
423 struct ofp_header *oh = msg->data;
424 if (oh->type == OFPT_PACKET_IN) {
425 if (msg->size >= offsetof (struct ofp_packet_in, data)) {
428 VLOG_WARN("packet too short (%zu bytes) for packet_in",
436 get_ofp_packet_eth_header(struct relay *r, struct ofp_packet_in **opip,
437 struct eth_header **ethp)
439 const int min_len = offsetof(struct ofp_packet_in, data) + ETH_HEADER_LEN;
440 struct ofp_packet_in *opi = get_ofp_packet_in(r);
441 if (opi && ntohs(opi->header.length) >= min_len) {
443 *ethp = (void *) opi->data;
450 /* OpenFlow message relaying. */
452 static struct relay *
453 relay_accept(const struct settings *s, struct pvconn *pvconn)
455 struct vconn *new_remote, *new_local;
456 char *nl_name_without_subscription;
457 struct rconn *r1, *r2;
460 new_remote = accept_vconn(pvconn);
465 /* nl:123 or nl:123:1 opens a netlink connection to local datapath 123. We
466 * only accept the former syntax in main().
468 * nl:123:0 opens a netlink connection to local datapath 123 without
469 * obtaining a subscription for ofp_packet_in or ofp_flow_expired
471 nl_name_without_subscription = xasprintf("%s:0", s->nl_name);
472 retval = vconn_open(nl_name_without_subscription, OFP_VERSION, &new_local);
474 VLOG_ERR_RL(&vrl, "could not connect to %s (%s)",
475 nl_name_without_subscription, strerror(retval));
476 vconn_close(new_remote);
477 free(nl_name_without_subscription);
481 /* Create and return relay. */
482 r1 = rconn_create(0, 0);
483 rconn_connect_unreliably(r1, nl_name_without_subscription, new_local);
484 free(nl_name_without_subscription);
486 r2 = rconn_create(0, 0);
487 rconn_connect_unreliably(r2, "passive", new_remote);
489 return relay_create(r1, r2, true);
492 static struct relay *
493 relay_create(struct rconn *local, struct rconn *remote, bool is_mgmt_conn)
495 struct relay *r = xcalloc(1, sizeof *r);
496 r->halves[HALF_LOCAL].rconn = local;
497 r->halves[HALF_REMOTE].rconn = remote;
498 r->is_mgmt_conn = is_mgmt_conn;
503 relay_run(struct relay *r, const struct hook hooks[], size_t n_hooks)
508 for (i = 0; i < 2; i++) {
509 rconn_run(r->halves[i].rconn);
512 /* Limit the number of iterations to prevent other tasks from starving. */
513 for (iteration = 0; iteration < 50; iteration++) {
514 bool progress = false;
515 for (i = 0; i < 2; i++) {
516 struct half *this = &r->halves[i];
517 struct half *peer = &r->halves[!i];
520 this->rxbuf = rconn_recv(this->rconn);
521 if (this->rxbuf && (i == HALF_REMOTE || !r->is_mgmt_conn)) {
522 const struct hook *h;
523 for (h = hooks; h < &hooks[n_hooks]; h++) {
524 if (h->packet_cb[i] && h->packet_cb[i](r, h->aux)) {
525 ofpbuf_delete(this->rxbuf);
534 if (this->rxbuf && !this->n_txq) {
535 int retval = rconn_send(peer->rconn, this->rxbuf,
537 if (retval != EAGAIN) {
541 ofpbuf_delete(this->rxbuf);
552 if (r->is_mgmt_conn) {
553 for (i = 0; i < 2; i++) {
554 struct half *this = &r->halves[i];
555 if (!rconn_is_alive(this->rconn)) {
564 relay_wait(struct relay *r)
568 for (i = 0; i < 2; i++) {
569 struct half *this = &r->halves[i];
571 rconn_run_wait(this->rconn);
573 rconn_recv_wait(this->rconn);
579 relay_destroy(struct relay *r)
583 list_remove(&r->node);
584 for (i = 0; i < 2; i++) {
585 struct half *this = &r->halves[i];
586 rconn_destroy(this->rconn);
587 ofpbuf_delete(this->rxbuf);
592 /* Port status watcher. */
594 typedef void port_changed_cb_func(uint16_t port_no,
595 const struct ofp_phy_port *old,
596 const struct ofp_phy_port *new,
599 struct port_watcher_cb {
600 port_changed_cb_func *port_changed;
604 struct port_watcher {
605 struct rconn *local_rconn;
606 struct rconn *remote_rconn;
607 struct ofp_phy_port ports[OFPP_MAX + 1];
608 time_t last_feature_request;
609 bool got_feature_reply;
611 struct port_watcher_cb cbs[2];
615 /* Returns the number of fields that differ from 'a' to 'b'. */
617 opp_differs(const struct ofp_phy_port *a, const struct ofp_phy_port *b)
619 BUILD_ASSERT_DECL(sizeof *a == 36); /* Trips when we add or remove fields. */
620 return ((a->port_no != b->port_no)
621 + (memcmp(a->hw_addr, b->hw_addr, sizeof a->hw_addr) != 0)
622 + (memcmp(a->name, b->name, sizeof a->name) != 0)
623 + (a->flags != b->flags)
624 + (a->speed != b->speed)
625 + (a->features != b->features));
629 sanitize_opp(struct ofp_phy_port *opp)
633 for (i = 0; i < sizeof opp->name; i++) {
634 char c = opp->name[i];
635 if (c && (c < 0x20 || c > 0x7e)) {
639 opp->name[sizeof opp->name - 1] = '\0';
643 port_no_to_pw_idx(int port_no)
645 return (port_no < OFPP_MAX ? port_no
646 : port_no == OFPP_LOCAL ? OFPP_MAX
651 call_port_changed_callbacks(struct port_watcher *pw, int port_no,
652 const struct ofp_phy_port *old,
653 const struct ofp_phy_port *new)
655 if (opp_differs(old, new)) {
657 for (i = 0; i < pw->n_cbs; i++) {
658 port_changed_cb_func *port_changed = pw->cbs[i].port_changed;
660 (port_changed)(port_no, old, new, pw->cbs[i].aux);
667 update_phy_port(struct port_watcher *pw, struct ofp_phy_port *opp,
668 uint8_t reason, bool seen[OFPP_MAX + 1])
670 struct ofp_phy_port *pw_opp;
671 struct ofp_phy_port old;
675 port_no = ntohs(opp->port_no);
676 idx = port_no_to_pw_idx(port_no);
685 pw_opp = &pw->ports[idx];
687 if (reason == OFPPR_DELETE) {
688 memset(pw_opp, 0, sizeof *pw_opp);
689 pw_opp->port_no = htons(OFPP_NONE);
690 } else if (reason == OFPPR_MOD || reason == OFPPR_ADD) {
692 sanitize_opp(pw_opp);
694 call_port_changed_callbacks(pw, port_no, &old, pw_opp);
698 port_watcher_local_packet_cb(struct relay *r, void *pw_)
700 struct port_watcher *pw = pw_;
701 struct ofpbuf *msg = r->halves[HALF_LOCAL].rxbuf;
702 struct ofp_header *oh = msg->data;
704 if (oh->type == OFPT_FEATURES_REPLY
705 && msg->size >= offsetof(struct ofp_switch_features, ports)) {
706 struct ofp_switch_features *osf = msg->data;
707 bool seen[ARRAY_SIZE(pw->ports)];
711 pw->got_feature_reply = true;
713 /* Update each port included in the message. */
714 memset(seen, 0, sizeof seen);
715 n_ports = ((msg->size - offsetof(struct ofp_switch_features, ports))
716 / sizeof *osf->ports);
717 for (i = 0; i < n_ports; i++) {
718 struct ofp_phy_port *opp = &osf->ports[i];
719 update_phy_port(pw, opp, OFPPR_MOD, seen);
722 /* Delete all the ports not included in the message. */
723 for (i = 0; i < ARRAY_SIZE(pw->ports); i++) {
725 update_phy_port(pw, &pw->ports[i], OFPPR_DELETE, NULL);
728 } else if (oh->type == OFPT_PORT_STATUS
729 && msg->size >= sizeof(struct ofp_port_status)) {
730 struct ofp_port_status *ops = msg->data;
731 update_phy_port(pw, &ops->desc, ops->reason, NULL);
737 port_watcher_remote_packet_cb(struct relay *r, void *pw_)
739 struct port_watcher *pw = pw_;
740 struct ofpbuf *msg = r->halves[HALF_REMOTE].rxbuf;
741 struct ofp_header *oh = msg->data;
743 if (oh->type == OFPT_PORT_MOD
744 && msg->size >= sizeof(struct ofp_port_mod)) {
745 struct ofp_port_mod *opm = msg->data;
746 uint16_t port_no = ntohs(opm->desc.port_no);
747 int idx = port_no_to_pw_idx(port_no);
749 struct ofp_phy_port *pw_opp = &pw->ports[idx];
750 if (pw_opp->port_no != htons(OFPP_NONE)) {
751 struct ofp_phy_port old = *pw_opp;
752 pw_opp->flags = ((pw_opp->flags & ~opm->mask)
753 | (opm->desc.flags & opm->mask));
754 call_port_changed_callbacks(pw, port_no, &old, pw_opp);
762 port_watcher_periodic_cb(void *pw_)
764 struct port_watcher *pw = pw_;
766 if (!pw->got_feature_reply && time_now() >= pw->last_feature_request + 5) {
768 make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &b);
769 rconn_send_with_limit(pw->local_rconn, b, &pw->n_txq, 1);
770 pw->last_feature_request = time_now();
775 put_duplexes(struct ds *ds, const char *name, uint32_t features,
776 uint32_t hd_bit, uint32_t fd_bit)
778 if (features & (hd_bit | fd_bit)) {
779 ds_put_format(ds, " %s", name);
780 if (features & hd_bit) {
781 ds_put_cstr(ds, "(HD)");
783 if (features & fd_bit) {
784 ds_put_cstr(ds, "(FD)");
790 log_port_status(uint16_t port_no,
791 const struct ofp_phy_port *old,
792 const struct ofp_phy_port *new,
795 if (VLOG_IS_DBG_ENABLED()) {
796 bool was_enabled = old->port_no != htons(OFPP_NONE);
797 bool now_enabled = new->port_no != htons(OFPP_NONE);
798 uint32_t features = ntohl(new->features);
801 if (old->flags != new->flags && opp_differs(old, new) == 1) {
802 /* Don't care if only flags changed. */
807 ds_put_format(&ds, "\"%s\", "ETH_ADDR_FMT, new->name,
808 ETH_ADDR_ARGS(new->hw_addr));
809 if (ntohl(new->speed)) {
810 ds_put_format(&ds, ", speed %"PRIu32, ntohl(new->speed));
812 if (features & (OFPPF_10MB_HD | OFPPF_10MB_FD
813 | OFPPF_100MB_HD | OFPPF_100MB_FD
814 | OFPPF_1GB_HD | OFPPF_1GB_FD | OFPPF_10GB_FD)) {
815 ds_put_cstr(&ds, ", supports");
816 put_duplexes(&ds, "10M", features, OFPPF_10MB_HD, OFPPF_10MB_FD);
817 put_duplexes(&ds, "100M", features,
818 OFPPF_100MB_HD, OFPPF_100MB_FD);
819 put_duplexes(&ds, "1G", features, OFPPF_100MB_HD, OFPPF_100MB_FD);
820 if (features & OFPPF_10GB_FD) {
821 ds_put_cstr(&ds, " 10G");
824 if (was_enabled != now_enabled) {
826 VLOG_DBG("Port %d added: %s", port_no, ds_cstr(&ds));
828 VLOG_DBG("Port %d deleted", port_no);
831 VLOG_DBG("Port %d changed: %s", port_no, ds_cstr(&ds));
838 port_watcher_register_callback(struct port_watcher *pw,
839 port_changed_cb_func *port_changed,
842 assert(pw->n_cbs < ARRAY_SIZE(pw->cbs));
843 pw->cbs[pw->n_cbs].port_changed = port_changed;
844 pw->cbs[pw->n_cbs].aux = aux;
849 port_watcher_get_flags(const struct port_watcher *pw, int port_no)
851 int idx = port_no_to_pw_idx(port_no);
852 return idx >= 0 ? ntohl(pw->ports[idx].flags) : 0;
856 port_watcher_set_flags(struct port_watcher *pw,
857 int port_no, uint32_t flags, uint32_t mask)
859 struct ofp_phy_port old;
860 struct ofp_phy_port *p;
861 struct ofp_port_mod *opm;
862 struct ofp_port_status *ops;
866 idx = port_no_to_pw_idx(port_no);
872 if (!((ntohl(p->flags) ^ flags) & mask)) {
877 /* Update our idea of the flags. */
878 p->flags = htonl((ntohl(p->flags) & ~mask) | (flags & mask));
879 call_port_changed_callbacks(pw, port_no, &old, p);
881 /* Change the flags in the datapath. */
882 opm = make_openflow(sizeof *opm, OFPT_PORT_MOD, &b);
883 opm->mask = htonl(mask);
885 rconn_send(pw->local_rconn, b, NULL);
887 /* Notify the controller that the flags changed. */
888 ops = make_openflow(sizeof *ops, OFPT_PORT_STATUS, &b);
889 ops->reason = OFPPR_MOD;
891 rconn_send(pw->remote_rconn, b, NULL);
895 port_watcher_is_ready(const struct port_watcher *pw)
897 return pw->got_feature_reply;
901 port_watcher_create(struct rconn *local_rconn, struct rconn *remote_rconn,
902 struct port_watcher **pwp)
904 struct port_watcher *pw;
907 pw = *pwp = xcalloc(1, sizeof *pw);
908 pw->local_rconn = local_rconn;
909 pw->remote_rconn = remote_rconn;
910 pw->last_feature_request = TIME_MIN;
911 for (i = 0; i < OFPP_MAX; i++) {
912 pw->ports[i].port_no = htons(OFPP_NONE);
914 port_watcher_register_callback(pw, log_port_status, NULL);
915 return make_hook(port_watcher_local_packet_cb,
916 port_watcher_remote_packet_cb,
917 port_watcher_periodic_cb, NULL, pw);
920 /* Spanning tree protocol. */
922 /* Extra time, in seconds, at boot before going into fail-open, to give the
923 * spanning tree protocol time to figure out the network layout. */
924 #define STP_EXTRA_BOOT_TIME 30
928 struct port_watcher *pw;
929 struct rconn *local_rconn;
930 struct rconn *remote_rconn;
931 uint8_t dpid[ETH_ADDR_LEN];
932 long long int last_tick_256ths;
937 stp_local_packet_cb(struct relay *r, void *stp_)
939 struct ofpbuf *msg = r->halves[HALF_LOCAL].rxbuf;
940 struct ofp_header *oh;
941 struct stp_data *stp = stp_;
942 struct ofp_packet_in *opi;
943 struct eth_header *eth;
944 struct llc_header *llc;
945 struct ofpbuf payload;
950 if (oh->type == OFPT_FEATURES_REPLY
951 && msg->size >= offsetof(struct ofp_switch_features, ports)) {
952 struct ofp_switch_features *osf = msg->data;
953 osf->capabilities |= htonl(OFPC_STP);
957 if (!get_ofp_packet_eth_header(r, &opi, ð)
958 || !eth_addr_equals(eth->eth_dst, stp_eth_addr)) {
962 port_no = ntohs(opi->in_port);
963 if (port_no >= STP_MAX_PORTS) {
964 /* STP only supports 255 ports. */
967 if (port_watcher_get_flags(stp->pw, port_no) & OFPPFL_NO_STP) {
968 /* We're not doing STP on this port. */
972 if (opi->reason == OFPR_ACTION) {
973 /* The controller set up a flow for this, so we won't intercept it. */
977 get_ofp_packet_payload(opi, &payload);
978 flow_extract(&payload, port_no, &flow);
979 if (flow.dl_type != htons(OFP_DL_TYPE_NOT_ETH_TYPE)) {
980 VLOG_DBG("non-LLC frame received on STP multicast address");
983 llc = ofpbuf_at_assert(&payload, sizeof *eth, sizeof *llc);
984 if (llc->llc_dsap != STP_LLC_DSAP) {
985 VLOG_DBG("bad DSAP 0x%02"PRIx8" received on STP multicast address",
990 /* Trim off padding on payload. */
991 if (payload.size > ntohs(eth->eth_type) + ETH_HEADER_LEN) {
992 payload.size = ntohs(eth->eth_type) + ETH_HEADER_LEN;
994 if (ofpbuf_try_pull(&payload, ETH_HEADER_LEN + LLC_HEADER_LEN)) {
995 struct stp_port *p = stp_get_port(stp->stp, port_no);
996 stp_received_bpdu(p, payload.data, payload.size);
1002 static long long int
1005 return time_msec() * 256 / 1000;
1009 stp_periodic_cb(void *stp_)
1011 struct stp_data *stp = stp_;
1012 long long int now_256ths = time_256ths();
1013 long long int elapsed_256ths = now_256ths - stp->last_tick_256ths;
1016 if (!port_watcher_is_ready(stp->pw)) {
1017 /* Can't start STP until we know port flags, because port flags can
1021 if (elapsed_256ths <= 0) {
1025 stp_tick(stp->stp, MIN(INT_MAX, elapsed_256ths));
1026 stp->last_tick_256ths = now_256ths;
1028 while (stp_get_changed_port(stp->stp, &p)) {
1029 int port_no = stp_port_no(p);
1030 enum stp_state state = stp_port_get_state(p);
1032 if (state != STP_DISABLED) {
1033 VLOG_WARN("STP: Port %d entered %s state",
1034 port_no, stp_state_name(state));
1036 if (!(port_watcher_get_flags(stp->pw, port_no) & OFPPFL_NO_STP)) {
1040 flags = OFPPFL_STP_LISTEN;
1043 flags = OFPPFL_STP_LEARN;
1046 case STP_FORWARDING:
1047 flags = OFPPFL_STP_FORWARD;
1050 flags = OFPPFL_STP_BLOCK;
1053 VLOG_DBG_RL(&vrl, "STP: Port %d has bad state %x",
1055 flags = OFPPFL_STP_FORWARD;
1058 if (!stp_forward_in_state(state)) {
1059 flags |= OFPPFL_NO_FLOOD;
1061 port_watcher_set_flags(stp->pw, port_no, flags,
1062 OFPPFL_STP_MASK | OFPPFL_NO_FLOOD);
1064 /* We don't own those flags. */
1070 stp_wait_cb(void *stp_ UNUSED)
1072 poll_timer_wait(1000);
1076 send_bpdu(const void *bpdu, size_t bpdu_size, int port_no, void *stp_)
1078 struct stp_data *stp = stp_;
1079 struct eth_header *eth;
1080 struct llc_header *llc;
1081 struct ofpbuf pkt, *opo;
1083 /* Packet skeleton. */
1084 ofpbuf_init(&pkt, ETH_HEADER_LEN + LLC_HEADER_LEN + bpdu_size);
1085 eth = ofpbuf_put_uninit(&pkt, sizeof *eth);
1086 llc = ofpbuf_put_uninit(&pkt, sizeof *llc);
1087 ofpbuf_put(&pkt, bpdu, bpdu_size);
1090 memcpy(eth->eth_dst, stp_eth_addr, ETH_ADDR_LEN);
1091 memcpy(eth->eth_src, stp->pw->ports[port_no].hw_addr, ETH_ADDR_LEN);
1092 eth->eth_type = htons(pkt.size - ETH_HEADER_LEN);
1095 llc->llc_dsap = STP_LLC_DSAP;
1096 llc->llc_ssap = STP_LLC_SSAP;
1097 llc->llc_cntl = STP_LLC_CNTL;
1099 opo = make_unbuffered_packet_out(&pkt, OFPP_NONE, port_no);
1100 ofpbuf_uninit(&pkt);
1101 rconn_send_with_limit(stp->local_rconn, opo, &stp->n_txq, OFPP_MAX);
1105 stp_is_port_supported(uint16_t port_no)
1107 /* We should be able to support STP on all possible OpenFlow physical
1108 * ports. (But we don't support STP on OFPP_LOCAL.) */
1109 BUILD_ASSERT_DECL(STP_MAX_PORTS >= OFPP_MAX);
1110 return port_no < STP_MAX_PORTS;
1114 stp_port_changed_cb(uint16_t port_no,
1115 const struct ofp_phy_port *old,
1116 const struct ofp_phy_port *new,
1119 struct stp_data *stp = stp_;
1122 if (!stp_is_port_supported(port_no)) {
1126 p = stp_get_port(stp->stp, port_no);
1127 if (new->port_no == htons(OFPP_NONE)
1128 || new->flags & htonl(OFPPFL_NO_STP)) {
1129 stp_port_disable(p);
1132 stp_port_set_speed(p, new->speed);
1137 stp_hook_create(const struct settings *s, struct port_watcher *pw,
1138 struct rconn *local, struct rconn *remote)
1140 uint8_t dpid[ETH_ADDR_LEN];
1141 struct netdev *netdev;
1142 struct stp_data *stp;
1145 retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
1147 ofp_fatal(retval, "Could not open %s device", s->of_name);
1149 memcpy(dpid, netdev_get_etheraddr(netdev), ETH_ADDR_LEN);
1150 netdev_close(netdev);
1152 stp = xcalloc(1, sizeof *stp);
1153 stp->stp = stp_create("stp", eth_addr_to_uint64(dpid), send_bpdu, stp);
1155 memcpy(stp->dpid, dpid, ETH_ADDR_LEN);
1156 stp->local_rconn = local;
1157 stp->remote_rconn = remote;
1158 stp->last_tick_256ths = time_256ths();
1160 port_watcher_register_callback(pw, stp_port_changed_cb, stp);
1161 return make_hook(stp_local_packet_cb, NULL,
1162 stp_periodic_cb, stp_wait_cb, stp);
1165 /* In-band control. */
1167 struct in_band_data {
1168 const struct settings *s;
1169 struct mac_learning *ml;
1170 struct netdev *of_device;
1171 struct rconn *controller;
1172 uint8_t mac[ETH_ADDR_LEN];
1177 queue_tx(struct rconn *rc, struct in_band_data *in_band, struct ofpbuf *b)
1179 rconn_send_with_limit(rc, b, &in_band->n_queued, 10);
1182 static const uint8_t *
1183 get_controller_mac(struct in_band_data *in_band)
1185 static uint32_t ip, last_nonzero_ip;
1186 static uint8_t mac[ETH_ADDR_LEN], last_nonzero_mac[ETH_ADDR_LEN];
1187 static time_t next_refresh = 0;
1189 uint32_t last_ip = ip;
1191 time_t now = time_now();
1193 ip = rconn_get_ip(in_band->controller);
1194 if (last_ip != ip || !next_refresh || now >= next_refresh) {
1197 /* Look up MAC address. */
1198 memset(mac, 0, sizeof mac);
1200 int retval = netdev_arp_lookup(in_band->of_device, ip, mac);
1202 VLOG_DBG("cannot look up controller hw address ("IP_FMT"): %s",
1203 IP_ARGS(&ip), strerror(retval));
1206 have_mac = !eth_addr_is_zero(mac);
1208 /* Log changes in IP, MAC addresses. */
1209 if (ip && ip != last_nonzero_ip) {
1210 VLOG_DBG("controller IP address changed from "IP_FMT
1211 " to "IP_FMT, IP_ARGS(&last_nonzero_ip), IP_ARGS(&ip));
1212 last_nonzero_ip = ip;
1214 if (have_mac && memcmp(last_nonzero_mac, mac, ETH_ADDR_LEN)) {
1215 VLOG_DBG("controller MAC address changed from "ETH_ADDR_FMT" to "
1217 ETH_ADDR_ARGS(last_nonzero_mac), ETH_ADDR_ARGS(mac));
1218 memcpy(last_nonzero_mac, mac, ETH_ADDR_LEN);
1221 /* Schedule next refresh.
1223 * If we have an IP address but not a MAC address, then refresh
1224 * quickly, since we probably will get a MAC address soon (via ARP).
1225 * Otherwise, we can afford to wait a little while. */
1226 next_refresh = now + (!ip || have_mac ? 10 : 1);
1228 return !eth_addr_is_zero(mac) ? mac : NULL;
1232 is_controller_mac(const uint8_t dl_addr[ETH_ADDR_LEN],
1233 struct in_band_data *in_band)
1235 const uint8_t *mac = get_controller_mac(in_band);
1236 return mac && eth_addr_equals(mac, dl_addr);
1240 in_band_learn_mac(struct in_band_data *in_band,
1241 uint16_t in_port, const uint8_t src_mac[ETH_ADDR_LEN])
1243 if (mac_learning_learn(in_band->ml, src_mac, in_port)) {
1244 VLOG_DBG_RL(&vrl, "learned that "ETH_ADDR_FMT" is on port %"PRIu16,
1245 ETH_ADDR_ARGS(src_mac), in_port);
1250 in_band_local_packet_cb(struct relay *r, void *in_band_)
1252 struct in_band_data *in_band = in_band_;
1253 struct rconn *rc = r->halves[HALF_LOCAL].rconn;
1254 struct ofp_packet_in *opi;
1255 struct eth_header *eth;
1256 struct ofpbuf payload;
1261 if (!get_ofp_packet_eth_header(r, &opi, ð)) {
1264 in_port = ntohs(opi->in_port);
1266 /* Deal with local stuff. */
1267 if (in_port == OFPP_LOCAL) {
1268 /* Sent by secure channel. */
1269 out_port = mac_learning_lookup(in_band->ml, eth->eth_dst);
1270 } else if (eth_addr_equals(eth->eth_dst, in_band->mac)) {
1271 /* Sent to secure channel. */
1272 out_port = OFPP_LOCAL;
1273 in_band_learn_mac(in_band, in_port, eth->eth_src);
1274 } else if (eth->eth_type == htons(ETH_TYPE_ARP)
1275 && eth_addr_is_broadcast(eth->eth_dst)
1276 && is_controller_mac(eth->eth_src, in_band)) {
1277 /* ARP sent by controller. */
1278 out_port = OFPP_FLOOD;
1279 } else if (is_controller_mac(eth->eth_dst, in_band)
1280 || is_controller_mac(eth->eth_src, in_band)) {
1281 /* Traffic to or from controller. Switch it by hand. */
1282 in_band_learn_mac(in_band, in_port, eth->eth_src);
1283 out_port = mac_learning_lookup(in_band->ml, eth->eth_dst);
1285 const uint8_t *controller_mac;
1286 controller_mac = get_controller_mac(in_band);
1287 if (eth->eth_type == htons(ETH_TYPE_ARP)
1288 && eth_addr_is_broadcast(eth->eth_dst)
1289 && is_controller_mac(eth->eth_src, in_band)) {
1290 /* ARP sent by controller. */
1291 out_port = OFPP_FLOOD;
1292 } else if (is_controller_mac(eth->eth_dst, in_band)
1293 && in_port == mac_learning_lookup(in_band->ml,
1295 /* Drop controller traffic that arrives on the controller port. */
1302 get_ofp_packet_payload(opi, &payload);
1303 flow_extract(&payload, in_port, &flow);
1304 if (in_port == out_port) {
1305 /* The input and output port match. Set up a flow to drop packets. */
1306 queue_tx(rc, in_band, make_add_flow(&flow, ntohl(opi->buffer_id),
1307 in_band->s->max_idle, 0));
1308 } else if (out_port != OFPP_FLOOD) {
1309 /* The output port is known, so add a new flow. */
1310 queue_tx(rc, in_band,
1311 make_add_simple_flow(&flow, ntohl(opi->buffer_id),
1312 out_port, in_band->s->max_idle));
1314 /* If the switch didn't buffer the packet, we need to send a copy. */
1315 if (ntohl(opi->buffer_id) == UINT32_MAX) {
1316 queue_tx(rc, in_band,
1317 make_unbuffered_packet_out(&payload, in_port, out_port));
1320 /* We don't know that MAC. Send along the packet without setting up a
1323 if (ntohl(opi->buffer_id) == UINT32_MAX) {
1324 b = make_unbuffered_packet_out(&payload, in_port, out_port);
1326 b = make_buffered_packet_out(ntohl(opi->buffer_id),
1329 queue_tx(rc, in_band, b);
1335 in_band_status_cb(struct status_reply *sr, void *in_band_)
1337 struct in_band_data *in_band = in_band_;
1338 struct in_addr local_ip;
1339 uint32_t controller_ip;
1340 const uint8_t *controller_mac;
1342 if (netdev_get_in4(in_band->of_device, &local_ip)) {
1343 status_reply_put(sr, "local-ip="IP_FMT, IP_ARGS(&local_ip.s_addr));
1345 status_reply_put(sr, "local-mac="ETH_ADDR_FMT,
1346 ETH_ADDR_ARGS(in_band->mac));
1348 controller_ip = rconn_get_ip(in_band->controller);
1349 if (controller_ip) {
1350 status_reply_put(sr, "controller-ip="IP_FMT,
1351 IP_ARGS(&controller_ip));
1353 controller_mac = get_controller_mac(in_band);
1354 if (controller_mac) {
1355 status_reply_put(sr, "controller-mac="ETH_ADDR_FMT,
1356 ETH_ADDR_ARGS(controller_mac));
1361 get_ofp_packet_payload(struct ofp_packet_in *opi, struct ofpbuf *payload)
1363 payload->data = opi->data;
1364 payload->size = ntohs(opi->header.length) - offsetof(struct ofp_packet_in,
1369 in_band_hook_create(const struct settings *s, struct switch_status *ss,
1370 struct rconn *remote)
1372 struct in_band_data *in_band;
1375 in_band = xcalloc(1, sizeof *in_band);
1377 in_band->ml = mac_learning_create();
1378 retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE,
1379 &in_band->of_device);
1381 ofp_fatal(retval, "Could not open %s device", s->of_name);
1383 memcpy(in_band->mac, netdev_get_etheraddr(in_band->of_device),
1385 in_band->controller = remote;
1386 switch_status_register_category(ss, "in-band", in_band_status_cb, in_band);
1387 return make_hook(in_band_local_packet_cb, NULL, NULL, NULL, in_band);
1390 /* Fail open support. */
1392 struct fail_open_data {
1393 const struct settings *s;
1394 struct rconn *local_rconn;
1395 struct rconn *remote_rconn;
1396 struct lswitch *lswitch;
1397 int last_disconn_secs;
1398 time_t boot_deadline;
1401 /* Causes 'r' to enter or leave fail-open mode, if appropriate. */
1403 fail_open_periodic_cb(void *fail_open_)
1405 struct fail_open_data *fail_open = fail_open_;
1409 if (time_now() < fail_open->boot_deadline) {
1412 disconn_secs = rconn_disconnected_duration(fail_open->remote_rconn);
1413 open = disconn_secs >= fail_open->s->probe_interval * 3;
1414 if (open != (fail_open->lswitch != NULL)) {
1416 VLOG_WARN("No longer in fail-open mode");
1417 lswitch_destroy(fail_open->lswitch);
1418 fail_open->lswitch = NULL;
1420 VLOG_WARN("Could not connect to controller for %d seconds, "
1421 "failing open", disconn_secs);
1422 fail_open->lswitch = lswitch_create(fail_open->local_rconn, true,
1423 fail_open->s->max_idle);
1424 fail_open->last_disconn_secs = disconn_secs;
1426 } else if (open && disconn_secs > fail_open->last_disconn_secs + 60) {
1427 VLOG_WARN("Still in fail-open mode after %d seconds disconnected "
1428 "from controller", disconn_secs);
1429 fail_open->last_disconn_secs = disconn_secs;
1434 fail_open_local_packet_cb(struct relay *r, void *fail_open_)
1436 struct fail_open_data *fail_open = fail_open_;
1437 if (!fail_open->lswitch) {
1440 lswitch_process_packet(fail_open->lswitch, fail_open->local_rconn,
1441 r->halves[HALF_LOCAL].rxbuf);
1442 rconn_run(fail_open->local_rconn);
1448 fail_open_status_cb(struct status_reply *sr, void *fail_open_)
1450 struct fail_open_data *fail_open = fail_open_;
1451 const struct settings *s = fail_open->s;
1452 int trigger_duration = s->probe_interval * 3;
1453 int cur_duration = rconn_disconnected_duration(fail_open->remote_rconn);
1455 status_reply_put(sr, "trigger-duration=%d", trigger_duration);
1456 status_reply_put(sr, "current-duration=%d", cur_duration);
1457 status_reply_put(sr, "triggered=%s",
1458 cur_duration >= trigger_duration ? "true" : "false");
1459 status_reply_put(sr, "max-idle=%d", s->max_idle);
1463 fail_open_hook_create(const struct settings *s, struct switch_status *ss,
1464 struct rconn *local_rconn, struct rconn *remote_rconn)
1466 struct fail_open_data *fail_open = xmalloc(sizeof *fail_open);
1468 fail_open->local_rconn = local_rconn;
1469 fail_open->remote_rconn = remote_rconn;
1470 fail_open->lswitch = NULL;
1471 fail_open->boot_deadline = time_now() + s->probe_interval * 3;
1472 if (s->enable_stp) {
1473 fail_open->boot_deadline += STP_EXTRA_BOOT_TIME;
1475 switch_status_register_category(ss, "fail-open",
1476 fail_open_status_cb, fail_open);
1477 return make_hook(fail_open_local_packet_cb, NULL,
1478 fail_open_periodic_cb, NULL, fail_open);
1481 struct rate_limiter {
1482 const struct settings *s;
1483 struct rconn *remote_rconn;
1485 /* One queue per physical port. */
1486 struct ofp_queue queues[OFPP_MAX];
1487 int n_queued; /* Sum over queues[*].n. */
1488 int next_tx_port; /* Next port to check in round-robin. */
1492 * It costs 1000 tokens to send a single packet_in message. A single token
1493 * per message would be more straightforward, but this choice lets us avoid
1494 * round-off error in refill_bucket()'s calculation of how many tokens to
1495 * add to the bucket, since no division step is needed. */
1496 long long int last_fill; /* Time at which we last added tokens. */
1497 int tokens; /* Current number of tokens. */
1499 /* Transmission queue. */
1500 int n_txq; /* No. of packets waiting in rconn for tx. */
1502 /* Statistics reporting. */
1503 unsigned long long n_normal; /* # txed w/o rate limit queuing. */
1504 unsigned long long n_limited; /* # queued for rate limiting. */
1505 unsigned long long n_queue_dropped; /* # dropped due to queue overflow. */
1506 unsigned long long n_tx_dropped; /* # dropped due to tx overflow. */
1509 /* Drop a packet from the longest queue in 'rl'. */
1511 drop_packet(struct rate_limiter *rl)
1513 struct ofp_queue *longest; /* Queue currently selected as longest. */
1514 int n_longest; /* # of queues of same length as 'longest'. */
1515 struct ofp_queue *q;
1517 longest = &rl->queues[0];
1519 for (q = &rl->queues[0]; q < &rl->queues[OFPP_MAX]; q++) {
1520 if (longest->n < q->n) {
1523 } else if (longest->n == q->n) {
1526 /* Randomly select one of the longest queues, with a uniform
1527 * distribution (Knuth algorithm 3.4.2R). */
1528 if (!random_range(n_longest)) {
1534 /* FIXME: do we want to pop the tail instead? */
1535 ofpbuf_delete(queue_pop_head(longest));
1539 /* Remove and return the next packet to transmit (in round-robin order). */
1540 static struct ofpbuf *
1541 dequeue_packet(struct rate_limiter *rl)
1545 for (i = 0; i < OFPP_MAX; i++) {
1546 unsigned int port = (rl->next_tx_port + i) % OFPP_MAX;
1547 struct ofp_queue *q = &rl->queues[port];
1549 rl->next_tx_port = (port + 1) % OFPP_MAX;
1551 return queue_pop_head(q);
1557 /* Add tokens to the bucket based on elapsed time. */
1559 refill_bucket(struct rate_limiter *rl)
1561 const struct settings *s = rl->s;
1562 long long int now = time_msec();
1563 long long int tokens = (now - rl->last_fill) * s->rate_limit + rl->tokens;
1564 if (tokens >= 1000) {
1565 rl->last_fill = now;
1566 rl->tokens = MIN(tokens, s->burst_limit * 1000);
1570 /* Attempts to remove enough tokens from 'rl' to transmit a packet. Returns
1571 * true if successful, false otherwise. (In the latter case no tokens are
1574 get_token(struct rate_limiter *rl)
1576 if (rl->tokens >= 1000) {
1585 rate_limit_local_packet_cb(struct relay *r, void *rl_)
1587 struct rate_limiter *rl = rl_;
1588 const struct settings *s = rl->s;
1589 struct ofp_packet_in *opi;
1591 opi = get_ofp_packet_in(r);
1596 if (!rl->n_queued && get_token(rl)) {
1597 /* In the common case where we are not constrained by the rate limit,
1598 * let the packet take the normal path. */
1602 /* Otherwise queue it up for the periodic callback to drain out. */
1603 struct ofpbuf *msg = r->halves[HALF_LOCAL].rxbuf;
1604 int port = ntohs(opi->in_port) % OFPP_MAX;
1605 if (rl->n_queued >= s->burst_limit) {
1608 queue_push_tail(&rl->queues[port], ofpbuf_clone(msg));
1616 rate_limit_status_cb(struct status_reply *sr, void *rl_)
1618 struct rate_limiter *rl = rl_;
1620 status_reply_put(sr, "normal=%llu", rl->n_normal);
1621 status_reply_put(sr, "limited=%llu", rl->n_limited);
1622 status_reply_put(sr, "queue-dropped=%llu", rl->n_queue_dropped);
1623 status_reply_put(sr, "tx-dropped=%llu", rl->n_tx_dropped);
1627 rate_limit_periodic_cb(void *rl_)
1629 struct rate_limiter *rl = rl_;
1632 /* Drain some packets out of the bucket if possible, but limit the number
1633 * of iterations to allow other code to get work done too. */
1635 for (i = 0; rl->n_queued && get_token(rl) && i < 50; i++) {
1636 /* Use a small, arbitrary limit for the amount of queuing to do here,
1637 * because the TCP connection is responsible for buffering and there is
1638 * no point in trying to transmit faster than the TCP connection can
1640 struct ofpbuf *b = dequeue_packet(rl);
1641 if (rconn_send_with_limit(rl->remote_rconn, b, &rl->n_txq, 10)) {
1648 rate_limit_wait_cb(void *rl_)
1650 struct rate_limiter *rl = rl_;
1652 if (rl->tokens >= 1000) {
1653 /* We can transmit more packets as soon as we're called again. */
1654 poll_immediate_wake();
1656 /* We have to wait for the bucket to re-fill. We could calculate
1657 * the exact amount of time here for increased smoothness. */
1658 poll_timer_wait(TIME_UPDATE_INTERVAL / 2);
1664 rate_limit_hook_create(const struct settings *s, struct switch_status *ss,
1665 struct rconn *local, struct rconn *remote)
1667 struct rate_limiter *rl;
1670 rl = xcalloc(1, sizeof *rl);
1672 rl->remote_rconn = remote;
1673 for (i = 0; i < ARRAY_SIZE(rl->queues); i++) {
1674 queue_init(&rl->queues[i]);
1676 rl->last_fill = time_msec();
1677 rl->tokens = s->rate_limit * 100;
1678 switch_status_register_category(ss, "rate-limit",
1679 rate_limit_status_cb, rl);
1680 return make_hook(rate_limit_local_packet_cb, NULL, rate_limit_periodic_cb,
1681 rate_limit_wait_cb, rl);
1684 /* OFPST_SWITCH statistics. */
1686 struct switch_status_category {
1688 void (*cb)(struct status_reply *, void *aux);
1692 struct switch_status {
1693 const struct settings *s;
1695 struct switch_status_category categories[8];
1699 struct status_reply {
1700 struct switch_status_category *category;
1706 switch_status_remote_packet_cb(struct relay *r, void *ss_)
1708 struct switch_status *ss = ss_;
1709 struct rconn *rc = r->halves[HALF_REMOTE].rconn;
1710 struct ofpbuf *msg = r->halves[HALF_REMOTE].rxbuf;
1711 struct switch_status_category *c;
1712 struct nicira_header *request;
1713 struct nicira_header *reply;
1714 struct status_reply sr;
1718 if (msg->size < sizeof(struct nicira_header)) {
1721 request = msg->data;
1722 if (request->header.type != OFPT_VENDOR
1723 || request->vendor_id != htonl(NX_VENDOR_ID)
1724 || request->subtype != htonl(NXT_STATUS_REQUEST)) {
1728 sr.request.string = (void *) (request + 1);
1729 sr.request.length = msg->size - sizeof *request;
1730 ds_init(&sr.output);
1731 for (c = ss->categories; c < &ss->categories[ss->n_categories]; c++) {
1732 if (!memcmp(c->name, sr.request.string,
1733 MIN(strlen(c->name), sr.request.length))) {
1738 reply = make_openflow_xid(sizeof *reply + sr.output.length,
1739 OFPT_VENDOR, request->header.xid, &b);
1740 reply->vendor_id = htonl(NX_VENDOR_ID);
1741 reply->subtype = htonl(NXT_STATUS_REPLY);
1742 memcpy(reply + 1, sr.output.string, sr.output.length);
1743 retval = rconn_send(rc, b, NULL);
1744 if (retval && retval != EAGAIN) {
1745 VLOG_WARN("send failed (%s)", strerror(retval));
1747 ds_destroy(&sr.output);
1752 rconn_status_cb(struct status_reply *sr, void *rconn_)
1754 struct rconn *rconn = rconn_;
1755 time_t now = time_now();
1757 status_reply_put(sr, "name=%s", rconn_get_name(rconn));
1758 status_reply_put(sr, "state=%s", rconn_get_state(rconn));
1759 status_reply_put(sr, "backoff=%d", rconn_get_backoff(rconn));
1760 status_reply_put(sr, "is-connected=%s",
1761 rconn_is_connected(rconn) ? "true" : "false");
1762 status_reply_put(sr, "sent-msgs=%u", rconn_packets_sent(rconn));
1763 status_reply_put(sr, "received-msgs=%u", rconn_packets_received(rconn));
1764 status_reply_put(sr, "attempted-connections=%u",
1765 rconn_get_attempted_connections(rconn));
1766 status_reply_put(sr, "successful-connections=%u",
1767 rconn_get_successful_connections(rconn));
1768 status_reply_put(sr, "last-connection=%ld",
1769 (long int) (now - rconn_get_last_connection(rconn)));
1770 status_reply_put(sr, "time-connected=%lu",
1771 rconn_get_total_time_connected(rconn));
1772 status_reply_put(sr, "state-elapsed=%u", rconn_get_state_elapsed(rconn));
1776 config_status_cb(struct status_reply *sr, void *s_)
1778 const struct settings *s = s_;
1781 for (i = 0; i < s->n_listeners; i++) {
1782 status_reply_put(sr, "management%zu=%s", i, s->listener_names[i]);
1784 if (s->probe_interval) {
1785 status_reply_put(sr, "probe-interval=%d", s->probe_interval);
1787 if (s->max_backoff) {
1788 status_reply_put(sr, "max-backoff=%d", s->max_backoff);
1793 switch_status_cb(struct status_reply *sr, void *ss_)
1795 struct switch_status *ss = ss_;
1796 time_t now = time_now();
1798 status_reply_put(sr, "now=%ld", (long int) now);
1799 status_reply_put(sr, "uptime=%ld", (long int) (now - ss->booted));
1800 status_reply_put(sr, "pid=%ld", (long int) getpid());
1804 switch_status_hook_create(const struct settings *s, struct switch_status **ssp)
1806 struct switch_status *ss = xcalloc(1, sizeof *ss);
1808 ss->booted = time_now();
1809 switch_status_register_category(ss, "config",
1810 config_status_cb, (void *) s);
1811 switch_status_register_category(ss, "switch", switch_status_cb, ss);
1813 return make_hook(NULL, switch_status_remote_packet_cb, NULL, NULL, ss);
1817 switch_status_register_category(struct switch_status *ss,
1818 const char *category,
1819 void (*cb)(struct status_reply *,
1823 struct switch_status_category *c;
1824 assert(ss->n_categories < ARRAY_SIZE(ss->categories));
1825 c = &ss->categories[ss->n_categories++];
1828 c->name = xstrdup(category);
1832 status_reply_put(struct status_reply *sr, const char *content, ...)
1834 size_t old_length = sr->output.length;
1838 /* Append the status reply to the output. */
1839 ds_put_format(&sr->output, "%s.", sr->category->name);
1840 va_start(args, content);
1841 ds_put_format_valist(&sr->output, content, args);
1843 if (ds_last(&sr->output) != '\n') {
1844 ds_put_char(&sr->output, '\n');
1847 /* Drop what we just added if it doesn't match the request. */
1848 added = sr->output.length - old_length;
1849 if (added < sr->request.length
1850 || memcmp(&sr->output.string[old_length],
1851 sr->request.string, sr->request.length)) {
1852 ds_truncate(&sr->output, old_length);
1857 /* Controller discovery. */
1861 const struct settings *s;
1862 struct dhclient *dhcp;
1867 discovery_status_cb(struct status_reply *sr, void *d_)
1869 struct discovery *d = d_;
1871 status_reply_put(sr, "accept-remote=%s", d->s->accept_controller_re);
1872 status_reply_put(sr, "n-changes=%d", d->n_changes);
1873 status_reply_put(sr, "state=%s", dhclient_get_state(d->dhcp));
1874 status_reply_put(sr, "state-elapsed=%u",
1875 dhclient_get_state_elapsed(d->dhcp));
1876 if (dhclient_is_bound(d->dhcp)) {
1877 uint32_t ip = dhclient_get_ip(d->dhcp);
1878 uint32_t netmask = dhclient_get_netmask(d->dhcp);
1879 uint32_t router = dhclient_get_router(d->dhcp);
1881 const struct dhcp_msg *cfg = dhclient_get_config(d->dhcp);
1882 uint32_t dns_server;
1886 status_reply_put(sr, "ip="IP_FMT, IP_ARGS(&ip));
1887 status_reply_put(sr, "netmask="IP_FMT, IP_ARGS(&netmask));
1889 status_reply_put(sr, "router="IP_FMT, IP_ARGS(&router));
1892 for (i = 0; dhcp_msg_get_ip(cfg, DHCP_CODE_DNS_SERVER, i, &dns_server);
1894 status_reply_put(sr, "dns%d="IP_FMT, i, IP_ARGS(&dns_server));
1897 domain_name = dhcp_msg_get_string(cfg, DHCP_CODE_DOMAIN_NAME);
1899 status_reply_put(sr, "domain=%s", domain_name);
1903 status_reply_put(sr, "lease-remaining=%u",
1904 dhclient_get_lease_remaining(d->dhcp));
1908 static struct discovery *
1909 discovery_init(const struct settings *s, struct switch_status *ss)
1911 struct netdev *netdev;
1912 struct discovery *d;
1913 struct dhclient *dhcp;
1916 /* Bring ofX network device up. */
1917 retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
1919 ofp_fatal(retval, "Could not open %s device", s->of_name);
1921 retval = netdev_turn_flags_on(netdev, NETDEV_UP, true);
1923 ofp_fatal(retval, "Could not bring %s device up", s->of_name);
1925 netdev_close(netdev);
1927 /* Initialize DHCP client. */
1928 retval = dhclient_create(s->of_name, modify_dhcp_request,
1929 validate_dhcp_offer, (void *) s, &dhcp);
1931 ofp_fatal(retval, "Failed to initialize DHCP client");
1933 dhclient_init(dhcp, 0);
1935 d = xmalloc(sizeof *d);
1940 switch_status_register_category(ss, "discovery", discovery_status_cb, d);
1946 discovery_question_connectivity(struct discovery *d)
1948 dhclient_force_renew(d->dhcp, 15);
1952 discovery_run(struct discovery *d, char **controller_name)
1954 dhclient_run(d->dhcp);
1955 if (!dhclient_changed(d->dhcp)) {
1959 dhclient_configure_netdev(d->dhcp);
1960 if (d->s->update_resolv_conf) {
1961 dhclient_update_resolv_conf(d->dhcp);
1964 if (dhclient_is_bound(d->dhcp)) {
1965 *controller_name = dhcp_msg_get_string(dhclient_get_config(d->dhcp),
1966 DHCP_CODE_OFP_CONTROLLER_VCONN);
1967 VLOG_WARN("%s: discovered controller", *controller_name);
1970 *controller_name = NULL;
1972 VLOG_WARN("discovered controller no longer available");
1980 discovery_wait(struct discovery *d)
1982 dhclient_wait(d->dhcp);
1986 modify_dhcp_request(struct dhcp_msg *msg, void *aux)
1988 dhcp_msg_put_string(msg, DHCP_CODE_VENDOR_CLASS, "OpenFlow");
1992 validate_dhcp_offer(const struct dhcp_msg *msg, void *s_)
1994 const struct settings *s = s_;
1998 vconn_name = dhcp_msg_get_string(msg, DHCP_CODE_OFP_CONTROLLER_VCONN);
2000 VLOG_WARN_RL(&vrl, "rejecting DHCP offer missing controller vconn");
2003 accept = !regexec(&s->accept_controller_regex, vconn_name, 0, NULL, 0);
2005 VLOG_WARN_RL(&vrl, "rejecting controller vconn that fails to match %s",
2006 s->accept_controller_re);
2012 /* User interface. */
2015 parse_options(int argc, char *argv[], struct settings *s)
2018 OPT_ACCEPT_VCONN = UCHAR_MAX + 1,
2020 OPT_INACTIVITY_PROBE,
2025 OPT_BOOTSTRAP_CA_CERT,
2028 static struct option long_options[] = {
2029 {"accept-vconn", required_argument, 0, OPT_ACCEPT_VCONN},
2030 {"no-resolv-conf", no_argument, 0, OPT_NO_RESOLV_CONF},
2031 {"fail", required_argument, 0, 'F'},
2032 {"inactivity-probe", required_argument, 0, OPT_INACTIVITY_PROBE},
2033 {"max-idle", required_argument, 0, OPT_MAX_IDLE},
2034 {"max-backoff", required_argument, 0, OPT_MAX_BACKOFF},
2035 {"listen", required_argument, 0, 'l'},
2036 {"monitor", required_argument, 0, 'm'},
2037 {"rate-limit", optional_argument, 0, OPT_RATE_LIMIT},
2038 {"burst-limit", required_argument, 0, OPT_BURST_LIMIT},
2039 {"no-stp", no_argument, 0, OPT_NO_STP},
2040 {"detach", no_argument, 0, 'D'},
2041 {"force", no_argument, 0, 'f'},
2042 {"pidfile", optional_argument, 0, 'P'},
2043 {"verbose", optional_argument, 0, 'v'},
2044 {"help", no_argument, 0, 'h'},
2045 {"version", no_argument, 0, 'V'},
2047 VCONN_SSL_LONG_OPTIONS
2048 {"bootstrap-ca-cert", required_argument, 0, OPT_BOOTSTRAP_CA_CERT},
2052 char *short_options = long_options_to_short_options(long_options);
2053 char *accept_re = NULL;
2056 /* Set defaults that we can figure out before parsing options. */
2058 s->monitor_name = NULL;
2059 s->fail_mode = FAIL_OPEN;
2061 s->probe_interval = 15;
2062 s->max_backoff = 15;
2063 s->update_resolv_conf = true;
2066 s->enable_stp = true;
2070 c = getopt_long(argc, argv, short_options, long_options, NULL);
2076 case OPT_ACCEPT_VCONN:
2077 accept_re = optarg[0] == '^' ? optarg : xasprintf("^%s", optarg);
2080 case OPT_NO_RESOLV_CONF:
2081 s->update_resolv_conf = false;
2085 if (!strcmp(optarg, "open")) {
2086 s->fail_mode = FAIL_OPEN;
2087 } else if (!strcmp(optarg, "closed")) {
2088 s->fail_mode = FAIL_CLOSED;
2090 ofp_fatal(0, "-f or --fail argument must be \"open\" "
2095 case OPT_INACTIVITY_PROBE:
2096 s->probe_interval = atoi(optarg);
2097 if (s->probe_interval < 5) {
2098 ofp_fatal(0, "--inactivity-probe argument must be at least 5");
2103 if (!strcmp(optarg, "permanent")) {
2104 s->max_idle = OFP_FLOW_PERMANENT;
2106 s->max_idle = atoi(optarg);
2107 if (s->max_idle < 1 || s->max_idle > 65535) {
2108 ofp_fatal(0, "--max-idle argument must be between 1 and "
2109 "65535 or the word 'permanent'");
2114 case OPT_MAX_BACKOFF:
2115 s->max_backoff = atoi(optarg);
2116 if (s->max_backoff < 1) {
2117 ofp_fatal(0, "--max-backoff argument must be at least 1");
2118 } else if (s->max_backoff > 3600) {
2119 s->max_backoff = 3600;
2123 case OPT_RATE_LIMIT:
2125 s->rate_limit = atoi(optarg);
2126 if (s->rate_limit < 1) {
2127 ofp_fatal(0, "--rate-limit argument must be at least 1");
2130 s->rate_limit = 1000;
2134 case OPT_BURST_LIMIT:
2135 s->burst_limit = atoi(optarg);
2136 if (s->burst_limit < 1) {
2137 ofp_fatal(0, "--burst-limit argument must be at least 1");
2142 s->enable_stp = false;
2150 set_pidfile(optarg);
2154 ignore_existing_pidfile();
2158 if (s->n_listeners >= MAX_MGMT) {
2160 "-l or --listen may be specified at most %d times",
2163 s->listener_names[s->n_listeners++] = optarg;
2167 if (s->monitor_name) {
2168 ofp_fatal(0, "-m or --monitor may only be specified once");
2170 s->monitor_name = optarg;
2177 printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
2181 vlog_set_verbosity(optarg);
2185 VCONN_SSL_OPTION_HANDLERS
2187 case OPT_BOOTSTRAP_CA_CERT:
2188 vconn_ssl_set_ca_cert_file(optarg, true);
2199 free(short_options);
2203 if (argc < 1 || argc > 2) {
2204 ofp_fatal(0, "need one or two non-option arguments; "
2205 "use --help for usage");
2208 /* Local and remote vconns. */
2209 s->nl_name = argv[0];
2210 if (strncmp(s->nl_name, "nl:", 3)
2211 || strlen(s->nl_name) < 4
2212 || s->nl_name[strspn(s->nl_name + 3, "0123456789") + 3]) {
2213 ofp_fatal(0, "%s: argument is not of the form \"nl:DP_IDX\"",
2216 s->of_name = xasprintf("of%s", s->nl_name + 3);
2217 s->controller_name = argc > 1 ? xstrdup(argv[1]) : NULL;
2219 /* Set accept_controller_regex. */
2221 accept_re = vconn_ssl_is_configured() ? "^ssl:.*" : ".*";
2223 retval = regcomp(&s->accept_controller_regex, accept_re,
2224 REG_NOSUB | REG_EXTENDED);
2226 size_t length = regerror(retval, &s->accept_controller_regex, NULL, 0);
2227 char *buffer = xmalloc(length);
2228 regerror(retval, &s->accept_controller_regex, buffer, length);
2229 ofp_fatal(0, "%s: %s", accept_re, buffer);
2231 s->accept_controller_re = accept_re;
2233 /* Mode of operation. */
2234 s->discovery = s->controller_name == NULL;
2238 enum netdev_flags flags;
2239 struct netdev *netdev;
2241 retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
2243 ofp_fatal(retval, "Could not open %s device", s->of_name);
2246 retval = netdev_get_flags(netdev, &flags);
2248 ofp_fatal(retval, "Could not get flags for %s device", s->of_name);
2251 s->in_band = (flags & NETDEV_UP) != 0;
2252 if (s->in_band && netdev_get_in6(netdev, NULL)) {
2253 VLOG_WARN("Ignoring IPv6 address on %s device: IPv6 not supported",
2257 netdev_close(netdev);
2260 /* Rate limiting. */
2261 if (s->rate_limit) {
2262 if (s->rate_limit < 100) {
2263 VLOG_WARN("Rate limit set to unusually low value %d",
2266 if (!s->burst_limit) {
2267 s->burst_limit = s->rate_limit / 4;
2269 s->burst_limit = MAX(s->burst_limit, 1);
2270 s->burst_limit = MIN(s->burst_limit, INT_MAX / 1000);
2277 printf("%s: secure channel, a relay for OpenFlow messages.\n"
2278 "usage: %s [OPTIONS] nl:DP_IDX [CONTROLLER]\n"
2279 "where nl:DP_IDX is a datapath that has been added with dpctl.\n"
2280 "CONTROLLER is an active OpenFlow connection method; if it is\n"
2281 "omitted, then secchan performs controller discovery.\n",
2282 program_name, program_name);
2283 vconn_usage(true, true, true);
2284 printf("\nController discovery options:\n"
2285 " --accept-vconn=REGEX accept matching discovered controllers\n"
2286 " --no-resolv-conf do not update /etc/resolv.conf\n"
2287 "\nNetworking options:\n"
2288 " -F, --fail=open|closed when controller connection fails:\n"
2289 " closed: drop all packets\n"
2290 " open (default): act as learning switch\n"
2291 " --inactivity-probe=SECS time between inactivity probes\n"
2292 " --max-idle=SECS max idle for flows set up by secchan\n"
2293 " --max-backoff=SECS max time between controller connection\n"
2294 " attempts (default: 15 seconds)\n"
2295 " -l, --listen=METHOD allow management connections on METHOD\n"
2296 " (a passive OpenFlow connection method)\n"
2297 " -m, --monitor=METHOD copy traffic to/from kernel to METHOD\n"
2298 " (a passive OpenFlow connection method)\n"
2299 " --no-stp disable 802.1D Spanning Tree Protocol\n"
2300 "\nRate-limiting of \"packet-in\" messages to the controller:\n"
2301 " --rate-limit[=PACKETS] max rate, in packets/s (default: 1000)\n"
2302 " --burst-limit=BURST limit on packet credit for idle time\n"
2303 "\nOther options:\n"
2304 " -D, --detach run in background as daemon\n"
2305 " -P, --pidfile[=FILE] create pidfile (default: %s/secchan.pid)\n"
2306 " -f, --force with -P, start even if already running\n"
2307 " -v, --verbose=MODULE[:FACILITY[:LEVEL]] set logging levels\n"
2308 " -v, --verbose set maximum verbosity level\n"
2309 " -h, --help display this help message\n"
2310 " -V, --version display version information\n",