1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
4 * We are making the OpenFlow specification and associated documentation
5 * (Software) available for public use and benefit with the expectation
6 * that others will use, modify and enhance the Software and contribute
7 * those enhancements back to the community. However, since we would
8 * like to make the Software available for broadest use, with as few
9 * restrictions as possible permission is hereby granted, free of
10 * charge, to any person obtaining a copy of this Software to deal in
11 * the Software under the copyrights without restriction, including
12 * without limitation the rights to use, copy, modify, merge, publish,
13 * distribute, sublicense, and/or sell copies of the Software, and to
14 * permit persons to whom the Software is furnished to do so, subject to
15 * the following conditions:
17 * The above copyright notice and this permission notice shall be
18 * included in all copies or substantial portions of the Software.
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 * The name and trademarks of copyright holder(s) may NOT be used in
30 * advertising or publicity pertaining to the Software or any
31 * derivatives without specific, written prior permission.
39 #include <netinet/in.h>
49 #include "command-line.h"
53 #include "dhcp-client.h"
54 #include "dynamic-string.h"
57 #include "learning-switch.h"
59 #include "mac-learning.h"
63 #include "poll-loop.h"
67 #include "vconn-ssl.h"
69 #include "vlog-socket.h"
72 #define THIS_MODULE VLM_secchan
74 /* Behavior when the connection to the controller fails. */
76 FAIL_OPEN, /* Act as learning switch. */
77 FAIL_CLOSED /* Drop all packets. */
80 /* Maximum number of management connection listeners. */
83 /* Settings that may be configured by the user. */
85 /* Overall mode of operation. */
86 bool discovery; /* Discover the controller automatically? */
87 bool in_band; /* Connect to controller in-band? */
89 /* Related vconns and network devices. */
90 const char *nl_name; /* Local datapath (must be "nl:" vconn). */
91 char *of_name; /* ofX network device name. */
92 const char *controller_name; /* Controller (if not discovery mode). */
93 const char *listener_names[MAX_MGMT]; /* Listen for mgmt connections. */
94 size_t n_listeners; /* Number of mgmt connection listeners. */
96 /* Failure behavior. */
97 enum fail_mode fail_mode; /* Act as learning switch if no controller? */
98 int max_idle; /* Idle time for flows in fail-open mode. */
99 int probe_interval; /* # seconds idle before sending echo request. */
100 int max_backoff; /* Max # seconds between connection attempts. */
102 /* Packet-in rate-limiting. */
103 int rate_limit; /* Tokens added to bucket per second. */
104 int burst_limit; /* Maximum number token bucket size. */
106 /* Discovery behavior. */
107 regex_t accept_controller_regex; /* Controller vconns to accept. */
108 const char *accept_controller_re; /* String version of regex. */
109 bool update_resolv_conf; /* Update /etc/resolv.conf? */
114 struct buffer *rxbuf;
115 int n_txq; /* No. of packets queued for tx on 'rconn'. */
122 #define HALF_REMOTE 1
123 struct half halves[2];
129 bool (*packet_cb)(struct relay *, int half, void *aux);
130 void (*periodic_cb)(void *aux);
131 void (*wait_cb)(void *aux);
135 static struct vlog_rate_limit vrl = VLOG_RATE_LIMIT_INIT(60, 60);
137 static void parse_options(int argc, char *argv[], struct settings *);
138 static void usage(void) NO_RETURN;
140 static struct relay *relay_create(struct rconn *local, struct rconn *remote,
142 static struct relay *relay_accept(const struct settings *, struct vconn *);
143 static void relay_run(struct relay *, const struct hook[], size_t n_hooks);
144 static void relay_wait(struct relay *);
145 static void relay_destroy(struct relay *);
147 static struct hook make_hook(bool (*packet_cb)(struct relay *, int, void *),
148 void (*periodic_cb)(void *),
149 void (*wait_cb)(void *),
152 struct switch_status;
154 static struct hook switch_status_hook_create(const struct settings *,
155 struct switch_status **);
156 static void switch_status_register_category(struct switch_status *,
157 const char *category,
158 void (*cb)(struct status_reply *,
161 static void status_reply_put(struct status_reply *, const char *, ...)
164 static void rconn_status_cb(struct status_reply *, void *rconn_);
166 static struct discovery *discovery_init(const struct settings *,
167 struct switch_status *);
168 static void discovery_question_connectivity(struct discovery *);
169 static bool discovery_run(struct discovery *, char **controller_name);
170 static void discovery_wait(struct discovery *);
172 static struct hook in_band_hook_create(const struct settings *,
173 struct switch_status *,
174 struct rconn *remote);
175 static struct hook fail_open_hook_create(const struct settings *,
176 struct switch_status *,
178 struct rconn *remote);
179 static struct hook rate_limit_hook_create(const struct settings *,
180 struct switch_status *,
182 struct rconn *remote);
185 static void modify_dhcp_request(struct dhcp_msg *, void *aux);
186 static bool validate_dhcp_offer(const struct dhcp_msg *, void *aux);
189 main(int argc, char *argv[])
193 struct list relays = LIST_INITIALIZER(&relays);
195 struct hook hooks[8];
198 struct vconn *listeners[MAX_MGMT];
201 struct rconn *local_rconn, *remote_rconn;
202 struct relay *controller_relay;
203 struct discovery *discovery;
204 struct switch_status *switch_status;
208 set_program_name(argv[0]);
209 register_fault_handlers();
212 parse_options(argc, argv, &s);
213 signal(SIGPIPE, SIG_IGN);
215 /* Start listening for management connections. */
217 for (i = 0; i < s.n_listeners; i++) {
218 const char *name = s.listener_names[i];
219 struct vconn *listener;
220 retval = vconn_open(name, &listener);
221 if (retval && retval != EAGAIN) {
222 fatal(retval, "opening %s", name);
224 if (!vconn_is_passive(listener)) {
225 fatal(0, "%s is not a passive vconn", name);
227 listeners[n_listeners++] = listener;
230 /* Initialize switch status hook. */
231 hooks[n_hooks++] = switch_status_hook_create(&s, &switch_status);
233 /* Start controller discovery. */
234 discovery = s.discovery ? discovery_init(&s, switch_status) : NULL;
236 /* Start listening for vlogconf requests. */
237 retval = vlog_server_listen(NULL, NULL);
239 fatal(retval, "Could not listen for vlog connections");
242 die_if_already_running();
245 VLOG_WARN("OpenFlow reference implementation version %s", VERSION);
246 VLOG_WARN("OpenFlow protocol version 0x%02x", OFP_VERSION);
248 /* Connect to datapath. */
249 local_rconn = rconn_create(0, s.max_backoff);
250 rconn_connect(local_rconn, s.nl_name);
251 switch_status_register_category(switch_status, "local",
252 rconn_status_cb, local_rconn);
254 /* Connect to controller. */
255 remote_rconn = rconn_create(s.probe_interval, s.max_backoff);
256 if (s.controller_name) {
257 retval = rconn_connect(remote_rconn, s.controller_name);
258 if (retval == EAFNOSUPPORT) {
259 fatal(0, "No support for %s vconn", s.controller_name);
262 switch_status_register_category(switch_status, "remote",
263 rconn_status_cb, remote_rconn);
265 /* Start relaying. */
266 controller_relay = relay_create(local_rconn, remote_rconn, false);
267 list_push_back(&relays, &controller_relay->node);
271 hooks[n_hooks++] = in_band_hook_create(&s, switch_status,
274 if (s.fail_mode == FAIL_OPEN) {
275 hooks[n_hooks++] = fail_open_hook_create(&s, switch_status,
276 local_rconn, remote_rconn);
279 hooks[n_hooks++] = rate_limit_hook_create(&s, switch_status,
280 local_rconn, remote_rconn);
282 assert(n_hooks <= ARRAY_SIZE(hooks));
289 LIST_FOR_EACH_SAFE (r, n, struct relay, node, &relays) {
290 relay_run(r, hooks, n_hooks);
292 for (i = 0; i < n_listeners; i++) {
294 struct relay *r = relay_accept(&s, listeners[i]);
298 list_push_back(&relays, &r->node);
301 for (i = 0; i < n_hooks; i++) {
302 if (hooks[i].periodic_cb) {
303 hooks[i].periodic_cb(hooks[i].aux);
307 char *controller_name;
308 if (rconn_is_connectivity_questionable(remote_rconn)) {
309 discovery_question_connectivity(discovery);
311 if (discovery_run(discovery, &controller_name)) {
312 if (controller_name) {
313 rconn_connect(remote_rconn, controller_name);
315 rconn_disconnect(remote_rconn);
320 /* Wait for something to happen. */
321 LIST_FOR_EACH (r, struct relay, node, &relays) {
324 for (i = 0; i < n_listeners; i++) {
325 vconn_accept_wait(listeners[i]);
327 for (i = 0; i < n_hooks; i++) {
328 if (hooks[i].wait_cb) {
329 hooks[i].wait_cb(hooks[i].aux);
333 discovery_wait(discovery);
342 make_hook(bool (*packet_cb)(struct relay *, int half, void *aux),
343 void (*periodic_cb)(void *aux),
344 void (*wait_cb)(void *aux),
348 h.packet_cb = packet_cb;
349 h.periodic_cb = periodic_cb;
355 /* OpenFlow message relaying. */
357 static struct relay *
358 relay_accept(const struct settings *s, struct vconn *listen_vconn)
360 struct vconn *new_remote, *new_local;
361 char *nl_name_without_subscription;
362 struct rconn *r1, *r2;
365 retval = vconn_accept(listen_vconn, &new_remote);
367 if (retval != EAGAIN) {
368 VLOG_WARN_RL(&vrl, "accept failed (%s)", strerror(retval));
373 /* nl:123 or nl:123:1 opens a netlink connection to local datapath 123. We
374 * only accept the former syntax in main().
376 * nl:123:0 opens a netlink connection to local datapath 123 without
377 * obtaining a subscription for ofp_packet_in or ofp_flow_expired
379 nl_name_without_subscription = xasprintf("%s:0", s->nl_name);
380 retval = vconn_open(nl_name_without_subscription, &new_local);
382 VLOG_ERR_RL(&vrl, "could not connect to %s (%s)",
383 nl_name_without_subscription, strerror(retval));
384 vconn_close(new_remote);
385 free(nl_name_without_subscription);
389 /* Create and return relay. */
390 r1 = rconn_create(0, 0);
391 rconn_connect_unreliably(r1, nl_name_without_subscription, new_local);
392 free(nl_name_without_subscription);
394 r2 = rconn_create(0, 0);
395 rconn_connect_unreliably(r2, "passive", new_remote);
397 return relay_create(r1, r2, true);
400 static struct relay *
401 relay_create(struct rconn *local, struct rconn *remote, bool is_mgmt_conn)
403 struct relay *r = xcalloc(1, sizeof *r);
404 r->halves[HALF_LOCAL].rconn = local;
405 r->halves[HALF_REMOTE].rconn = remote;
406 r->is_mgmt_conn = is_mgmt_conn;
411 relay_run(struct relay *r, const struct hook hooks[], size_t n_hooks)
416 for (i = 0; i < 2; i++) {
417 rconn_run(r->halves[i].rconn);
420 /* Limit the number of iterations to prevent other tasks from starving. */
421 for (iteration = 0; iteration < 50; iteration++) {
422 bool progress = false;
423 for (i = 0; i < 2; i++) {
424 struct half *this = &r->halves[i];
425 struct half *peer = &r->halves[!i];
428 this->rxbuf = rconn_recv(this->rconn);
430 const struct hook *h;
431 for (h = hooks; h < &hooks[n_hooks]; h++) {
432 if (h->packet_cb(r, i, h->aux)) {
433 buffer_delete(this->rxbuf);
442 if (this->rxbuf && !this->n_txq) {
443 int retval = rconn_send(peer->rconn, this->rxbuf,
445 if (retval != EAGAIN) {
449 buffer_delete(this->rxbuf);
460 if (r->is_mgmt_conn) {
461 for (i = 0; i < 2; i++) {
462 struct half *this = &r->halves[i];
463 if (!rconn_is_alive(this->rconn)) {
472 relay_wait(struct relay *r)
476 for (i = 0; i < 2; i++) {
477 struct half *this = &r->halves[i];
479 rconn_run_wait(this->rconn);
481 rconn_recv_wait(this->rconn);
487 relay_destroy(struct relay *r)
491 list_remove(&r->node);
492 for (i = 0; i < 2; i++) {
493 struct half *this = &r->halves[i];
494 rconn_destroy(this->rconn);
495 buffer_delete(this->rxbuf);
500 /* In-band control. */
502 struct in_band_data {
503 const struct settings *s;
504 struct mac_learning *ml;
505 struct netdev *of_device;
506 struct rconn *controller;
507 uint8_t mac[ETH_ADDR_LEN];
512 queue_tx(struct rconn *rc, struct in_band_data *in_band, struct buffer *b)
514 rconn_send_with_limit(rc, b, &in_band->n_queued, 10);
517 static const uint8_t *
518 get_controller_mac(struct in_band_data *in_band)
520 static uint32_t ip, last_nonzero_ip;
521 static uint8_t mac[ETH_ADDR_LEN], last_nonzero_mac[ETH_ADDR_LEN];
522 static time_t next_refresh = 0;
524 uint32_t last_ip = ip;
526 time_t now = time_now();
528 ip = rconn_get_ip(in_band->controller);
529 if (last_ip != ip || !next_refresh || now >= next_refresh) {
532 /* Look up MAC address. */
533 memset(mac, 0, sizeof mac);
535 int retval = netdev_arp_lookup(in_band->of_device, ip, mac);
537 VLOG_DBG("cannot look up controller hw address ("IP_FMT"): %s",
538 IP_ARGS(&ip), strerror(retval));
541 have_mac = !eth_addr_is_zero(mac);
543 /* Log changes in IP, MAC addresses. */
544 if (ip && ip != last_nonzero_ip) {
545 VLOG_DBG("controller IP address changed from "IP_FMT
546 " to "IP_FMT, IP_ARGS(&last_nonzero_ip), IP_ARGS(&ip));
547 last_nonzero_ip = ip;
549 if (have_mac && memcmp(last_nonzero_mac, mac, ETH_ADDR_LEN)) {
550 VLOG_DBG("controller MAC address changed from "ETH_ADDR_FMT" to "
552 ETH_ADDR_ARGS(last_nonzero_mac), ETH_ADDR_ARGS(mac));
553 memcpy(last_nonzero_mac, mac, ETH_ADDR_LEN);
556 /* Schedule next refresh.
558 * If we have an IP address but not a MAC address, then refresh
559 * quickly, since we probably will get a MAC address soon (via ARP).
560 * Otherwise, we can afford to wait a little while. */
561 next_refresh = now + (!ip || have_mac ? 10 : 1);
563 return !eth_addr_is_zero(mac) ? mac : NULL;
567 is_controller_mac(const uint8_t dl_addr[ETH_ADDR_LEN],
568 struct in_band_data *in_band)
570 const uint8_t *mac = get_controller_mac(in_band);
571 return mac && eth_addr_equals(mac, dl_addr);
575 in_band_packet_cb(struct relay *r, int half, void *in_band_)
577 struct in_band_data *in_band = in_band_;
578 struct rconn *rc = r->halves[HALF_LOCAL].rconn;
579 struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
580 struct ofp_packet_in *opi;
581 struct ofp_header *oh;
582 size_t pkt_ofs, pkt_len;
585 uint16_t in_port, out_port;
586 const uint8_t *controller_mac;
588 if (half != HALF_LOCAL || r->is_mgmt_conn) {
593 if (oh->type != OFPT_PACKET_IN) {
596 if (msg->size < offsetof(struct ofp_packet_in, data)) {
597 VLOG_WARN_RL(&vrl, "packet too short (%zu bytes) for packet_in",
602 /* Extract flow data from 'opi' into 'flow'. */
604 in_port = ntohs(opi->in_port);
605 pkt_ofs = offsetof(struct ofp_packet_in, data);
606 pkt_len = ntohs(opi->header.length) - pkt_ofs;
607 pkt.data = opi->data;
609 flow_extract(&pkt, in_port, &flow);
611 /* Deal with local stuff. */
612 controller_mac = get_controller_mac(in_band);
613 if (in_port == OFPP_LOCAL) {
614 /* Sent by secure channel. */
615 out_port = mac_learning_lookup(in_band->ml, flow.dl_dst);
616 } else if (eth_addr_equals(flow.dl_dst, in_band->mac)) {
617 /* Sent to secure channel. */
618 out_port = OFPP_LOCAL;
619 if (mac_learning_learn(in_band->ml, flow.dl_src, in_port)) {
620 VLOG_DBG_RL(&vrl, "learned that "ETH_ADDR_FMT" is on port %"PRIu16,
621 ETH_ADDR_ARGS(flow.dl_src), in_port);
623 } else if (flow.dl_type == htons(ETH_TYPE_ARP)
624 && eth_addr_is_broadcast(flow.dl_dst)
625 && is_controller_mac(flow.dl_src, in_band)) {
626 /* ARP sent by controller. */
627 out_port = OFPP_FLOOD;
628 } else if (is_controller_mac(flow.dl_dst, in_band)
629 && in_port == mac_learning_lookup(in_band->ml,
631 /* Drop controller traffic that arrives on the controller port. */
632 queue_tx(rc, in_band, make_add_flow(&flow, ntohl(opi->buffer_id),
633 in_band->s->max_idle, 0));
639 if (out_port != OFPP_FLOOD) {
640 /* The output port is known, so add a new flow. */
641 queue_tx(rc, in_band,
642 make_add_simple_flow(&flow, ntohl(opi->buffer_id),
643 out_port, in_band->s->max_idle));
645 /* If the switch didn't buffer the packet, we need to send a copy. */
646 if (ntohl(opi->buffer_id) == UINT32_MAX) {
647 queue_tx(rc, in_band,
648 make_unbuffered_packet_out(&pkt, in_port, out_port));
651 /* We don't know that MAC. Send along the packet without setting up a
654 if (ntohl(opi->buffer_id) == UINT32_MAX) {
655 b = make_unbuffered_packet_out(&pkt, in_port, out_port);
657 b = make_buffered_packet_out(ntohl(opi->buffer_id),
660 queue_tx(rc, in_band, b);
666 in_band_status_cb(struct status_reply *sr, void *in_band_)
668 struct in_band_data *in_band = in_band_;
669 struct in_addr local_ip;
670 uint32_t controller_ip;
671 const uint8_t *controller_mac;
673 if (netdev_get_in4(in_band->of_device, &local_ip)) {
674 status_reply_put(sr, "local-ip="IP_FMT, IP_ARGS(&local_ip.s_addr));
676 status_reply_put(sr, "local-mac="ETH_ADDR_FMT,
677 ETH_ADDR_ARGS(in_band->mac));
679 controller_ip = rconn_get_ip(in_band->controller);
681 status_reply_put(sr, "controller-ip="IP_FMT,
682 IP_ARGS(&controller_ip));
684 controller_mac = get_controller_mac(in_band);
685 if (controller_mac) {
686 status_reply_put(sr, "controller-mac="ETH_ADDR_FMT,
687 ETH_ADDR_ARGS(controller_mac));
692 in_band_hook_create(const struct settings *s, struct switch_status *ss,
693 struct rconn *remote)
695 struct in_band_data *in_band;
698 in_band = xcalloc(1, sizeof *in_band);
700 in_band->ml = mac_learning_create();
701 retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE,
702 &in_band->of_device);
704 fatal(retval, "Could not open %s device", s->of_name);
706 memcpy(in_band->mac, netdev_get_etheraddr(in_band->of_device),
708 in_band->controller = remote;
709 switch_status_register_category(ss, "in-band", in_band_status_cb, in_band);
710 return make_hook(in_band_packet_cb, NULL, NULL, in_band);
713 /* Fail open support. */
715 struct fail_open_data {
716 const struct settings *s;
717 struct rconn *local_rconn;
718 struct rconn *remote_rconn;
719 struct lswitch *lswitch;
720 int last_disconn_secs;
723 /* Causes 'r' to enter or leave fail-open mode, if appropriate. */
725 fail_open_periodic_cb(void *fail_open_)
727 struct fail_open_data *fail_open = fail_open_;
731 disconn_secs = rconn_disconnected_duration(fail_open->remote_rconn);
732 open = disconn_secs >= fail_open->s->probe_interval * 3;
733 if (open != (fail_open->lswitch != NULL)) {
735 VLOG_WARN("No longer in fail-open mode");
736 lswitch_destroy(fail_open->lswitch);
737 fail_open->lswitch = NULL;
739 VLOG_WARN("Could not connect to controller for %d seconds, "
740 "failing open", disconn_secs);
741 fail_open->lswitch = lswitch_create(fail_open->local_rconn, true,
742 fail_open->s->max_idle);
743 fail_open->last_disconn_secs = disconn_secs;
745 } else if (open && disconn_secs > fail_open->last_disconn_secs + 60) {
746 VLOG_WARN("Still in fail-open mode after %d seconds disconnected "
747 "from controller", disconn_secs);
748 fail_open->last_disconn_secs = disconn_secs;
753 fail_open_packet_cb(struct relay *r, int half, void *fail_open_)
755 struct fail_open_data *fail_open = fail_open_;
756 if (half != HALF_LOCAL || r->is_mgmt_conn || !fail_open->lswitch) {
759 lswitch_process_packet(fail_open->lswitch, fail_open->local_rconn,
760 r->halves[HALF_LOCAL].rxbuf);
761 rconn_run(fail_open->local_rconn);
767 fail_open_status_cb(struct status_reply *sr, void *fail_open_)
769 struct fail_open_data *fail_open = fail_open_;
770 const struct settings *s = fail_open->s;
771 int trigger_duration = s->probe_interval * 3;
772 int cur_duration = rconn_disconnected_duration(fail_open->remote_rconn);
774 status_reply_put(sr, "trigger-duration=%d", trigger_duration);
775 status_reply_put(sr, "current-duration=%d", cur_duration);
776 status_reply_put(sr, "triggered=%s",
777 cur_duration >= trigger_duration ? "true" : "false");
778 status_reply_put(sr, "max-idle=%d", s->max_idle);
782 fail_open_hook_create(const struct settings *s, struct switch_status *ss,
783 struct rconn *local_rconn, struct rconn *remote_rconn)
785 struct fail_open_data *fail_open = xmalloc(sizeof *fail_open);
787 fail_open->local_rconn = local_rconn;
788 fail_open->remote_rconn = remote_rconn;
789 fail_open->lswitch = NULL;
790 switch_status_register_category(ss, "fail-open",
791 fail_open_status_cb, fail_open);
792 return make_hook(fail_open_packet_cb, fail_open_periodic_cb, NULL,
796 struct rate_limiter {
797 const struct settings *s;
798 struct rconn *remote_rconn;
800 /* One queue per physical port. */
801 struct queue queues[OFPP_MAX];
802 int n_queued; /* Sum over queues[*].n. */
803 int next_tx_port; /* Next port to check in round-robin. */
807 * It costs 1000 tokens to send a single packet_in message. A single token
808 * per message would be more straightforward, but this choice lets us avoid
809 * round-off error in refill_bucket()'s calculation of how many tokens to
810 * add to the bucket, since no division step is needed. */
811 long long int last_fill; /* Time at which we last added tokens. */
812 int tokens; /* Current number of tokens. */
814 /* Transmission queue. */
815 int n_txq; /* No. of packets waiting in rconn for tx. */
817 /* Statistics reporting. */
818 unsigned long long n_normal; /* # txed w/o rate limit queuing. */
819 unsigned long long n_limited; /* # queued for rate limiting. */
820 unsigned long long n_queue_dropped; /* # dropped due to queue overflow. */
821 unsigned long long n_tx_dropped; /* # dropped due to tx overflow. */
824 /* Drop a packet from the longest queue in 'rl'. */
826 drop_packet(struct rate_limiter *rl)
828 struct queue *longest; /* Queue currently selected as longest. */
829 int n_longest; /* # of queues of same length as 'longest'. */
832 longest = &rl->queues[0];
834 for (q = &rl->queues[0]; q < &rl->queues[OFPP_MAX]; q++) {
835 if (longest->n < q->n) {
838 } else if (longest->n == q->n) {
841 /* Randomly select one of the longest queues, with a uniform
842 * distribution (Knuth algorithm 3.4.2R). */
843 if (!random_range(n_longest)) {
849 /* FIXME: do we want to pop the tail instead? */
850 buffer_delete(queue_pop_head(longest));
854 /* Remove and return the next packet to transmit (in round-robin order). */
855 static struct buffer *
856 dequeue_packet(struct rate_limiter *rl)
860 for (i = 0; i < OFPP_MAX; i++) {
861 unsigned int port = (rl->next_tx_port + i) % OFPP_MAX;
862 struct queue *q = &rl->queues[port];
864 rl->next_tx_port = (port + 1) % OFPP_MAX;
866 return queue_pop_head(q);
872 /* Add tokens to the bucket based on elapsed time. */
874 refill_bucket(struct rate_limiter *rl)
876 const struct settings *s = rl->s;
877 long long int now = time_msec();
878 long long int tokens = (now - rl->last_fill) * s->rate_limit + rl->tokens;
879 if (tokens >= 1000) {
881 rl->tokens = MIN(tokens, s->burst_limit * 1000);
885 /* Attempts to remove enough tokens from 'rl' to transmit a packet. Returns
886 * true if successful, false otherwise. (In the latter case no tokens are
889 get_token(struct rate_limiter *rl)
891 if (rl->tokens >= 1000) {
900 rate_limit_packet_cb(struct relay *r, int half, void *rl_)
902 struct rate_limiter *rl = rl_;
903 const struct settings *s = rl->s;
904 struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
905 struct ofp_header *oh;
907 if (half == HALF_REMOTE) {
912 if (oh->type != OFPT_PACKET_IN) {
915 if (msg->size < offsetof(struct ofp_packet_in, data)) {
916 VLOG_WARN_RL(&vrl, "packet too short (%zu bytes) for packet_in",
921 if (!rl->n_queued && get_token(rl)) {
922 /* In the common case where we are not constrained by the rate limit,
923 * let the packet take the normal path. */
927 /* Otherwise queue it up for the periodic callback to drain out. */
928 struct ofp_packet_in *opi = msg->data;
929 int port = ntohs(opi->in_port) % OFPP_MAX;
930 if (rl->n_queued >= s->burst_limit) {
933 queue_push_tail(&rl->queues[port], buffer_clone(msg));
941 rate_limit_status_cb(struct status_reply *sr, void *rl_)
943 struct rate_limiter *rl = rl_;
945 status_reply_put(sr, "normal=%llu", rl->n_normal);
946 status_reply_put(sr, "limited=%llu", rl->n_limited);
947 status_reply_put(sr, "queue-dropped=%llu", rl->n_queue_dropped);
948 status_reply_put(sr, "tx-dropped=%llu", rl->n_tx_dropped);
952 rate_limit_periodic_cb(void *rl_)
954 struct rate_limiter *rl = rl_;
957 /* Drain some packets out of the bucket if possible, but limit the number
958 * of iterations to allow other code to get work done too. */
960 for (i = 0; rl->n_queued && get_token(rl) && i < 50; i++) {
961 /* Use a small, arbitrary limit for the amount of queuing to do here,
962 * because the TCP connection is responsible for buffering and there is
963 * no point in trying to transmit faster than the TCP connection can
965 struct buffer *b = dequeue_packet(rl);
966 if (rconn_send_with_limit(rl->remote_rconn, b, &rl->n_txq, 10)) {
973 rate_limit_wait_cb(void *rl_)
975 struct rate_limiter *rl = rl_;
977 if (rl->tokens >= 1000) {
978 /* We can transmit more packets as soon as we're called again. */
979 poll_immediate_wake();
981 /* We have to wait for the bucket to re-fill. We could calculate
982 * the exact amount of time here for increased smoothness. */
983 poll_timer_wait(TIME_UPDATE_INTERVAL / 2);
989 rate_limit_hook_create(const struct settings *s, struct switch_status *ss,
990 struct rconn *local, struct rconn *remote)
992 struct rate_limiter *rl;
995 rl = xcalloc(1, sizeof *rl);
997 rl->remote_rconn = remote;
998 for (i = 0; i < ARRAY_SIZE(rl->queues); i++) {
999 queue_init(&rl->queues[i]);
1001 rl->last_fill = time_msec();
1002 rl->tokens = s->rate_limit * 100;
1003 switch_status_register_category(ss, "rate-limit",
1004 rate_limit_status_cb, rl);
1005 return make_hook(rate_limit_packet_cb, rate_limit_periodic_cb,
1006 rate_limit_wait_cb, rl);
1009 /* OFPST_SWITCH statistics. */
1011 struct switch_status_category {
1013 void (*cb)(struct status_reply *, void *aux);
1017 struct switch_status {
1018 const struct settings *s;
1020 struct switch_status_category categories[8];
1024 struct status_reply {
1025 struct switch_status_category *category;
1031 switch_status_packet_cb(struct relay *r, int half, void *ss_)
1033 struct switch_status *ss = ss_;
1034 struct rconn *rc = r->halves[HALF_REMOTE].rconn;
1035 struct buffer *msg = r->halves[HALF_REMOTE].rxbuf;
1036 struct switch_status_category *c;
1037 struct ofp_stats_request *osr;
1038 struct ofp_stats_reply *reply;
1039 struct status_reply sr;
1040 struct ofp_header *oh;
1044 if (half == HALF_LOCAL) {
1049 if (oh->type != OFPT_STATS_REQUEST) {
1052 if (msg->size < sizeof(struct ofp_stats_request)) {
1053 VLOG_WARN_RL(&vrl, "packet too short (%zu bytes) for stats_request",
1059 if (osr->type != htons(OFPST_SWITCH)) {
1063 sr.request.string = (void *) (osr + 1);
1064 sr.request.length = msg->size - sizeof *osr;
1065 ds_init(&sr.output);
1066 for (c = ss->categories; c < &ss->categories[ss->n_categories]; c++) {
1067 if (!memcmp(c->name, sr.request.string,
1068 MIN(strlen(c->name), sr.request.length))) {
1073 reply = make_openflow_xid((offsetof(struct ofp_stats_reply, body)
1074 + sr.output.length),
1075 OFPT_STATS_REPLY, osr->header.xid, &b);
1076 reply->type = htons(OFPST_SWITCH);
1078 memcpy(reply->body, sr.output.string, sr.output.length);
1079 retval = rconn_send(rc, b, NULL);
1080 if (retval && retval != EAGAIN) {
1081 VLOG_WARN("send failed (%s)", strerror(retval));
1083 ds_destroy(&sr.output);
1088 rconn_status_cb(struct status_reply *sr, void *rconn_)
1090 struct rconn *rconn = rconn_;
1091 time_t now = time_now();
1093 status_reply_put(sr, "name=%s", rconn_get_name(rconn));
1094 status_reply_put(sr, "state=%s", rconn_get_state(rconn));
1095 status_reply_put(sr, "backoff=%d", rconn_get_backoff(rconn));
1096 status_reply_put(sr, "is-connected=%s",
1097 rconn_is_connected(rconn) ? "true" : "false");
1098 status_reply_put(sr, "sent-msgs=%u", rconn_packets_sent(rconn));
1099 status_reply_put(sr, "received-msgs=%u", rconn_packets_received(rconn));
1100 status_reply_put(sr, "attempted-connections=%u",
1101 rconn_get_attempted_connections(rconn));
1102 status_reply_put(sr, "successful-connections=%u",
1103 rconn_get_successful_connections(rconn));
1104 status_reply_put(sr, "last-connection=%ld",
1105 (long int) (now - rconn_get_last_connection(rconn)));
1106 status_reply_put(sr, "time-connected=%lu",
1107 rconn_get_total_time_connected(rconn));
1108 status_reply_put(sr, "state-elapsed=%u", rconn_get_state_elapsed(rconn));
1112 config_status_cb(struct status_reply *sr, void *s_)
1114 const struct settings *s = s_;
1117 for (i = 0; i < s->n_listeners; i++) {
1118 status_reply_put(sr, "management%zu=%s", i, s->listener_names[i]);
1120 if (s->probe_interval) {
1121 status_reply_put(sr, "probe-interval=%d", s->probe_interval);
1123 if (s->max_backoff) {
1124 status_reply_put(sr, "max-backoff=%d", s->max_backoff);
1129 switch_status_cb(struct status_reply *sr, void *ss_)
1131 struct switch_status *ss = ss_;
1132 time_t now = time_now();
1134 status_reply_put(sr, "now=%ld", (long int) now);
1135 status_reply_put(sr, "uptime=%ld", (long int) (now - ss->booted));
1136 status_reply_put(sr, "pid=%ld", (long int) getpid());
1140 switch_status_hook_create(const struct settings *s, struct switch_status **ssp)
1142 struct switch_status *ss = xcalloc(1, sizeof *ss);
1144 ss->booted = time_now();
1145 switch_status_register_category(ss, "config",
1146 config_status_cb, (void *) s);
1147 switch_status_register_category(ss, "switch", switch_status_cb, ss);
1149 return make_hook(switch_status_packet_cb, NULL, NULL, ss);
1153 switch_status_register_category(struct switch_status *ss,
1154 const char *category,
1155 void (*cb)(struct status_reply *,
1159 struct switch_status_category *c;
1160 assert(ss->n_categories < ARRAY_SIZE(ss->categories));
1161 c = &ss->categories[ss->n_categories++];
1164 c->name = xstrdup(category);
1168 status_reply_put(struct status_reply *sr, const char *content, ...)
1170 size_t old_length = sr->output.length;
1174 /* Append the status reply to the output. */
1175 ds_put_format(&sr->output, "%s.", sr->category->name);
1176 va_start(args, content);
1177 ds_put_format_valist(&sr->output, content, args);
1179 if (ds_last(&sr->output) != '\n') {
1180 ds_put_char(&sr->output, '\n');
1183 /* Drop what we just added if it doesn't match the request. */
1184 added = sr->output.length - old_length;
1185 if (added < sr->request.length
1186 || memcmp(&sr->output.string[old_length],
1187 sr->request.string, sr->request.length)) {
1188 ds_truncate(&sr->output, old_length);
1193 /* Controller discovery. */
1197 const struct settings *s;
1198 struct dhclient *dhcp;
1203 discovery_status_cb(struct status_reply *sr, void *d_)
1205 struct discovery *d = d_;
1207 status_reply_put(sr, "discovery.accept-remote=%s",
1208 d->s->accept_controller_re);
1209 status_reply_put(sr, "discovery.n-changes=%d", d->n_changes);
1210 status_reply_put(sr, "discovery.state=%s", dhclient_get_state(d->dhcp));
1211 status_reply_put(sr, "discovery.state-elapsed=%u",
1212 dhclient_get_state_elapsed(d->dhcp));
1213 if (dhclient_is_bound(d->dhcp)) {
1214 uint32_t ip = dhclient_get_ip(d->dhcp);
1215 uint32_t netmask = dhclient_get_netmask(d->dhcp);
1216 uint32_t router = dhclient_get_router(d->dhcp);
1218 const struct dhcp_msg *cfg = dhclient_get_config(d->dhcp);
1219 uint32_t dns_server;
1223 status_reply_put(sr, "discovery.ip="IP_FMT, IP_ARGS(&ip));
1224 status_reply_put(sr, "discovery.netmask="IP_FMT, IP_ARGS(&netmask));
1226 status_reply_put(sr, "discovery.router="IP_FMT, IP_ARGS(&router));
1229 for (i = 0; dhcp_msg_get_ip(cfg, DHCP_CODE_DNS_SERVER, i, &dns_server);
1231 status_reply_put(sr, "discovery.dns%d="IP_FMT,
1232 i, IP_ARGS(&dns_server));
1235 domain_name = dhcp_msg_get_string(cfg, DHCP_CODE_DOMAIN_NAME);
1237 status_reply_put(sr, "discovery.domain=%s", domain_name);
1241 status_reply_put(sr, "discovery.lease-remaining=%u",
1242 dhclient_get_lease_remaining(d->dhcp));
1246 static struct discovery *
1247 discovery_init(const struct settings *s, struct switch_status *ss)
1249 struct netdev *netdev;
1250 struct discovery *d;
1251 struct dhclient *dhcp;
1254 /* Bring ofX network device up. */
1255 retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
1257 fatal(retval, "Could not open %s device", s->of_name);
1259 retval = netdev_turn_flags_on(netdev, NETDEV_UP, true);
1261 fatal(retval, "Could not bring %s device up", s->of_name);
1263 netdev_close(netdev);
1265 /* Initialize DHCP client. */
1266 retval = dhclient_create(s->of_name, modify_dhcp_request,
1267 validate_dhcp_offer, (void *) s, &dhcp);
1269 fatal(retval, "Failed to initialize DHCP client");
1271 dhclient_init(dhcp, 0);
1273 d = xmalloc(sizeof *d);
1278 switch_status_register_category(ss, "discovery", discovery_status_cb, d);
1284 discovery_question_connectivity(struct discovery *d)
1286 dhclient_force_renew(d->dhcp, 15);
1290 discovery_run(struct discovery *d, char **controller_name)
1292 dhclient_run(d->dhcp);
1293 if (!dhclient_changed(d->dhcp)) {
1297 dhclient_configure_netdev(d->dhcp);
1298 if (d->s->update_resolv_conf) {
1299 dhclient_update_resolv_conf(d->dhcp);
1302 if (dhclient_is_bound(d->dhcp)) {
1303 *controller_name = dhcp_msg_get_string(dhclient_get_config(d->dhcp),
1304 DHCP_CODE_OFP_CONTROLLER_VCONN);
1305 VLOG_WARN("%s: discovered controller", *controller_name);
1308 *controller_name = NULL;
1310 VLOG_WARN("discovered controller no longer available");
1318 discovery_wait(struct discovery *d)
1320 dhclient_wait(d->dhcp);
1324 modify_dhcp_request(struct dhcp_msg *msg, void *aux)
1326 dhcp_msg_put_string(msg, DHCP_CODE_VENDOR_CLASS, "OpenFlow");
1330 validate_dhcp_offer(const struct dhcp_msg *msg, void *s_)
1332 const struct settings *s = s_;
1336 vconn_name = dhcp_msg_get_string(msg, DHCP_CODE_OFP_CONTROLLER_VCONN);
1338 VLOG_WARN_RL(&vrl, "rejecting DHCP offer missing controller vconn");
1341 accept = !regexec(&s->accept_controller_regex, vconn_name, 0, NULL, 0);
1343 VLOG_WARN_RL(&vrl, "rejecting controller vconn that fails to match %s",
1344 s->accept_controller_re);
1350 /* User interface. */
1353 parse_options(int argc, char *argv[], struct settings *s)
1356 OPT_ACCEPT_VCONN = UCHAR_MAX + 1,
1358 OPT_INACTIVITY_PROBE,
1364 static struct option long_options[] = {
1365 {"accept-vconn", required_argument, 0, OPT_ACCEPT_VCONN},
1366 {"no-resolv-conf", no_argument, 0, OPT_NO_RESOLV_CONF},
1367 {"fail", required_argument, 0, 'F'},
1368 {"inactivity-probe", required_argument, 0, OPT_INACTIVITY_PROBE},
1369 {"max-idle", required_argument, 0, OPT_MAX_IDLE},
1370 {"max-backoff", required_argument, 0, OPT_MAX_BACKOFF},
1371 {"listen", required_argument, 0, 'l'},
1372 {"rate-limit", optional_argument, 0, OPT_RATE_LIMIT},
1373 {"burst-limit", required_argument, 0, OPT_BURST_LIMIT},
1374 {"detach", no_argument, 0, 'D'},
1375 {"force", no_argument, 0, 'f'},
1376 {"pidfile", optional_argument, 0, 'P'},
1377 {"verbose", optional_argument, 0, 'v'},
1378 {"help", no_argument, 0, 'h'},
1379 {"version", no_argument, 0, 'V'},
1380 VCONN_SSL_LONG_OPTIONS
1383 char *short_options = long_options_to_short_options(long_options);
1384 char *accept_re = NULL;
1387 /* Set defaults that we can figure out before parsing options. */
1389 s->fail_mode = FAIL_OPEN;
1391 s->probe_interval = 15;
1392 s->max_backoff = 15;
1393 s->update_resolv_conf = true;
1399 c = getopt_long(argc, argv, short_options, long_options, NULL);
1405 case OPT_ACCEPT_VCONN:
1406 accept_re = optarg[0] == '^' ? optarg : xasprintf("^%s", optarg);
1409 case OPT_NO_RESOLV_CONF:
1410 s->update_resolv_conf = false;
1414 if (!strcmp(optarg, "open")) {
1415 s->fail_mode = FAIL_OPEN;
1416 } else if (!strcmp(optarg, "closed")) {
1417 s->fail_mode = FAIL_CLOSED;
1420 "-f or --fail argument must be \"open\" or \"closed\"");
1424 case OPT_INACTIVITY_PROBE:
1425 s->probe_interval = atoi(optarg);
1426 if (s->probe_interval < 5) {
1427 fatal(0, "--inactivity-probe argument must be at least 5");
1432 if (!strcmp(optarg, "permanent")) {
1433 s->max_idle = OFP_FLOW_PERMANENT;
1435 s->max_idle = atoi(optarg);
1436 if (s->max_idle < 1 || s->max_idle > 65535) {
1437 fatal(0, "--max-idle argument must be between 1 and "
1438 "65535 or the word 'permanent'");
1443 case OPT_MAX_BACKOFF:
1444 s->max_backoff = atoi(optarg);
1445 if (s->max_backoff < 1) {
1446 fatal(0, "--max-backoff argument must be at least 1");
1447 } else if (s->max_backoff > 3600) {
1448 s->max_backoff = 3600;
1452 case OPT_RATE_LIMIT:
1454 s->rate_limit = atoi(optarg);
1455 if (s->rate_limit < 1) {
1456 fatal(0, "--rate-limit argument must be at least 1");
1459 s->rate_limit = 1000;
1463 case OPT_BURST_LIMIT:
1464 s->burst_limit = atoi(optarg);
1465 if (s->burst_limit < 1) {
1466 fatal(0, "--burst-limit argument must be at least 1");
1475 set_pidfile(optarg);
1479 ignore_existing_pidfile();
1483 if (s->n_listeners >= MAX_MGMT) {
1484 fatal(0, "-l or --listen may be specified at most %d times",
1487 s->listener_names[s->n_listeners++] = optarg;
1494 printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
1498 vlog_set_verbosity(optarg);
1501 VCONN_SSL_OPTION_HANDLERS
1510 free(short_options);
1514 if (argc < 1 || argc > 2) {
1515 fatal(0, "need one or two non-option arguments; use --help for usage");
1518 /* Local and remote vconns. */
1519 s->nl_name = argv[0];
1520 if (strncmp(s->nl_name, "nl:", 3)
1521 || strlen(s->nl_name) < 4
1522 || s->nl_name[strspn(s->nl_name + 3, "0123456789") + 3]) {
1523 fatal(0, "%s: argument is not of the form \"nl:DP_IDX\"", s->nl_name);
1525 s->of_name = xasprintf("of%s", s->nl_name + 3);
1526 s->controller_name = argc > 1 ? xstrdup(argv[1]) : NULL;
1528 /* Set accept_controller_regex. */
1530 accept_re = vconn_ssl_is_configured() ? "^ssl:.*" : ".*";
1532 retval = regcomp(&s->accept_controller_regex, accept_re,
1533 REG_NOSUB | REG_EXTENDED);
1535 size_t length = regerror(retval, &s->accept_controller_regex, NULL, 0);
1536 char *buffer = xmalloc(length);
1537 regerror(retval, &s->accept_controller_regex, buffer, length);
1538 fatal(0, "%s: %s", accept_re, buffer);
1540 s->accept_controller_re = accept_re;
1542 /* Mode of operation. */
1543 s->discovery = s->controller_name == NULL;
1547 enum netdev_flags flags;
1548 struct netdev *netdev;
1550 retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
1552 fatal(retval, "Could not open %s device", s->of_name);
1555 retval = netdev_get_flags(netdev, &flags);
1557 fatal(retval, "Could not get flags for %s device", s->of_name);
1560 s->in_band = (flags & NETDEV_UP) != 0;
1561 if (s->in_band && netdev_get_in6(netdev, NULL)) {
1562 VLOG_WARN("Ignoring IPv6 address on %s device: IPv6 not supported",
1566 netdev_close(netdev);
1569 /* Rate limiting. */
1570 if (s->rate_limit) {
1571 if (s->rate_limit < 100) {
1572 VLOG_WARN("Rate limit set to unusually low value %d",
1575 if (!s->burst_limit) {
1576 s->burst_limit = s->rate_limit / 4;
1578 s->burst_limit = MAX(s->burst_limit, 1);
1579 s->burst_limit = MIN(s->burst_limit, INT_MAX / 1000);
1586 printf("%s: secure channel, a relay for OpenFlow messages.\n"
1587 "usage: %s [OPTIONS] nl:DP_IDX [CONTROLLER]\n"
1588 "where nl:DP_IDX is a datapath that has been added with dpctl.\n"
1589 "CONTROLLER is an active OpenFlow connection method; if it is\n"
1590 "omitted, then secchan performs controller discovery.\n",
1591 program_name, program_name);
1592 vconn_usage(true, true);
1593 printf("\nController discovery options:\n"
1594 " --accept-vconn=REGEX accept matching discovered controllers\n"
1595 " --no-resolv-conf do not update /etc/resolv.conf\n"
1596 "\nNetworking options:\n"
1597 " -F, --fail=open|closed when controller connection fails:\n"
1598 " closed: drop all packets\n"
1599 " open (default): act as learning switch\n"
1600 " --inactivity-probe=SECS time between inactivity probes\n"
1601 " --max-idle=SECS max idle for flows set up by secchan\n"
1602 " --max-backoff=SECS max time between controller connection\n"
1603 " attempts (default: 15 seconds)\n"
1604 " -l, --listen=METHOD allow management connections on METHOD\n"
1605 " (a passive OpenFlow connection method)\n"
1606 "\nRate-limiting of \"packet-in\" messages to the controller:\n"
1607 " --rate-limit[=PACKETS] max rate, in packets/s (default: 1000)\n"
1608 " --burst-limit=BURST limit on packet credit for idle time\n"
1609 "\nOther options:\n"
1610 " -D, --detach run in background as daemon\n"
1611 " -P, --pidfile[=FILE] create pidfile (default: %s/secchan.pid)\n"
1612 " -f, --force with -P, start even if already running\n"
1613 " -v, --verbose=MODULE[:FACILITY[:LEVEL]] set logging levels\n"
1614 " -v, --verbose set maximum verbosity level\n"
1615 " -h, --help display this help message\n"
1616 " -V, --version display version information\n",