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"
65 #include "port-array.h"
70 #include "vconn-ssl.h"
72 #include "vlog-socket.h"
76 #define THIS_MODULE VLM_secchan
78 /* Behavior when the connection to the controller fails. */
80 FAIL_OPEN, /* Act as learning switch. */
81 FAIL_CLOSED /* Drop all packets. */
84 /* Maximum number of management connection listeners. */
87 /* Settings that may be configured by the user. */
89 /* Overall mode of operation. */
90 bool discovery; /* Discover the controller automatically? */
91 bool in_band; /* Connect to controller in-band? */
93 /* Related vconns and network devices. */
94 const char *dp_name; /* Local datapath. */
95 const char *controller_name; /* Controller (if not discovery mode). */
96 const char *listener_names[MAX_MGMT]; /* Listen for mgmt connections. */
97 size_t n_listeners; /* Number of mgmt connection listeners. */
98 const char *monitor_name; /* Listen for traffic monitor connections. */
100 /* Failure behavior. */
101 enum fail_mode fail_mode; /* Act as learning switch if no controller? */
102 int max_idle; /* Idle time for flows in fail-open mode. */
103 int probe_interval; /* # seconds idle before sending echo request. */
104 int max_backoff; /* Max # seconds between connection attempts. */
106 /* Packet-in rate-limiting. */
107 int rate_limit; /* Tokens added to bucket per second. */
108 int burst_limit; /* Maximum number token bucket size. */
110 /* Discovery behavior. */
111 regex_t accept_controller_regex; /* Controller vconns to accept. */
112 const char *accept_controller_re; /* String version of regex. */
113 bool update_resolv_conf; /* Update /etc/resolv.conf? */
115 /* Spanning tree protocol. */
121 struct ofpbuf *rxbuf;
122 int n_txq; /* No. of packets queued for tx on 'rconn'. */
129 #define HALF_REMOTE 1
130 struct half halves[2];
136 bool (*packet_cb[2])(struct relay *, void *aux);
137 void (*periodic_cb)(void *aux);
138 void (*wait_cb)(void *aux);
142 static struct vlog_rate_limit vrl = VLOG_RATE_LIMIT_INIT(60, 60);
144 static void parse_options(int argc, char *argv[], struct settings *);
145 static void usage(void) NO_RETURN;
147 static struct pvconn *open_passive_vconn(const char *name);
148 static struct vconn *accept_vconn(struct pvconn *pvconn);
150 static struct relay *relay_create(struct rconn *local, struct rconn *remote,
152 static struct relay *relay_accept(const struct settings *, struct pvconn *);
153 static void relay_run(struct relay *, const struct hook[], size_t n_hooks);
154 static void relay_wait(struct relay *);
155 static void relay_destroy(struct relay *);
157 static struct hook make_hook(bool (*local_packet_cb)(struct relay *, void *),
158 bool (*remote_packet_cb)(struct relay *, void *),
159 void (*periodic_cb)(void *),
160 void (*wait_cb)(void *),
162 static struct ofp_packet_in *get_ofp_packet_in(struct relay *);
163 static bool get_ofp_packet_eth_header(struct relay *, struct ofp_packet_in **,
164 struct eth_header **);
165 static void get_ofp_packet_payload(struct ofp_packet_in *, struct ofpbuf *);
167 struct switch_status;
169 static struct hook switch_status_hook_create(const struct settings *,
170 struct switch_status **);
171 static void switch_status_register_category(struct switch_status *,
172 const char *category,
173 void (*cb)(struct status_reply *,
176 static void status_reply_put(struct status_reply *, const char *, ...)
179 static void rconn_status_cb(struct status_reply *, void *rconn_);
182 static struct discovery *discovery_init(const struct settings *,
183 struct port_watcher *,
184 struct switch_status *);
185 static void discovery_question_connectivity(struct discovery *);
186 static bool discovery_run(struct discovery *, char **controller_name);
187 static void discovery_wait(struct discovery *);
189 static struct hook in_band_hook_create(const struct settings *,
190 struct switch_status *,
191 struct port_watcher *,
192 struct rconn *remote);
194 static struct hook port_watcher_create(struct rconn *local,
195 struct rconn *remote,
196 struct port_watcher **);
197 static uint32_t port_watcher_get_config(const struct port_watcher *,
199 static const char *port_watcher_get_name(const struct port_watcher *,
200 uint16_t port_no) UNUSED;
201 static const uint8_t *port_watcher_get_hwaddr(const struct port_watcher *,
203 static void port_watcher_set_flags(struct port_watcher *, uint16_t port_no,
204 uint32_t config, uint32_t c_mask,
205 uint32_t state, uint32_t s_mask);
208 static struct hook snat_hook_create(struct port_watcher *pw);
211 static struct hook stp_hook_create(const struct settings *,
212 struct port_watcher *,
213 struct rconn *local, struct rconn *remote);
215 static struct hook fail_open_hook_create(const struct settings *,
216 struct switch_status *,
218 struct rconn *remote);
219 static struct hook rate_limit_hook_create(const struct settings *,
220 struct switch_status *,
222 struct rconn *remote);
225 static void modify_dhcp_request(struct dhcp_msg *, void *aux);
226 static bool validate_dhcp_offer(const struct dhcp_msg *, void *aux);
229 main(int argc, char *argv[])
233 struct list relays = LIST_INITIALIZER(&relays);
235 struct hook hooks[8];
238 struct pvconn *monitor;
240 struct pvconn *listeners[MAX_MGMT];
243 struct rconn *local_rconn, *remote_rconn;
244 struct relay *controller_relay;
245 struct discovery *discovery;
246 struct switch_status *switch_status;
247 struct port_watcher *pw;
251 set_program_name(argv[0]);
252 register_fault_handlers();
255 parse_options(argc, argv, &s);
256 signal(SIGPIPE, SIG_IGN);
258 /* Start listening for management and monitoring connections. */
260 for (i = 0; i < s.n_listeners; i++) {
261 listeners[n_listeners++] = open_passive_vconn(s.listener_names[i]);
263 monitor = s.monitor_name ? open_passive_vconn(s.monitor_name) : NULL;
265 /* Initialize switch status hook. */
266 hooks[n_hooks++] = switch_status_hook_create(&s, &switch_status);
268 /* Start listening for vlogconf requests. */
269 retval = vlog_server_listen(NULL, NULL);
271 ofp_fatal(retval, "Could not listen for vlog connections");
274 die_if_already_running();
277 VLOG_WARN("OpenFlow reference implementation version %s", VERSION);
278 VLOG_WARN("OpenFlow protocol version 0x%02x", OFP_VERSION);
280 /* Connect to datapath. */
281 local_rconn = rconn_create(0, s.max_backoff);
282 rconn_connect(local_rconn, s.dp_name);
283 switch_status_register_category(switch_status, "local",
284 rconn_status_cb, local_rconn);
286 /* Connect to controller. */
287 remote_rconn = rconn_create(s.probe_interval, s.max_backoff);
288 if (s.controller_name) {
289 retval = rconn_connect(remote_rconn, s.controller_name);
290 if (retval == EAFNOSUPPORT) {
291 ofp_fatal(0, "No support for %s vconn", s.controller_name);
294 switch_status_register_category(switch_status, "remote",
295 rconn_status_cb, remote_rconn);
297 /* Start relaying. */
298 controller_relay = relay_create(local_rconn, remote_rconn, false);
299 list_push_back(&relays, &controller_relay->node);
302 hooks[n_hooks++] = port_watcher_create(local_rconn, remote_rconn, &pw);
303 discovery = s.discovery ? discovery_init(&s, pw, switch_status) : NULL;
305 hooks[n_hooks++] = snat_hook_create(pw);
308 hooks[n_hooks++] = stp_hook_create(&s, pw, local_rconn, remote_rconn);
311 hooks[n_hooks++] = in_band_hook_create(&s, switch_status, pw,
314 if (s.fail_mode == FAIL_OPEN) {
315 hooks[n_hooks++] = fail_open_hook_create(&s, switch_status,
316 local_rconn, remote_rconn);
319 hooks[n_hooks++] = rate_limit_hook_create(&s, switch_status,
320 local_rconn, remote_rconn);
322 assert(n_hooks <= ARRAY_SIZE(hooks));
329 LIST_FOR_EACH_SAFE (r, n, struct relay, node, &relays) {
330 relay_run(r, hooks, n_hooks);
332 for (i = 0; i < n_listeners; i++) {
334 struct relay *r = relay_accept(&s, listeners[i]);
338 list_push_back(&relays, &r->node);
342 struct vconn *new = accept_vconn(monitor);
344 rconn_add_monitor(local_rconn, new);
347 for (i = 0; i < n_hooks; i++) {
348 if (hooks[i].periodic_cb) {
349 hooks[i].periodic_cb(hooks[i].aux);
353 char *controller_name;
354 if (rconn_is_connectivity_questionable(remote_rconn)) {
355 discovery_question_connectivity(discovery);
357 if (discovery_run(discovery, &controller_name)) {
358 if (controller_name) {
359 rconn_connect(remote_rconn, controller_name);
361 rconn_disconnect(remote_rconn);
366 /* Wait for something to happen. */
367 LIST_FOR_EACH (r, struct relay, node, &relays) {
370 for (i = 0; i < n_listeners; i++) {
371 pvconn_wait(listeners[i]);
374 pvconn_wait(monitor);
376 for (i = 0; i < n_hooks; i++) {
377 if (hooks[i].wait_cb) {
378 hooks[i].wait_cb(hooks[i].aux);
382 discovery_wait(discovery);
390 static struct pvconn *
391 open_passive_vconn(const char *name)
393 struct pvconn *pvconn;
396 retval = pvconn_open(name, &pvconn);
397 if (retval && retval != EAGAIN) {
398 ofp_fatal(retval, "opening %s", name);
403 static struct vconn *
404 accept_vconn(struct pvconn *pvconn)
409 retval = pvconn_accept(pvconn, OFP_VERSION, &new);
410 if (retval && retval != EAGAIN) {
411 VLOG_WARN_RL(&vrl, "accept failed (%s)", strerror(retval));
417 make_hook(bool (*local_packet_cb)(struct relay *, void *aux),
418 bool (*remote_packet_cb)(struct relay *, void *aux),
419 void (*periodic_cb)(void *aux),
420 void (*wait_cb)(void *aux),
424 h.packet_cb[HALF_LOCAL] = local_packet_cb;
425 h.packet_cb[HALF_REMOTE] = remote_packet_cb;
426 h.periodic_cb = periodic_cb;
432 static struct ofp_packet_in *
433 get_ofp_packet_in(struct relay *r)
435 struct ofpbuf *msg = r->halves[HALF_LOCAL].rxbuf;
436 struct ofp_header *oh = msg->data;
437 if (oh->type == OFPT_PACKET_IN) {
438 if (msg->size >= offsetof (struct ofp_packet_in, data)) {
441 VLOG_WARN("packet too short (%zu bytes) for packet_in",
449 get_ofp_packet_eth_header(struct relay *r, struct ofp_packet_in **opip,
450 struct eth_header **ethp)
452 const int min_len = offsetof(struct ofp_packet_in, data) + ETH_HEADER_LEN;
453 struct ofp_packet_in *opi = get_ofp_packet_in(r);
454 if (opi && ntohs(opi->header.length) >= min_len) {
456 *ethp = (void *) opi->data;
463 /* OpenFlow message relaying. */
465 static struct relay *
466 relay_accept(const struct settings *s, struct pvconn *pvconn)
468 struct vconn *new_remote, *new_local;
469 struct rconn *r1, *r2;
474 new_remote = accept_vconn(pvconn);
479 if (sscanf(s->dp_name, "nl:%d", &nl_index) == 1) {
480 /* nl:123 or nl:123:1 opens a netlink connection to local datapath 123.
481 * nl:123:0 opens a netlink connection to local datapath 123 without
482 * obtaining a subscription for ofp_packet_in or ofp_flow_expired
483 * messages. That's what we want here; management connections should
484 * not receive those messages, at least by default. */
485 vconn_name = xasprintf("nl:%d:0", nl_index);
487 /* We don't have a way to specify not to subscribe to those messages
488 * for other transports. (That's a defect: really this should be in
489 * the OpenFlow protocol, not the Netlink transport). */
490 VLOG_WARN_RL(&vrl, "new management connection will receive "
491 "asynchronous messages");
492 vconn_name = xstrdup(s->dp_name);
495 retval = vconn_open(vconn_name, OFP_VERSION, &new_local);
497 VLOG_ERR_RL(&vrl, "could not connect to %s (%s)",
498 vconn_name, strerror(retval));
499 vconn_close(new_remote);
504 /* Create and return relay. */
505 r1 = rconn_create(0, 0);
506 rconn_connect_unreliably(r1, vconn_name, new_local);
509 r2 = rconn_create(0, 0);
510 rconn_connect_unreliably(r2, "passive", new_remote);
512 return relay_create(r1, r2, true);
515 static struct relay *
516 relay_create(struct rconn *local, struct rconn *remote, bool is_mgmt_conn)
518 struct relay *r = xcalloc(1, sizeof *r);
519 r->halves[HALF_LOCAL].rconn = local;
520 r->halves[HALF_REMOTE].rconn = remote;
521 r->is_mgmt_conn = is_mgmt_conn;
526 relay_run(struct relay *r, const struct hook hooks[], size_t n_hooks)
531 for (i = 0; i < 2; i++) {
532 rconn_run(r->halves[i].rconn);
535 /* Limit the number of iterations to prevent other tasks from starving. */
536 for (iteration = 0; iteration < 50; iteration++) {
537 bool progress = false;
538 for (i = 0; i < 2; i++) {
539 struct half *this = &r->halves[i];
540 struct half *peer = &r->halves[!i];
543 this->rxbuf = rconn_recv(this->rconn);
544 if (this->rxbuf && (i == HALF_REMOTE || !r->is_mgmt_conn)) {
545 const struct hook *h;
546 for (h = hooks; h < &hooks[n_hooks]; h++) {
547 if (h->packet_cb[i] && h->packet_cb[i](r, h->aux)) {
548 ofpbuf_delete(this->rxbuf);
557 if (this->rxbuf && !this->n_txq) {
558 int retval = rconn_send(peer->rconn, this->rxbuf,
560 if (retval != EAGAIN) {
564 ofpbuf_delete(this->rxbuf);
575 if (r->is_mgmt_conn) {
576 for (i = 0; i < 2; i++) {
577 struct half *this = &r->halves[i];
578 if (!rconn_is_alive(this->rconn)) {
587 relay_wait(struct relay *r)
591 for (i = 0; i < 2; i++) {
592 struct half *this = &r->halves[i];
594 rconn_run_wait(this->rconn);
596 rconn_recv_wait(this->rconn);
602 relay_destroy(struct relay *r)
606 list_remove(&r->node);
607 for (i = 0; i < 2; i++) {
608 struct half *this = &r->halves[i];
609 rconn_destroy(this->rconn);
610 ofpbuf_delete(this->rxbuf);
615 /* Port status watcher. */
617 typedef void port_changed_cb_func(uint16_t port_no,
618 const struct ofp_phy_port *old,
619 const struct ofp_phy_port *new,
622 struct port_watcher_cb {
623 port_changed_cb_func *port_changed;
627 typedef void local_port_changed_cb_func(const struct ofp_phy_port *new,
630 struct port_watcher_local_cb {
631 local_port_changed_cb_func *local_port_changed;
635 struct port_watcher {
636 struct rconn *local_rconn;
637 struct rconn *remote_rconn;
638 struct port_array ports;
639 time_t last_feature_request;
640 bool got_feature_reply;
641 uint64_t datapath_id;
643 struct port_watcher_cb cbs[2];
645 struct port_watcher_local_cb local_cbs[4];
647 char local_port_name[OFP_MAX_PORT_NAME_LEN + 1];
650 /* Returns the number of fields that differ from 'a' to 'b'. */
652 opp_differs(const struct ofp_phy_port *a, const struct ofp_phy_port *b)
654 BUILD_ASSERT_DECL(sizeof *a == 48); /* Trips when we add or remove fields. */
655 return ((a->port_no != b->port_no)
656 + (memcmp(a->hw_addr, b->hw_addr, sizeof a->hw_addr) != 0)
657 + (memcmp(a->name, b->name, sizeof a->name) != 0)
658 + (a->config != b->config)
659 + (a->state != b->state)
660 + (a->curr != b->curr)
661 + (a->advertised != b->advertised)
662 + (a->supported != b->supported)
663 + (a->peer != b->peer));
667 sanitize_opp(struct ofp_phy_port *opp)
671 for (i = 0; i < sizeof opp->name; i++) {
672 char c = opp->name[i];
673 if (c && (c < 0x20 || c > 0x7e)) {
677 opp->name[sizeof opp->name - 1] = '\0';
681 call_port_changed_callbacks(struct port_watcher *pw, int port_no,
682 const struct ofp_phy_port *old,
683 const struct ofp_phy_port *new)
686 for (i = 0; i < pw->n_cbs; i++) {
687 port_changed_cb_func *port_changed = pw->cbs[i].port_changed;
688 (port_changed)(port_no, old, new, pw->cbs[i].aux);
693 get_port_name(const struct ofp_phy_port *port, char *name, size_t name_size)
697 memcpy(name, port->name, MIN(name_size, sizeof port->name));
698 name[name_size - 1] = '\0';
699 for (p = name; *p != '\0'; p++) {
700 if (*p < 32 || *p > 126) {
706 static struct ofp_phy_port *
707 lookup_port(const struct port_watcher *pw, uint16_t port_no)
709 return port_array_get(&pw->ports, port_no);
713 call_local_port_changed_callbacks(struct port_watcher *pw)
715 char name[OFP_MAX_PORT_NAME_LEN + 1];
716 const struct ofp_phy_port *port;
719 /* Pass the local port to the callbacks, if it exists.
720 Pass a null pointer if there is no local port. */
721 port = lookup_port(pw, OFPP_LOCAL);
723 /* Log the name of the local port. */
725 get_port_name(port, name, sizeof name);
729 if (strcmp(pw->local_port_name, name)) {
731 VLOG_WARN("Identified data path local port as \"%s\".", name);
733 VLOG_WARN("Data path has no local port.");
735 strcpy(pw->local_port_name, name);
738 /* Invoke callbacks. */
739 for (i = 0; i < pw->n_local_cbs; i++) {
740 local_port_changed_cb_func *cb = pw->local_cbs[i].local_port_changed;
741 (cb)(port, pw->local_cbs[i].aux);
746 update_phy_port(struct port_watcher *pw, struct ofp_phy_port *opp,
749 struct ofp_phy_port *old;
752 port_no = ntohs(opp->port_no);
753 old = lookup_port(pw, port_no);
755 if (reason == OFPPR_DELETE && old) {
756 call_port_changed_callbacks(pw, port_no, old, NULL);
758 port_array_set(&pw->ports, port_no, NULL);
759 } else if ((reason == OFPPR_MODIFY || reason == OFPPR_ADD)
760 && (!old || opp_differs(opp, old))) {
761 struct ofp_phy_port new = *opp;
763 call_port_changed_callbacks(pw, port_no, old, &new);
767 port_array_set(&pw->ports, port_no, xmemdup(&new, sizeof new));
773 port_watcher_local_packet_cb(struct relay *r, void *pw_)
775 struct port_watcher *pw = pw_;
776 struct ofpbuf *msg = r->halves[HALF_LOCAL].rxbuf;
777 struct ofp_header *oh = msg->data;
779 if (oh->type == OFPT_FEATURES_REPLY
780 && msg->size >= offsetof(struct ofp_switch_features, ports)) {
781 struct ofp_switch_features *osf = msg->data;
782 bool seen[PORT_ARRAY_SIZE];
783 struct ofp_phy_port *p;
784 unsigned int port_no;
788 pw->got_feature_reply = true;
789 if (pw->datapath_id != osf->datapath_id) {
790 pw->datapath_id = osf->datapath_id;
791 VLOG_WARN("Datapath id is %012"PRIx64, ntohll(pw->datapath_id));
794 /* Update each port included in the message. */
795 memset(seen, false, sizeof seen);
796 n_ports = ((msg->size - offsetof(struct ofp_switch_features, ports))
797 / sizeof *osf->ports);
798 for (i = 0; i < n_ports; i++) {
799 struct ofp_phy_port *opp = &osf->ports[i];
800 update_phy_port(pw, opp, OFPPR_MODIFY);
801 seen[ntohs(opp->port_no)] = true;
804 /* Delete all the ports not included in the message. */
805 for (p = port_array_first(&pw->ports, &port_no); p;
806 p = port_array_next(&pw->ports, &port_no)) {
807 if (!seen[port_no]) {
808 update_phy_port(pw, p, OFPPR_DELETE);
812 call_local_port_changed_callbacks(pw);
813 } else if (oh->type == OFPT_PORT_STATUS
814 && msg->size >= sizeof(struct ofp_port_status)) {
815 struct ofp_port_status *ops = msg->data;
816 update_phy_port(pw, &ops->desc, ops->reason);
817 if (ops->desc.port_no == htons(OFPP_LOCAL)) {
818 call_local_port_changed_callbacks(pw);
825 port_watcher_remote_packet_cb(struct relay *r, void *pw_)
827 struct port_watcher *pw = pw_;
828 struct ofpbuf *msg = r->halves[HALF_REMOTE].rxbuf;
829 struct ofp_header *oh = msg->data;
831 if (oh->type == OFPT_PORT_MOD
832 && msg->size >= sizeof(struct ofp_port_mod)) {
833 struct ofp_port_mod *opm = msg->data;
834 uint16_t port_no = ntohs(opm->port_no);
835 struct ofp_phy_port *pw_opp = lookup_port(pw, port_no);
836 if (pw_opp->port_no != htons(OFPP_NONE)) {
837 struct ofp_phy_port old = *pw_opp;
838 pw_opp->config = ((pw_opp->config & ~opm->mask)
839 | (opm->config & opm->mask));
840 call_port_changed_callbacks(pw, port_no, &old, pw_opp);
841 if (pw_opp->port_no == htons(OFPP_LOCAL)) {
842 call_local_port_changed_callbacks(pw);
850 port_watcher_periodic_cb(void *pw_)
852 struct port_watcher *pw = pw_;
854 if (!pw->got_feature_reply
855 && time_now() >= pw->last_feature_request + 5
856 && rconn_is_connected(pw->local_rconn)) {
858 make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &b);
859 rconn_send_with_limit(pw->local_rconn, b, &pw->n_txq, 1);
860 pw->last_feature_request = time_now();
865 port_watcher_wait_cb(void *pw_)
867 struct port_watcher *pw = pw_;
868 if (!pw->got_feature_reply && rconn_is_connected(pw->local_rconn)) {
869 if (pw->last_feature_request != TIME_MIN) {
870 poll_timer_wait(pw->last_feature_request + 5 - time_now());
872 poll_immediate_wake();
878 put_duplexes(struct ds *ds, const char *name, uint32_t features,
879 uint32_t hd_bit, uint32_t fd_bit)
881 if (features & (hd_bit | fd_bit)) {
882 ds_put_format(ds, " %s", name);
883 if (features & hd_bit) {
884 ds_put_cstr(ds, "(HD)");
886 if (features & fd_bit) {
887 ds_put_cstr(ds, "(FD)");
893 put_features(struct ds *ds, const char *name, uint32_t features)
895 if (features & (OFPPF_10MB_HD | OFPPF_10MB_FD
896 | OFPPF_100MB_HD | OFPPF_100MB_FD
897 | OFPPF_1GB_HD | OFPPF_1GB_FD | OFPPF_10GB_FD)) {
898 ds_put_cstr(ds, name);
899 put_duplexes(ds, "10M", features, OFPPF_10MB_HD, OFPPF_10MB_FD);
900 put_duplexes(ds, "100M", features,
901 OFPPF_100MB_HD, OFPPF_100MB_FD);
902 put_duplexes(ds, "1G", features, OFPPF_100MB_HD, OFPPF_100MB_FD);
903 if (features & OFPPF_10GB_FD) {
904 ds_put_cstr(ds, " 10G");
906 if (features & OFPPF_AUTONEG) {
907 ds_put_cstr(ds, " AUTO_NEG");
909 if (features & OFPPF_PAUSE) {
910 ds_put_cstr(ds, " PAUSE");
912 if (features & OFPPF_PAUSE_ASYM) {
913 ds_put_cstr(ds, " PAUSE_ASYM");
919 log_port_status(uint16_t port_no,
920 const struct ofp_phy_port *old,
921 const struct ofp_phy_port *new,
924 if (VLOG_IS_DBG_ENABLED()) {
925 if (old && new && (opp_differs(old, new)
926 == ((old->config != new->config)
927 + (old->state != new->state))))
929 /* Don't care if only state or config changed. */
932 VLOG_DBG("Port %d deleted", port_no);
935 struct ds ds = DS_EMPTY_INITIALIZER;
936 uint32_t curr = ntohl(new->curr);
937 uint32_t supported = ntohl(new->supported);
938 ds_put_format(&ds, "\"%s\", "ETH_ADDR_FMT, new->name,
939 ETH_ADDR_ARGS(new->hw_addr));
941 put_features(&ds, ", current", curr);
944 put_features(&ds, ", supports", supported);
946 VLOG_DBG("Port %d %s: %s",
947 port_no, old ? "changed" : "added", ds_cstr(&ds));
954 port_watcher_register_callback(struct port_watcher *pw,
955 port_changed_cb_func *port_changed,
958 assert(pw->n_cbs < ARRAY_SIZE(pw->cbs));
959 pw->cbs[pw->n_cbs].port_changed = port_changed;
960 pw->cbs[pw->n_cbs].aux = aux;
965 port_watcher_register_local_port_callback(struct port_watcher *pw,
966 local_port_changed_cb_func *cb,
969 assert(pw->n_local_cbs < ARRAY_SIZE(pw->local_cbs));
970 pw->local_cbs[pw->n_local_cbs].local_port_changed = cb;
971 pw->local_cbs[pw->n_local_cbs].aux = aux;
976 port_watcher_get_config(const struct port_watcher *pw, uint16_t port_no)
978 struct ofp_phy_port *p = lookup_port(pw, port_no);
979 return p ? ntohl(p->config) : 0;
983 port_watcher_get_name(const struct port_watcher *pw, uint16_t port_no)
985 struct ofp_phy_port *p = lookup_port(pw, port_no);
986 return p ? (const char *) p->name : NULL;
989 static const uint8_t *
990 port_watcher_get_hwaddr(const struct port_watcher *pw, uint16_t port_no)
992 struct ofp_phy_port *p = lookup_port(pw, port_no);
993 return p ? p->hw_addr : NULL;
997 port_watcher_set_flags(struct port_watcher *pw, uint16_t port_no,
998 uint32_t config, uint32_t c_mask,
999 uint32_t state, uint32_t s_mask)
1001 struct ofp_phy_port old;
1002 struct ofp_phy_port *p;
1003 struct ofp_port_mod *opm;
1004 struct ofp_port_status *ops;
1007 p = lookup_port(pw, port_no);
1012 if (!((ntohl(p->state) ^ state) & s_mask)
1013 && (!((ntohl(p->config) ^ config) & c_mask))) {
1018 /* Update our idea of the flags. */
1019 p->config = htonl((ntohl(p->config) & ~c_mask) | (config & c_mask));
1020 p->state = htonl((ntohl(p->state) & ~s_mask) | (state & s_mask));
1021 call_port_changed_callbacks(pw, port_no, &old, p);
1023 /* Change the flags in the datapath. */
1024 opm = make_openflow(sizeof *opm, OFPT_PORT_MOD, &b);
1025 opm->port_no = p->port_no;
1026 memcpy(opm->hw_addr, p->hw_addr, OFP_ETH_ALEN);
1027 opm->config = p->config;
1028 opm->mask = htonl(c_mask);
1029 opm->advertise = htonl(0);
1030 rconn_send(pw->local_rconn, b, NULL);
1032 /* Notify the controller that the flags changed. */
1033 ops = make_openflow(sizeof *ops, OFPT_PORT_STATUS, &b);
1034 ops->reason = OFPPR_MODIFY;
1036 rconn_send(pw->remote_rconn, b, NULL);
1040 port_watcher_is_ready(const struct port_watcher *pw)
1042 return pw->got_feature_reply;
1046 port_watcher_create(struct rconn *local_rconn, struct rconn *remote_rconn,
1047 struct port_watcher **pwp)
1049 struct port_watcher *pw;
1051 pw = *pwp = xcalloc(1, sizeof *pw);
1052 pw->local_rconn = local_rconn;
1053 pw->remote_rconn = remote_rconn;
1054 pw->last_feature_request = TIME_MIN;
1055 port_array_init(&pw->ports);
1056 pw->local_port_name[0] = '\0';
1057 port_watcher_register_callback(pw, log_port_status, NULL);
1058 return make_hook(port_watcher_local_packet_cb,
1059 port_watcher_remote_packet_cb,
1060 port_watcher_periodic_cb,
1061 port_watcher_wait_cb, pw);
1065 struct snat_port_conf {
1067 struct nx_snat_config config;
1071 struct port_watcher *pw;
1072 struct list port_list;
1076 /* Source-NAT configuration monitor. */
1077 #define SNAT_CMD_LEN 1024
1079 /* Commands to configure iptables. There is no programmatic interface
1080 * to iptables from the kernel, so we're stuck making command-line calls
1082 #define SNAT_FLUSH_ALL_CMD "/sbin/iptables -t nat -F"
1083 #define SNAT_FLUSH_CHAIN_CMD "/sbin/iptables -t nat -F of-snat-%s"
1085 #define SNAT_ADD_CHAIN_CMD "/sbin/iptables -t nat -N of-snat-%s"
1086 #define SNAT_CONF_CHAIN_CMD "/sbin/iptables -t nat -A POSTROUTING -o %s -j of-snat-%s"
1088 #define SNAT_ADD_IP_CMD "/sbin/iptables -t nat -A of-snat-%s -j SNAT --to %s-%s"
1089 #define SNAT_ADD_TCP_CMD "/sbin/iptables -t nat -A of-snat-%s -j SNAT -p TCP --to %s-%s:%d-%d"
1090 #define SNAT_ADD_UDP_CMD "/sbin/iptables -t nat -A of-snat-%s -j SNAT -p UDP --to %s-%s:%d-%d"
1092 #define SNAT_UNSET_CHAIN_CMD "/sbin/iptables -t nat -D POSTROUTING -o %s -j of-snat-%s"
1093 #define SNAT_DEL_CHAIN_CMD "/sbin/iptables -t nat -X of-snat-%s"
1096 snat_add_rules(const struct nx_snat_config *sc, const uint8_t *dev_name)
1098 char command[SNAT_CMD_LEN];
1099 char ip_str_start[16];
1100 char ip_str_end[16];
1103 snprintf(ip_str_start, sizeof ip_str_start, IP_FMT,
1104 IP_ARGS(&sc->ip_addr_start));
1105 snprintf(ip_str_end, sizeof ip_str_end, IP_FMT,
1106 IP_ARGS(&sc->ip_addr_end));
1108 /* We always attempt to remove existing entries, so that we know
1109 * there's a pristine state for SNAT on the interface. We just ignore
1110 * the results of these calls, since iptables will complain about
1111 * any non-existent entries. */
1113 /* Flush the chain that does the SNAT. */
1114 snprintf(command, sizeof(command), SNAT_FLUSH_CHAIN_CMD, dev_name);
1117 /* We always try to create the a new chain. */
1118 snprintf(command, sizeof(command), SNAT_ADD_CHAIN_CMD, dev_name);
1121 /* Disassociate any old SNAT chain from the POSTROUTING chain. */
1122 snprintf(command, sizeof(command), SNAT_UNSET_CHAIN_CMD, dev_name,
1126 /* Associate the new chain with the POSTROUTING hook. */
1127 snprintf(command, sizeof(command), SNAT_CONF_CHAIN_CMD, dev_name,
1129 if (system(command) != 0) {
1130 VLOG_ERR("SNAT: problem flushing chain for add");
1134 /* If configured, restrict TCP source port ranges. */
1135 if ((sc->tcp_start != 0) && (sc->tcp_end != 0)) {
1136 snprintf(command, sizeof(command), SNAT_ADD_TCP_CMD,
1137 dev_name, ip_str_start, ip_str_end,
1138 ntohs(sc->tcp_start), ntohs(sc->tcp_end));
1139 if (system(command) != 0) {
1140 VLOG_ERR("SNAT: problem adding TCP rule");
1145 /* If configured, restrict UDP source port ranges. */
1146 if ((sc->udp_start != 0) && (sc->udp_end != 0)) {
1147 snprintf(command, sizeof(command), SNAT_ADD_UDP_CMD,
1148 dev_name, ip_str_start, ip_str_end,
1149 ntohs(sc->udp_start), ntohs(sc->udp_end));
1150 if (system(command) != 0) {
1151 VLOG_ERR("SNAT: problem adding UDP rule");
1156 /* Add a rule that covers all IP traffic that would not be covered
1157 * by the prior TCP or UDP ranges. */
1158 snprintf(command, sizeof(command), SNAT_ADD_IP_CMD,
1159 dev_name, ip_str_start, ip_str_end);
1160 if (system(command) != 0) {
1161 VLOG_ERR("SNAT: problem adding base rule");
1167 snat_del_rules(const uint8_t *dev_name)
1169 char command[SNAT_CMD_LEN];
1171 /* Flush the chain that does the SNAT. */
1172 snprintf(command, sizeof(command), SNAT_FLUSH_CHAIN_CMD, dev_name);
1173 if (system(command) != 0) {
1174 VLOG_ERR("SNAT: problem flushing chain for deletion");
1178 /* Disassociate the SNAT chain from the POSTROUTING chain. */
1179 snprintf(command, sizeof(command), SNAT_UNSET_CHAIN_CMD, dev_name,
1181 if (system(command) != 0) {
1182 VLOG_ERR("SNAT: problem unsetting chain");
1186 /* Now we can finally delete our SNAT chain. */
1187 snprintf(command, sizeof(command), SNAT_DEL_CHAIN_CMD, dev_name);
1188 if (system(command) != 0) {
1189 VLOG_ERR("SNAT: problem deleting chain");
1195 snat_config(const struct nx_snat_config *sc, struct snat_data *snat)
1197 struct snat_port_conf *c, *spc=NULL;
1198 const uint8_t *netdev_name;
1200 netdev_name = (const uint8_t *) port_watcher_get_name(snat->pw,
1206 LIST_FOR_EACH(c, struct snat_port_conf, node, &snat->port_list) {
1207 if (c->config.port == sc->port) {
1213 if (sc->command == NXSC_ADD) {
1215 spc = xmalloc(sizeof(*c));
1217 VLOG_ERR("SNAT: no memory for new entry");
1220 list_push_back(&snat->port_list, &spc->node);
1222 memcpy(&spc->config, sc, sizeof(spc->config));
1223 snat_add_rules(sc, netdev_name);
1225 snat_del_rules(netdev_name);
1226 list_remove(&spc->node);
1231 snat_remote_packet_cb(struct relay *r, void *snat_)
1233 struct snat_data *snat = snat_;
1234 struct ofpbuf *msg = r->halves[HALF_REMOTE].rxbuf;
1235 struct nicira_header *request = msg->data;
1236 struct nx_act_config *nac = msg->data;
1240 if (msg->size < sizeof(struct nx_act_config)) {
1243 request = msg->data;
1244 if (request->header.type != OFPT_VENDOR
1245 || request->vendor != htonl(NX_VENDOR_ID)
1246 || request->subtype != htonl(NXT_ACT_SET_CONFIG)) {
1250 /* We're only interested in attempts to configure SNAT */
1251 if (nac->type != htons(NXAST_SNAT)) {
1255 n_configs = (msg->size - sizeof *nac) / sizeof *nac->snat;
1256 for (i=0; i<n_configs; i++) {
1257 snat_config(&nac->snat[i], snat);
1264 snat_port_changed_cb(uint16_t port_no,
1265 const struct ofp_phy_port *old,
1266 const struct ofp_phy_port *new,
1269 struct snat_data *snat = snat_;
1270 struct snat_port_conf *c;
1272 /* We're only interested in ports that went away */
1277 LIST_FOR_EACH(c, struct snat_port_conf, node, &snat->port_list) {
1278 if (c->config.port == old->port_no) {
1279 snat_del_rules(old->name);
1280 list_remove(&c->node);
1287 snat_hook_create(struct port_watcher *pw)
1290 struct snat_data *snat;
1292 ret = system(SNAT_FLUSH_ALL_CMD);
1294 VLOG_ERR("SNAT: problem flushing tables");
1297 snat = xcalloc(1, sizeof *snat);
1299 list_init(&snat->port_list);
1301 port_watcher_register_callback(pw, snat_port_changed_cb, snat);
1302 return make_hook(NULL, snat_remote_packet_cb, NULL, NULL, snat);
1304 #endif /* SUPPORT_SNAT */
1306 /* Spanning tree protocol. */
1308 /* Extra time, in seconds, at boot before going into fail-open, to give the
1309 * spanning tree protocol time to figure out the network layout. */
1310 #define STP_EXTRA_BOOT_TIME 30
1314 struct port_watcher *pw;
1315 struct rconn *local_rconn;
1316 struct rconn *remote_rconn;
1317 long long int last_tick_256ths;
1322 stp_local_packet_cb(struct relay *r, void *stp_)
1324 struct ofpbuf *msg = r->halves[HALF_LOCAL].rxbuf;
1325 struct ofp_header *oh;
1326 struct stp_data *stp = stp_;
1327 struct ofp_packet_in *opi;
1328 struct eth_header *eth;
1329 struct llc_header *llc;
1330 struct ofpbuf payload;
1335 if (oh->type == OFPT_FEATURES_REPLY
1336 && msg->size >= offsetof(struct ofp_switch_features, ports)) {
1337 struct ofp_switch_features *osf = msg->data;
1338 osf->capabilities |= htonl(OFPC_STP);
1342 if (!get_ofp_packet_eth_header(r, &opi, ð)
1343 || !eth_addr_equals(eth->eth_dst, stp_eth_addr)) {
1347 port_no = ntohs(opi->in_port);
1348 if (port_no >= STP_MAX_PORTS) {
1349 /* STP only supports 255 ports. */
1352 if (port_watcher_get_config(stp->pw, port_no) & OFPPC_NO_STP) {
1353 /* We're not doing STP on this port. */
1357 if (opi->reason == OFPR_ACTION) {
1358 /* The controller set up a flow for this, so we won't intercept it. */
1362 get_ofp_packet_payload(opi, &payload);
1363 flow_extract(&payload, port_no, &flow);
1364 if (flow.dl_type != htons(OFP_DL_TYPE_NOT_ETH_TYPE)) {
1365 VLOG_DBG("non-LLC frame received on STP multicast address");
1368 llc = ofpbuf_at_assert(&payload, sizeof *eth, sizeof *llc);
1369 if (llc->llc_dsap != STP_LLC_DSAP) {
1370 VLOG_DBG("bad DSAP 0x%02"PRIx8" received on STP multicast address",
1375 /* Trim off padding on payload. */
1376 if (payload.size > ntohs(eth->eth_type) + ETH_HEADER_LEN) {
1377 payload.size = ntohs(eth->eth_type) + ETH_HEADER_LEN;
1379 if (ofpbuf_try_pull(&payload, ETH_HEADER_LEN + LLC_HEADER_LEN)) {
1380 struct stp_port *p = stp_get_port(stp->stp, port_no);
1381 stp_received_bpdu(p, payload.data, payload.size);
1387 static long long int
1390 return time_msec() * 256 / 1000;
1394 stp_periodic_cb(void *stp_)
1396 struct stp_data *stp = stp_;
1397 long long int now_256ths = time_256ths();
1398 long long int elapsed_256ths = now_256ths - stp->last_tick_256ths;
1401 if (!port_watcher_is_ready(stp->pw)) {
1402 /* Can't start STP until we know port flags, because port flags can
1406 if (elapsed_256ths <= 0) {
1410 stp_tick(stp->stp, MIN(INT_MAX, elapsed_256ths));
1411 stp->last_tick_256ths = now_256ths;
1413 while (stp_get_changed_port(stp->stp, &p)) {
1414 int port_no = stp_port_no(p);
1415 enum stp_state s_state = stp_port_get_state(p);
1417 if (s_state != STP_DISABLED) {
1418 VLOG_WARN("STP: Port %d entered %s state",
1419 port_no, stp_state_name(s_state));
1421 if (!(port_watcher_get_config(stp->pw, port_no) & OFPPC_NO_STP)) {
1422 uint32_t p_config = 0;
1426 p_state = OFPPS_STP_LISTEN;
1429 p_state = OFPPS_STP_LEARN;
1432 case STP_FORWARDING:
1433 p_state = OFPPS_STP_FORWARD;
1436 p_state = OFPPS_STP_BLOCK;
1439 VLOG_DBG_RL(&vrl, "STP: Port %d has bad state %x",
1441 p_state = OFPPS_STP_FORWARD;
1444 if (!stp_forward_in_state(s_state)) {
1445 p_config = OFPPC_NO_FLOOD;
1447 port_watcher_set_flags(stp->pw, port_no,
1448 p_config, OFPPC_NO_FLOOD,
1449 p_state, OFPPS_STP_MASK);
1451 /* We don't own those flags. */
1457 stp_wait_cb(void *stp_ UNUSED)
1459 poll_timer_wait(1000);
1463 send_bpdu(const void *bpdu, size_t bpdu_size, int port_no, void *stp_)
1465 struct stp_data *stp = stp_;
1466 const uint8_t *port_mac;
1467 struct eth_header *eth;
1468 struct llc_header *llc;
1469 struct ofpbuf pkt, *opo;
1471 port_mac = port_watcher_get_hwaddr(stp->pw, port_no);
1473 VLOG_WARN_RL(&vrl, "cannot send BPDU on missing port %d", port_no);
1477 /* Packet skeleton. */
1478 ofpbuf_init(&pkt, ETH_HEADER_LEN + LLC_HEADER_LEN + bpdu_size);
1479 eth = ofpbuf_put_uninit(&pkt, sizeof *eth);
1480 llc = ofpbuf_put_uninit(&pkt, sizeof *llc);
1481 ofpbuf_put(&pkt, bpdu, bpdu_size);
1484 memcpy(eth->eth_dst, stp_eth_addr, ETH_ADDR_LEN);
1485 memcpy(eth->eth_src, port_mac, ETH_ADDR_LEN);
1486 eth->eth_type = htons(pkt.size - ETH_HEADER_LEN);
1489 llc->llc_dsap = STP_LLC_DSAP;
1490 llc->llc_ssap = STP_LLC_SSAP;
1491 llc->llc_cntl = STP_LLC_CNTL;
1493 opo = make_unbuffered_packet_out(&pkt, OFPP_NONE, port_no);
1494 ofpbuf_uninit(&pkt);
1495 rconn_send_with_limit(stp->local_rconn, opo, &stp->n_txq, OFPP_MAX);
1499 stp_is_port_supported(uint16_t port_no)
1501 return port_no < STP_MAX_PORTS;
1505 stp_port_changed_cb(uint16_t port_no,
1506 const struct ofp_phy_port *old,
1507 const struct ofp_phy_port *new,
1510 struct stp_data *stp = stp_;
1513 if (!stp_is_port_supported(port_no)) {
1517 p = stp_get_port(stp->stp, port_no);
1519 || new->config & htonl(OFPPC_NO_STP | OFPPC_PORT_DOWN)
1520 || new->state & htonl(OFPPS_LINK_DOWN)) {
1521 stp_port_disable(p);
1525 if (new->curr & (OFPPF_10MB_HD | OFPPF_10MB_FD)) {
1527 } else if (new->curr & (OFPPF_100MB_HD | OFPPF_100MB_FD)) {
1529 } else if (new->curr & (OFPPF_1GB_HD | OFPPF_1GB_FD)) {
1531 } else if (new->curr & OFPPF_100MB_FD) {
1534 stp_port_set_speed(p, speed);
1539 stp_local_port_changed_cb(const struct ofp_phy_port *port, void *stp_)
1541 struct stp_data *stp = stp_;
1543 stp_set_bridge_id(stp->stp, eth_addr_to_uint64(port->hw_addr));
1548 stp_hook_create(const struct settings *s, struct port_watcher *pw,
1549 struct rconn *local, struct rconn *remote)
1551 uint8_t dpid[ETH_ADDR_LEN];
1552 struct stp_data *stp;
1554 stp = xcalloc(1, sizeof *stp);
1555 eth_addr_random(dpid);
1556 stp->stp = stp_create("stp", eth_addr_to_uint64(dpid), send_bpdu, stp);
1558 stp->local_rconn = local;
1559 stp->remote_rconn = remote;
1560 stp->last_tick_256ths = time_256ths();
1562 port_watcher_register_callback(pw, stp_port_changed_cb, stp);
1563 port_watcher_register_local_port_callback(pw, stp_local_port_changed_cb,
1565 return make_hook(stp_local_packet_cb, NULL,
1566 stp_periodic_cb, stp_wait_cb, stp);
1569 /* In-band control. */
1571 struct in_band_data {
1572 const struct settings *s;
1573 struct mac_learning *ml;
1574 struct netdev *of_device;
1575 struct rconn *controller;
1580 queue_tx(struct rconn *rc, struct in_band_data *in_band, struct ofpbuf *b)
1582 rconn_send_with_limit(rc, b, &in_band->n_queued, 10);
1585 static const uint8_t *
1586 get_controller_mac(struct in_band_data *in_band)
1588 static uint32_t ip, last_nonzero_ip;
1589 static uint8_t mac[ETH_ADDR_LEN], last_nonzero_mac[ETH_ADDR_LEN];
1590 static time_t next_refresh = 0;
1592 uint32_t last_ip = ip;
1594 time_t now = time_now();
1596 ip = rconn_get_ip(in_band->controller);
1597 if (last_ip != ip || !next_refresh || now >= next_refresh) {
1600 /* Look up MAC address. */
1601 memset(mac, 0, sizeof mac);
1602 if (ip && in_band->of_device) {
1603 int retval = netdev_arp_lookup(in_band->of_device, ip, mac);
1605 VLOG_DBG_RL(&vrl, "cannot look up controller hw address "
1606 "("IP_FMT"): %s", IP_ARGS(&ip), strerror(retval));
1609 have_mac = !eth_addr_is_zero(mac);
1611 /* Log changes in IP, MAC addresses. */
1612 if (ip && ip != last_nonzero_ip) {
1613 VLOG_DBG("controller IP address changed from "IP_FMT
1614 " to "IP_FMT, IP_ARGS(&last_nonzero_ip), IP_ARGS(&ip));
1615 last_nonzero_ip = ip;
1617 if (have_mac && memcmp(last_nonzero_mac, mac, ETH_ADDR_LEN)) {
1618 VLOG_DBG("controller MAC address changed from "ETH_ADDR_FMT" to "
1620 ETH_ADDR_ARGS(last_nonzero_mac), ETH_ADDR_ARGS(mac));
1621 memcpy(last_nonzero_mac, mac, ETH_ADDR_LEN);
1624 /* Schedule next refresh.
1626 * If we have an IP address but not a MAC address, then refresh
1627 * quickly, since we probably will get a MAC address soon (via ARP).
1628 * Otherwise, we can afford to wait a little while. */
1629 next_refresh = now + (!ip || have_mac ? 10 : 1);
1631 return !eth_addr_is_zero(mac) ? mac : NULL;
1635 is_controller_mac(const uint8_t dl_addr[ETH_ADDR_LEN],
1636 struct in_band_data *in_band)
1638 const uint8_t *mac = get_controller_mac(in_band);
1639 return mac && eth_addr_equals(mac, dl_addr);
1643 in_band_learn_mac(struct in_band_data *in_band,
1644 uint16_t in_port, const uint8_t src_mac[ETH_ADDR_LEN])
1646 if (mac_learning_learn(in_band->ml, src_mac, in_port)) {
1647 VLOG_DBG_RL(&vrl, "learned that "ETH_ADDR_FMT" is on port %"PRIu16,
1648 ETH_ADDR_ARGS(src_mac), in_port);
1653 in_band_local_packet_cb(struct relay *r, void *in_band_)
1655 struct in_band_data *in_band = in_band_;
1656 struct rconn *rc = r->halves[HALF_LOCAL].rconn;
1657 struct ofp_packet_in *opi;
1658 struct eth_header *eth;
1659 struct ofpbuf payload;
1664 if (!get_ofp_packet_eth_header(r, &opi, ð) || !in_band->of_device) {
1667 in_port = ntohs(opi->in_port);
1669 /* Deal with local stuff. */
1670 if (in_port == OFPP_LOCAL) {
1671 /* Sent by secure channel. */
1672 out_port = mac_learning_lookup(in_band->ml, eth->eth_dst);
1673 } else if (eth_addr_equals(eth->eth_dst,
1674 netdev_get_etheraddr(in_band->of_device))) {
1675 /* Sent to secure channel. */
1676 out_port = OFPP_LOCAL;
1677 in_band_learn_mac(in_band, in_port, eth->eth_src);
1678 } else if (eth->eth_type == htons(ETH_TYPE_ARP)
1679 && eth_addr_is_broadcast(eth->eth_dst)
1680 && is_controller_mac(eth->eth_src, in_band)) {
1681 /* ARP sent by controller. */
1682 out_port = OFPP_FLOOD;
1683 } else if (is_controller_mac(eth->eth_dst, in_band)
1684 || is_controller_mac(eth->eth_src, in_band)) {
1685 /* Traffic to or from controller. Switch it by hand. */
1686 in_band_learn_mac(in_band, in_port, eth->eth_src);
1687 out_port = mac_learning_lookup(in_band->ml, eth->eth_dst);
1689 const uint8_t *controller_mac;
1690 controller_mac = get_controller_mac(in_band);
1691 if (eth->eth_type == htons(ETH_TYPE_ARP)
1692 && eth_addr_is_broadcast(eth->eth_dst)
1693 && is_controller_mac(eth->eth_src, in_band)) {
1694 /* ARP sent by controller. */
1695 out_port = OFPP_FLOOD;
1696 } else if (is_controller_mac(eth->eth_dst, in_band)
1697 && in_port == mac_learning_lookup(in_band->ml,
1699 /* Drop controller traffic that arrives on the controller port. */
1706 get_ofp_packet_payload(opi, &payload);
1707 flow_extract(&payload, in_port, &flow);
1708 if (in_port == out_port) {
1709 /* The input and output port match. Set up a flow to drop packets. */
1710 queue_tx(rc, in_band, make_add_flow(&flow, ntohl(opi->buffer_id),
1711 in_band->s->max_idle, 0));
1712 } else if (out_port != OFPP_FLOOD) {
1713 /* The output port is known, so add a new flow. */
1714 queue_tx(rc, in_band,
1715 make_add_simple_flow(&flow, ntohl(opi->buffer_id),
1716 out_port, in_band->s->max_idle));
1718 /* If the switch didn't buffer the packet, we need to send a copy. */
1719 if (ntohl(opi->buffer_id) == UINT32_MAX) {
1720 queue_tx(rc, in_band,
1721 make_unbuffered_packet_out(&payload, in_port, out_port));
1724 /* We don't know that MAC. Send along the packet without setting up a
1727 if (ntohl(opi->buffer_id) == UINT32_MAX) {
1728 b = make_unbuffered_packet_out(&payload, in_port, out_port);
1730 b = make_buffered_packet_out(ntohl(opi->buffer_id),
1733 queue_tx(rc, in_band, b);
1739 in_band_status_cb(struct status_reply *sr, void *in_band_)
1741 struct in_band_data *in_band = in_band_;
1742 struct in_addr local_ip;
1743 uint32_t controller_ip;
1744 const uint8_t *controller_mac;
1746 if (in_band->of_device) {
1747 const uint8_t *mac = netdev_get_etheraddr(in_band->of_device);
1748 if (netdev_get_in4(in_band->of_device, &local_ip)) {
1749 status_reply_put(sr, "local-ip="IP_FMT, IP_ARGS(&local_ip.s_addr));
1751 status_reply_put(sr, "local-mac="ETH_ADDR_FMT, ETH_ADDR_ARGS(mac));
1753 controller_ip = rconn_get_ip(in_band->controller);
1754 if (controller_ip) {
1755 status_reply_put(sr, "controller-ip="IP_FMT,
1756 IP_ARGS(&controller_ip));
1758 controller_mac = get_controller_mac(in_band);
1759 if (controller_mac) {
1760 status_reply_put(sr, "controller-mac="ETH_ADDR_FMT,
1761 ETH_ADDR_ARGS(controller_mac));
1767 get_ofp_packet_payload(struct ofp_packet_in *opi, struct ofpbuf *payload)
1769 payload->data = opi->data;
1770 payload->size = ntohs(opi->header.length) - offsetof(struct ofp_packet_in,
1775 in_band_local_port_cb(const struct ofp_phy_port *port, void *in_band_)
1777 struct in_band_data *in_band = in_band_;
1779 char name[sizeof port->name + 1];
1780 get_port_name(port, name, sizeof name);
1782 if (!in_band->of_device
1783 || strcmp(netdev_get_name(in_band->of_device), name))
1786 netdev_close(in_band->of_device);
1787 error = netdev_open(name, NETDEV_ETH_TYPE_NONE,
1788 &in_band->of_device);
1790 VLOG_ERR("failed to open in-band control network device "
1791 "\"%s\": %s", name, strerror(errno));
1795 netdev_close(in_band->of_device);
1796 in_band->of_device = NULL;
1801 in_band_hook_create(const struct settings *s, struct switch_status *ss,
1802 struct port_watcher *pw, struct rconn *remote)
1804 struct in_band_data *in_band;
1806 in_band = xcalloc(1, sizeof *in_band);
1808 in_band->ml = mac_learning_create();
1809 in_band->of_device = NULL;
1810 in_band->controller = remote;
1811 switch_status_register_category(ss, "in-band", in_band_status_cb, in_band);
1812 port_watcher_register_local_port_callback(pw, in_band_local_port_cb,
1814 return make_hook(in_band_local_packet_cb, NULL, NULL, NULL, in_band);
1817 /* Fail open support. */
1819 struct fail_open_data {
1820 const struct settings *s;
1821 struct rconn *local_rconn;
1822 struct rconn *remote_rconn;
1823 struct lswitch *lswitch;
1824 int last_disconn_secs;
1825 time_t boot_deadline;
1828 /* Causes 'r' to enter or leave fail-open mode, if appropriate. */
1830 fail_open_periodic_cb(void *fail_open_)
1832 struct fail_open_data *fail_open = fail_open_;
1836 if (time_now() < fail_open->boot_deadline) {
1839 disconn_secs = rconn_failure_duration(fail_open->remote_rconn);
1840 open = disconn_secs >= fail_open->s->probe_interval * 3;
1841 if (open != (fail_open->lswitch != NULL)) {
1843 VLOG_WARN("No longer in fail-open mode");
1844 lswitch_destroy(fail_open->lswitch);
1845 fail_open->lswitch = NULL;
1847 VLOG_WARN("Could not connect to controller for %d seconds, "
1848 "failing open", disconn_secs);
1849 fail_open->lswitch = lswitch_create(fail_open->local_rconn, true,
1850 fail_open->s->max_idle);
1851 fail_open->last_disconn_secs = disconn_secs;
1853 } else if (open && disconn_secs > fail_open->last_disconn_secs + 60) {
1854 VLOG_WARN("Still in fail-open mode after %d seconds disconnected "
1855 "from controller", disconn_secs);
1856 fail_open->last_disconn_secs = disconn_secs;
1861 fail_open_local_packet_cb(struct relay *r, void *fail_open_)
1863 struct fail_open_data *fail_open = fail_open_;
1864 if (!fail_open->lswitch) {
1867 lswitch_process_packet(fail_open->lswitch, fail_open->local_rconn,
1868 r->halves[HALF_LOCAL].rxbuf);
1869 rconn_run(fail_open->local_rconn);
1875 fail_open_status_cb(struct status_reply *sr, void *fail_open_)
1877 struct fail_open_data *fail_open = fail_open_;
1878 const struct settings *s = fail_open->s;
1879 int trigger_duration = s->probe_interval * 3;
1880 int cur_duration = rconn_failure_duration(fail_open->remote_rconn);
1882 status_reply_put(sr, "trigger-duration=%d", trigger_duration);
1883 status_reply_put(sr, "current-duration=%d", cur_duration);
1884 status_reply_put(sr, "triggered=%s",
1885 cur_duration >= trigger_duration ? "true" : "false");
1886 status_reply_put(sr, "max-idle=%d", s->max_idle);
1890 fail_open_hook_create(const struct settings *s, struct switch_status *ss,
1891 struct rconn *local_rconn, struct rconn *remote_rconn)
1893 struct fail_open_data *fail_open = xmalloc(sizeof *fail_open);
1895 fail_open->local_rconn = local_rconn;
1896 fail_open->remote_rconn = remote_rconn;
1897 fail_open->lswitch = NULL;
1898 fail_open->boot_deadline = time_now() + s->probe_interval * 3;
1899 if (s->enable_stp) {
1900 fail_open->boot_deadline += STP_EXTRA_BOOT_TIME;
1902 switch_status_register_category(ss, "fail-open",
1903 fail_open_status_cb, fail_open);
1904 return make_hook(fail_open_local_packet_cb, NULL,
1905 fail_open_periodic_cb, NULL, fail_open);
1908 struct rate_limiter {
1909 const struct settings *s;
1910 struct rconn *remote_rconn;
1912 /* One queue per physical port. */
1913 struct ofp_queue queues[OFPP_MAX];
1914 int n_queued; /* Sum over queues[*].n. */
1915 int next_tx_port; /* Next port to check in round-robin. */
1919 * It costs 1000 tokens to send a single packet_in message. A single token
1920 * per message would be more straightforward, but this choice lets us avoid
1921 * round-off error in refill_bucket()'s calculation of how many tokens to
1922 * add to the bucket, since no division step is needed. */
1923 long long int last_fill; /* Time at which we last added tokens. */
1924 int tokens; /* Current number of tokens. */
1926 /* Transmission queue. */
1927 int n_txq; /* No. of packets waiting in rconn for tx. */
1929 /* Statistics reporting. */
1930 unsigned long long n_normal; /* # txed w/o rate limit queuing. */
1931 unsigned long long n_limited; /* # queued for rate limiting. */
1932 unsigned long long n_queue_dropped; /* # dropped due to queue overflow. */
1933 unsigned long long n_tx_dropped; /* # dropped due to tx overflow. */
1936 /* Drop a packet from the longest queue in 'rl'. */
1938 drop_packet(struct rate_limiter *rl)
1940 struct ofp_queue *longest; /* Queue currently selected as longest. */
1941 int n_longest; /* # of queues of same length as 'longest'. */
1942 struct ofp_queue *q;
1944 longest = &rl->queues[0];
1946 for (q = &rl->queues[0]; q < &rl->queues[OFPP_MAX]; q++) {
1947 if (longest->n < q->n) {
1950 } else if (longest->n == q->n) {
1953 /* Randomly select one of the longest queues, with a uniform
1954 * distribution (Knuth algorithm 3.4.2R). */
1955 if (!random_range(n_longest)) {
1961 /* FIXME: do we want to pop the tail instead? */
1962 ofpbuf_delete(queue_pop_head(longest));
1966 /* Remove and return the next packet to transmit (in round-robin order). */
1967 static struct ofpbuf *
1968 dequeue_packet(struct rate_limiter *rl)
1972 for (i = 0; i < OFPP_MAX; i++) {
1973 unsigned int port = (rl->next_tx_port + i) % OFPP_MAX;
1974 struct ofp_queue *q = &rl->queues[port];
1976 rl->next_tx_port = (port + 1) % OFPP_MAX;
1978 return queue_pop_head(q);
1984 /* Add tokens to the bucket based on elapsed time. */
1986 refill_bucket(struct rate_limiter *rl)
1988 const struct settings *s = rl->s;
1989 long long int now = time_msec();
1990 long long int tokens = (now - rl->last_fill) * s->rate_limit + rl->tokens;
1991 if (tokens >= 1000) {
1992 rl->last_fill = now;
1993 rl->tokens = MIN(tokens, s->burst_limit * 1000);
1997 /* Attempts to remove enough tokens from 'rl' to transmit a packet. Returns
1998 * true if successful, false otherwise. (In the latter case no tokens are
2001 get_token(struct rate_limiter *rl)
2003 if (rl->tokens >= 1000) {
2012 rate_limit_local_packet_cb(struct relay *r, void *rl_)
2014 struct rate_limiter *rl = rl_;
2015 const struct settings *s = rl->s;
2016 struct ofp_packet_in *opi;
2018 opi = get_ofp_packet_in(r);
2023 if (!rl->n_queued && get_token(rl)) {
2024 /* In the common case where we are not constrained by the rate limit,
2025 * let the packet take the normal path. */
2029 /* Otherwise queue it up for the periodic callback to drain out. */
2030 struct ofpbuf *msg = r->halves[HALF_LOCAL].rxbuf;
2031 int port = ntohs(opi->in_port) % OFPP_MAX;
2032 if (rl->n_queued >= s->burst_limit) {
2035 queue_push_tail(&rl->queues[port], ofpbuf_clone(msg));
2043 rate_limit_status_cb(struct status_reply *sr, void *rl_)
2045 struct rate_limiter *rl = rl_;
2047 status_reply_put(sr, "normal=%llu", rl->n_normal);
2048 status_reply_put(sr, "limited=%llu", rl->n_limited);
2049 status_reply_put(sr, "queue-dropped=%llu", rl->n_queue_dropped);
2050 status_reply_put(sr, "tx-dropped=%llu", rl->n_tx_dropped);
2054 rate_limit_periodic_cb(void *rl_)
2056 struct rate_limiter *rl = rl_;
2059 /* Drain some packets out of the bucket if possible, but limit the number
2060 * of iterations to allow other code to get work done too. */
2062 for (i = 0; rl->n_queued && get_token(rl) && i < 50; i++) {
2063 /* Use a small, arbitrary limit for the amount of queuing to do here,
2064 * because the TCP connection is responsible for buffering and there is
2065 * no point in trying to transmit faster than the TCP connection can
2067 struct ofpbuf *b = dequeue_packet(rl);
2068 if (rconn_send_with_limit(rl->remote_rconn, b, &rl->n_txq, 10)) {
2075 rate_limit_wait_cb(void *rl_)
2077 struct rate_limiter *rl = rl_;
2079 if (rl->tokens >= 1000) {
2080 /* We can transmit more packets as soon as we're called again. */
2081 poll_immediate_wake();
2083 /* We have to wait for the bucket to re-fill. We could calculate
2084 * the exact amount of time here for increased smoothness. */
2085 poll_timer_wait(TIME_UPDATE_INTERVAL / 2);
2091 rate_limit_hook_create(const struct settings *s, struct switch_status *ss,
2092 struct rconn *local, struct rconn *remote)
2094 struct rate_limiter *rl;
2097 rl = xcalloc(1, sizeof *rl);
2099 rl->remote_rconn = remote;
2100 for (i = 0; i < ARRAY_SIZE(rl->queues); i++) {
2101 queue_init(&rl->queues[i]);
2103 rl->last_fill = time_msec();
2104 rl->tokens = s->rate_limit * 100;
2105 switch_status_register_category(ss, "rate-limit",
2106 rate_limit_status_cb, rl);
2107 return make_hook(rate_limit_local_packet_cb, NULL, rate_limit_periodic_cb,
2108 rate_limit_wait_cb, rl);
2111 /* OFPST_SWITCH statistics. */
2113 struct switch_status_category {
2115 void (*cb)(struct status_reply *, void *aux);
2119 struct switch_status {
2120 const struct settings *s;
2122 struct switch_status_category categories[8];
2126 struct status_reply {
2127 struct switch_status_category *category;
2133 switch_status_remote_packet_cb(struct relay *r, void *ss_)
2135 struct switch_status *ss = ss_;
2136 struct rconn *rc = r->halves[HALF_REMOTE].rconn;
2137 struct ofpbuf *msg = r->halves[HALF_REMOTE].rxbuf;
2138 struct switch_status_category *c;
2139 struct nicira_header *request;
2140 struct nicira_header *reply;
2141 struct status_reply sr;
2145 if (msg->size < sizeof(struct nicira_header)) {
2148 request = msg->data;
2149 if (request->header.type != OFPT_VENDOR
2150 || request->vendor != htonl(NX_VENDOR_ID)
2151 || request->subtype != htonl(NXT_STATUS_REQUEST)) {
2155 sr.request.string = (void *) (request + 1);
2156 sr.request.length = msg->size - sizeof *request;
2157 ds_init(&sr.output);
2158 for (c = ss->categories; c < &ss->categories[ss->n_categories]; c++) {
2159 if (!memcmp(c->name, sr.request.string,
2160 MIN(strlen(c->name), sr.request.length))) {
2165 reply = make_openflow_xid(sizeof *reply + sr.output.length,
2166 OFPT_VENDOR, request->header.xid, &b);
2167 reply->vendor = htonl(NX_VENDOR_ID);
2168 reply->subtype = htonl(NXT_STATUS_REPLY);
2169 memcpy(reply + 1, sr.output.string, sr.output.length);
2170 retval = rconn_send(rc, b, NULL);
2171 if (retval && retval != EAGAIN) {
2172 VLOG_WARN("send failed (%s)", strerror(retval));
2174 ds_destroy(&sr.output);
2179 rconn_status_cb(struct status_reply *sr, void *rconn_)
2181 struct rconn *rconn = rconn_;
2182 time_t now = time_now();
2184 status_reply_put(sr, "name=%s", rconn_get_name(rconn));
2185 status_reply_put(sr, "state=%s", rconn_get_state(rconn));
2186 status_reply_put(sr, "backoff=%d", rconn_get_backoff(rconn));
2187 status_reply_put(sr, "is-connected=%s",
2188 rconn_is_connected(rconn) ? "true" : "false");
2189 status_reply_put(sr, "sent-msgs=%u", rconn_packets_sent(rconn));
2190 status_reply_put(sr, "received-msgs=%u", rconn_packets_received(rconn));
2191 status_reply_put(sr, "attempted-connections=%u",
2192 rconn_get_attempted_connections(rconn));
2193 status_reply_put(sr, "successful-connections=%u",
2194 rconn_get_successful_connections(rconn));
2195 status_reply_put(sr, "last-connection=%ld",
2196 (long int) (now - rconn_get_last_connection(rconn)));
2197 status_reply_put(sr, "time-connected=%lu",
2198 rconn_get_total_time_connected(rconn));
2199 status_reply_put(sr, "state-elapsed=%u", rconn_get_state_elapsed(rconn));
2203 config_status_cb(struct status_reply *sr, void *s_)
2205 const struct settings *s = s_;
2208 for (i = 0; i < s->n_listeners; i++) {
2209 status_reply_put(sr, "management%zu=%s", i, s->listener_names[i]);
2211 if (s->probe_interval) {
2212 status_reply_put(sr, "probe-interval=%d", s->probe_interval);
2214 if (s->max_backoff) {
2215 status_reply_put(sr, "max-backoff=%d", s->max_backoff);
2220 switch_status_cb(struct status_reply *sr, void *ss_)
2222 struct switch_status *ss = ss_;
2223 time_t now = time_now();
2225 status_reply_put(sr, "now=%ld", (long int) now);
2226 status_reply_put(sr, "uptime=%ld", (long int) (now - ss->booted));
2227 status_reply_put(sr, "pid=%ld", (long int) getpid());
2231 switch_status_hook_create(const struct settings *s, struct switch_status **ssp)
2233 struct switch_status *ss = xcalloc(1, sizeof *ss);
2235 ss->booted = time_now();
2236 switch_status_register_category(ss, "config",
2237 config_status_cb, (void *) s);
2238 switch_status_register_category(ss, "switch", switch_status_cb, ss);
2240 return make_hook(NULL, switch_status_remote_packet_cb, NULL, NULL, ss);
2244 switch_status_register_category(struct switch_status *ss,
2245 const char *category,
2246 void (*cb)(struct status_reply *,
2250 struct switch_status_category *c;
2251 assert(ss->n_categories < ARRAY_SIZE(ss->categories));
2252 c = &ss->categories[ss->n_categories++];
2255 c->name = xstrdup(category);
2259 status_reply_put(struct status_reply *sr, const char *content, ...)
2261 size_t old_length = sr->output.length;
2265 /* Append the status reply to the output. */
2266 ds_put_format(&sr->output, "%s.", sr->category->name);
2267 va_start(args, content);
2268 ds_put_format_valist(&sr->output, content, args);
2270 if (ds_last(&sr->output) != '\n') {
2271 ds_put_char(&sr->output, '\n');
2274 /* Drop what we just added if it doesn't match the request. */
2275 added = sr->output.length - old_length;
2276 if (added < sr->request.length
2277 || memcmp(&sr->output.string[old_length],
2278 sr->request.string, sr->request.length)) {
2279 ds_truncate(&sr->output, old_length);
2284 /* Controller discovery. */
2288 const struct settings *s;
2289 struct dhclient *dhcp;
2294 discovery_status_cb(struct status_reply *sr, void *d_)
2296 struct discovery *d = d_;
2298 status_reply_put(sr, "accept-remote=%s", d->s->accept_controller_re);
2299 status_reply_put(sr, "n-changes=%d", d->n_changes);
2301 status_reply_put(sr, "state=%s", dhclient_get_state(d->dhcp));
2302 status_reply_put(sr, "state-elapsed=%u",
2303 dhclient_get_state_elapsed(d->dhcp));
2304 if (dhclient_is_bound(d->dhcp)) {
2305 uint32_t ip = dhclient_get_ip(d->dhcp);
2306 uint32_t netmask = dhclient_get_netmask(d->dhcp);
2307 uint32_t router = dhclient_get_router(d->dhcp);
2309 const struct dhcp_msg *cfg = dhclient_get_config(d->dhcp);
2310 uint32_t dns_server;
2314 status_reply_put(sr, "ip="IP_FMT, IP_ARGS(&ip));
2315 status_reply_put(sr, "netmask="IP_FMT, IP_ARGS(&netmask));
2317 status_reply_put(sr, "router="IP_FMT, IP_ARGS(&router));
2320 for (i = 0; dhcp_msg_get_ip(cfg, DHCP_CODE_DNS_SERVER, i,
2323 status_reply_put(sr, "dns%d="IP_FMT, i, IP_ARGS(&dns_server));
2326 domain_name = dhcp_msg_get_string(cfg, DHCP_CODE_DOMAIN_NAME);
2328 status_reply_put(sr, "domain=%s", domain_name);
2332 status_reply_put(sr, "lease-remaining=%u",
2333 dhclient_get_lease_remaining(d->dhcp));
2339 discovery_local_port_cb(const struct ofp_phy_port *port, void *d_)
2341 struct discovery *d = d_;
2343 char name[OFP_MAX_PORT_NAME_LEN + 1];
2344 struct netdev *netdev;
2347 /* Check that this was really a change. */
2348 get_port_name(port, name, sizeof name);
2349 if (d->dhcp && !strcmp(netdev_get_name(dhclient_get_netdev(d->dhcp)),
2354 /* Destroy current DHCP client. */
2355 dhclient_destroy(d->dhcp);
2358 /* Bring local network device up. */
2359 retval = netdev_open(name, NETDEV_ETH_TYPE_NONE, &netdev);
2361 VLOG_ERR("Could not open %s device, discovery disabled: %s",
2362 name, strerror(retval));
2365 retval = netdev_turn_flags_on(netdev, NETDEV_UP, true);
2367 VLOG_ERR("Could not bring %s device up, discovery disabled: %s",
2368 name, strerror(retval));
2371 netdev_close(netdev);
2373 /* Initialize DHCP client. */
2374 retval = dhclient_create(name, modify_dhcp_request,
2375 validate_dhcp_offer, (void *) d->s, &d->dhcp);
2377 VLOG_ERR("Failed to initialize DHCP client, "
2378 "discovery disabled: %s", strerror(retval));
2381 dhclient_set_max_timeout(d->dhcp, 3);
2382 dhclient_init(d->dhcp, 0);
2384 dhclient_destroy(d->dhcp);
2390 static struct discovery *
2391 discovery_init(const struct settings *s, struct port_watcher *pw,
2392 struct switch_status *ss)
2394 struct discovery *d;
2396 d = xmalloc(sizeof *d);
2401 switch_status_register_category(ss, "discovery", discovery_status_cb, d);
2402 port_watcher_register_local_port_callback(pw, discovery_local_port_cb, d);
2408 discovery_question_connectivity(struct discovery *d)
2411 dhclient_force_renew(d->dhcp, 15);
2416 discovery_run(struct discovery *d, char **controller_name)
2419 *controller_name = NULL;
2423 dhclient_run(d->dhcp);
2424 if (!dhclient_changed(d->dhcp)) {
2428 dhclient_configure_netdev(d->dhcp);
2429 if (d->s->update_resolv_conf) {
2430 dhclient_update_resolv_conf(d->dhcp);
2433 if (dhclient_is_bound(d->dhcp)) {
2434 *controller_name = dhcp_msg_get_string(dhclient_get_config(d->dhcp),
2435 DHCP_CODE_OFP_CONTROLLER_VCONN);
2436 VLOG_WARN("%s: discovered controller", *controller_name);
2439 *controller_name = NULL;
2441 VLOG_WARN("discovered controller no longer available");
2449 discovery_wait(struct discovery *d)
2452 dhclient_wait(d->dhcp);
2457 modify_dhcp_request(struct dhcp_msg *msg, void *aux)
2459 dhcp_msg_put_string(msg, DHCP_CODE_VENDOR_CLASS, "OpenFlow");
2463 validate_dhcp_offer(const struct dhcp_msg *msg, void *s_)
2465 const struct settings *s = s_;
2469 vconn_name = dhcp_msg_get_string(msg, DHCP_CODE_OFP_CONTROLLER_VCONN);
2471 VLOG_WARN_RL(&vrl, "rejecting DHCP offer missing controller vconn");
2474 accept = !regexec(&s->accept_controller_regex, vconn_name, 0, NULL, 0);
2476 VLOG_WARN_RL(&vrl, "rejecting controller vconn that fails to match %s",
2477 s->accept_controller_re);
2483 /* User interface. */
2486 parse_options(int argc, char *argv[], struct settings *s)
2489 OPT_ACCEPT_VCONN = UCHAR_MAX + 1,
2491 OPT_INACTIVITY_PROBE,
2496 OPT_BOOTSTRAP_CA_CERT,
2502 static struct option long_options[] = {
2503 {"accept-vconn", required_argument, 0, OPT_ACCEPT_VCONN},
2504 {"no-resolv-conf", no_argument, 0, OPT_NO_RESOLV_CONF},
2505 {"fail", required_argument, 0, 'F'},
2506 {"inactivity-probe", required_argument, 0, OPT_INACTIVITY_PROBE},
2507 {"max-idle", required_argument, 0, OPT_MAX_IDLE},
2508 {"max-backoff", required_argument, 0, OPT_MAX_BACKOFF},
2509 {"listen", required_argument, 0, 'l'},
2510 {"monitor", required_argument, 0, 'm'},
2511 {"rate-limit", optional_argument, 0, OPT_RATE_LIMIT},
2512 {"burst-limit", required_argument, 0, OPT_BURST_LIMIT},
2513 {"stp", no_argument, 0, OPT_STP},
2514 {"no-stp", no_argument, 0, OPT_NO_STP},
2515 {"out-of-band", no_argument, 0, OPT_OUT_OF_BAND},
2516 {"in-band", no_argument, 0, OPT_IN_BAND},
2517 {"detach", no_argument, 0, 'D'},
2518 {"force", no_argument, 0, 'f'},
2519 {"pidfile", optional_argument, 0, 'P'},
2520 {"verbose", optional_argument, 0, 'v'},
2521 {"help", no_argument, 0, 'h'},
2522 {"version", no_argument, 0, 'V'},
2524 VCONN_SSL_LONG_OPTIONS
2525 {"bootstrap-ca-cert", required_argument, 0, OPT_BOOTSTRAP_CA_CERT},
2529 char *short_options = long_options_to_short_options(long_options);
2530 char *accept_re = NULL;
2533 /* Set defaults that we can figure out before parsing options. */
2535 s->monitor_name = NULL;
2536 s->fail_mode = FAIL_OPEN;
2538 s->probe_interval = 15;
2539 s->max_backoff = 15;
2540 s->update_resolv_conf = true;
2543 s->enable_stp = false;
2548 c = getopt_long(argc, argv, short_options, long_options, NULL);
2554 case OPT_ACCEPT_VCONN:
2555 accept_re = optarg[0] == '^' ? optarg : xasprintf("^%s", optarg);
2558 case OPT_NO_RESOLV_CONF:
2559 s->update_resolv_conf = false;
2563 if (!strcmp(optarg, "open")) {
2564 s->fail_mode = FAIL_OPEN;
2565 } else if (!strcmp(optarg, "closed")) {
2566 s->fail_mode = FAIL_CLOSED;
2568 ofp_fatal(0, "-f or --fail argument must be \"open\" "
2573 case OPT_INACTIVITY_PROBE:
2574 s->probe_interval = atoi(optarg);
2575 if (s->probe_interval < 5) {
2576 ofp_fatal(0, "--inactivity-probe argument must be at least 5");
2581 if (!strcmp(optarg, "permanent")) {
2582 s->max_idle = OFP_FLOW_PERMANENT;
2584 s->max_idle = atoi(optarg);
2585 if (s->max_idle < 1 || s->max_idle > 65535) {
2586 ofp_fatal(0, "--max-idle argument must be between 1 and "
2587 "65535 or the word 'permanent'");
2592 case OPT_MAX_BACKOFF:
2593 s->max_backoff = atoi(optarg);
2594 if (s->max_backoff < 1) {
2595 ofp_fatal(0, "--max-backoff argument must be at least 1");
2596 } else if (s->max_backoff > 3600) {
2597 s->max_backoff = 3600;
2601 case OPT_RATE_LIMIT:
2603 s->rate_limit = atoi(optarg);
2604 if (s->rate_limit < 1) {
2605 ofp_fatal(0, "--rate-limit argument must be at least 1");
2608 s->rate_limit = 1000;
2612 case OPT_BURST_LIMIT:
2613 s->burst_limit = atoi(optarg);
2614 if (s->burst_limit < 1) {
2615 ofp_fatal(0, "--burst-limit argument must be at least 1");
2620 s->enable_stp = true;
2624 s->enable_stp = false;
2627 case OPT_OUT_OF_BAND:
2640 set_pidfile(optarg);
2644 ignore_existing_pidfile();
2648 if (s->n_listeners >= MAX_MGMT) {
2650 "-l or --listen may be specified at most %d times",
2653 s->listener_names[s->n_listeners++] = optarg;
2657 if (s->monitor_name) {
2658 ofp_fatal(0, "-m or --monitor may only be specified once");
2660 s->monitor_name = optarg;
2667 printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
2671 vlog_set_verbosity(optarg);
2675 VCONN_SSL_OPTION_HANDLERS
2677 case OPT_BOOTSTRAP_CA_CERT:
2678 vconn_ssl_set_ca_cert_file(optarg, true);
2689 free(short_options);
2693 if (argc < 1 || argc > 2) {
2694 ofp_fatal(0, "need one or two non-option arguments; "
2695 "use --help for usage");
2698 /* Local and remote vconns. */
2699 s->dp_name = argv[0];
2700 s->controller_name = argc > 1 ? xstrdup(argv[1]) : NULL;
2702 /* Set accept_controller_regex. */
2704 accept_re = vconn_ssl_is_configured() ? "^ssl:.*" : ".*";
2706 retval = regcomp(&s->accept_controller_regex, accept_re,
2707 REG_NOSUB | REG_EXTENDED);
2709 size_t length = regerror(retval, &s->accept_controller_regex, NULL, 0);
2710 char *buffer = xmalloc(length);
2711 regerror(retval, &s->accept_controller_regex, buffer, length);
2712 ofp_fatal(0, "%s: %s", accept_re, buffer);
2714 s->accept_controller_re = accept_re;
2716 /* Mode of operation. */
2717 s->discovery = s->controller_name == NULL;
2718 if (s->discovery && !s->in_band) {
2719 ofp_fatal(0, "Cannot perform discovery with out-of-band control");
2722 /* Rate limiting. */
2723 if (s->rate_limit) {
2724 if (s->rate_limit < 100) {
2725 VLOG_WARN("Rate limit set to unusually low value %d",
2728 if (!s->burst_limit) {
2729 s->burst_limit = s->rate_limit / 4;
2731 s->burst_limit = MAX(s->burst_limit, 1);
2732 s->burst_limit = MIN(s->burst_limit, INT_MAX / 1000);
2739 printf("%s: secure channel, a relay for OpenFlow messages.\n"
2740 "usage: %s [OPTIONS] nl:DP_IDX [CONTROLLER]\n"
2741 "where nl:DP_IDX is a datapath that has been added with dpctl.\n"
2742 "CONTROLLER is an active OpenFlow connection method; if it is\n"
2743 "omitted, then secchan performs controller discovery.\n",
2744 program_name, program_name);
2745 vconn_usage(true, true, true);
2746 printf("\nController discovery options:\n"
2747 " --accept-vconn=REGEX accept matching discovered controllers\n"
2748 " --no-resolv-conf do not update /etc/resolv.conf\n"
2749 "\nNetworking options:\n"
2750 " -F, --fail=open|closed when controller connection fails:\n"
2751 " closed: drop all packets\n"
2752 " open (default): act as learning switch\n"
2753 " --inactivity-probe=SECS time between inactivity probes\n"
2754 " --max-idle=SECS max idle for flows set up by secchan\n"
2755 " --max-backoff=SECS max time between controller connection\n"
2756 " attempts (default: 15 seconds)\n"
2757 " -l, --listen=METHOD allow management connections on METHOD\n"
2758 " (a passive OpenFlow connection method)\n"
2759 " -m, --monitor=METHOD copy traffic to/from kernel to METHOD\n"
2760 " (a passive OpenFlow connection method)\n"
2761 " --out-of-band controller connection is out-of-band\n"
2762 " --stp enable 802.1D Spanning Tree Protocol\n"
2763 " --no-stp disable 802.1D Spanning Tree Protocol\n"
2764 "\nRate-limiting of \"packet-in\" messages to the controller:\n"
2765 " --rate-limit[=PACKETS] max rate, in packets/s (default: 1000)\n"
2766 " --burst-limit=BURST limit on packet credit for idle time\n"
2767 "\nOther options:\n"
2768 " -D, --detach run in background as daemon\n"
2769 " -P, --pidfile[=FILE] create pidfile (default: %s/secchan.pid)\n"
2770 " -f, --force with -P, start even if already running\n"
2771 " -v, --verbose=MODULE[:FACILITY[:LEVEL]] set logging levels\n"
2772 " -v, --verbose set maximum verbosity level\n"
2773 " -h, --help display this help message\n"
2774 " -V, --version display version information\n",