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 /* Settings that may be configured by the user. */
82 /* Overall mode of operation. */
83 bool discovery; /* Discover the controller automatically? */
84 bool in_band; /* Connect to controller in-band? */
86 /* Related vconns and network devices. */
87 const char *nl_name; /* Local datapath (must be "nl:" vconn). */
88 char *of_name; /* ofX network device name. */
89 const char *controller_name; /* Controller (if not discovery mode). */
90 const char *listen_vconn_name; /* Listens for mgmt connections. */
92 /* Failure behavior. */
93 enum fail_mode fail_mode; /* Act as learning switch if no controller? */
94 int max_idle; /* Idle time for flows in fail-open mode. */
95 int probe_interval; /* # seconds idle before sending echo request. */
96 int max_backoff; /* Max # seconds between connection attempts. */
98 /* Packet-in rate-limiting. */
99 int rate_limit; /* Tokens added to bucket per second. */
100 int burst_limit; /* Maximum number token bucket size. */
102 /* Discovery behavior. */
103 regex_t accept_controller_regex; /* Controller vconns to accept. */
104 const char *accept_controller_re; /* String version of regex. */
105 bool update_resolv_conf; /* Update /etc/resolv.conf? */
110 struct buffer *rxbuf;
111 int n_txq; /* No. of packets queued for tx on 'rconn'. */
118 #define HALF_REMOTE 1
119 struct half halves[2];
125 bool (*packet_cb)(struct relay *, int half, void *aux);
126 void (*periodic_cb)(void *aux);
127 void (*wait_cb)(void *aux);
131 static void parse_options(int argc, char *argv[], struct settings *);
132 static void usage(void) NO_RETURN;
134 static struct relay *relay_create(struct rconn *local, struct rconn *remote,
136 static struct relay *relay_accept(const struct settings *, struct vconn *);
137 static void relay_run(struct relay *, const struct hook[], size_t n_hooks);
138 static void relay_wait(struct relay *);
139 static void relay_destroy(struct relay *);
141 static struct hook make_hook(bool (*packet_cb)(struct relay *, int, void *),
142 void (*periodic_cb)(void *),
143 void (*wait_cb)(void *),
146 static struct discovery *discovery_init(const struct settings *);
147 static void discovery_question_connectivity(struct discovery *);
148 static bool discovery_run(struct discovery *, char **controller_name);
149 static void discovery_wait(struct discovery *);
151 static struct hook in_band_hook_create(const struct settings *);
152 static struct hook fail_open_hook_create(const struct settings *,
154 struct rconn *remote);
155 static struct hook rate_limit_hook_create(const struct settings *,
157 struct rconn *remote);
159 static void modify_dhcp_request(struct dhcp_msg *, void *aux);
160 static bool validate_dhcp_offer(const struct dhcp_msg *, void *aux);
163 main(int argc, char *argv[])
167 struct list relays = LIST_INITIALIZER(&relays);
169 struct hook hooks[4];
172 struct rconn *local_rconn, *remote_rconn;
173 struct vconn *listen_vconn;
174 struct relay *controller_relay;
175 struct discovery *discovery;
178 set_program_name(argv[0]);
179 register_fault_handlers();
182 parse_options(argc, argv, &s);
183 signal(SIGPIPE, SIG_IGN);
185 /* Start listening for management connections. */
186 if (s.listen_vconn_name) {
187 retval = vconn_open(s.listen_vconn_name, &listen_vconn);
188 if (retval && retval != EAGAIN) {
189 fatal(retval, "opening %s", s.listen_vconn_name);
191 if (!vconn_is_passive(listen_vconn)) {
192 fatal(0, "%s is not a passive vconn", s.listen_vconn_name);
198 /* Start controller discovery. */
199 discovery = s.discovery ? discovery_init(&s) : NULL;
201 /* Start listening for vlogconf requests. */
202 retval = vlog_server_listen(NULL, NULL);
204 fatal(retval, "Could not listen for vlog connections");
209 VLOG_WARN("OpenFlow reference implementation version %s", VERSION);
210 VLOG_WARN("OpenFlow protocol version 0x%02x", OFP_VERSION);
212 /* Connect to datapath. */
213 local_rconn = rconn_create(0, s.max_backoff);
214 rconn_connect(local_rconn, s.nl_name);
216 /* Connect to controller. */
217 remote_rconn = rconn_create(s.probe_interval, s.max_backoff);
218 if (s.controller_name) {
219 retval = rconn_connect(remote_rconn, s.controller_name);
220 if (retval == EAFNOSUPPORT) {
221 fatal(0, "No support for %s vconn", s.controller_name);
225 /* Start relaying. */
226 controller_relay = relay_create(local_rconn, remote_rconn, false);
227 list_push_back(&relays, &controller_relay->node);
232 hooks[n_hooks++] = in_band_hook_create(&s);
234 if (s.fail_mode == FAIL_OPEN) {
235 hooks[n_hooks++] = fail_open_hook_create(&s,
236 local_rconn, remote_rconn);
239 hooks[n_hooks++] = rate_limit_hook_create(&s,
240 local_rconn, remote_rconn);
242 assert(n_hooks <= ARRAY_SIZE(hooks));
249 LIST_FOR_EACH_SAFE (r, n, struct relay, node, &relays) {
250 relay_run(r, hooks, n_hooks);
254 struct relay *r = relay_accept(&s, listen_vconn);
258 list_push_back(&relays, &r->node);
261 for (i = 0; i < n_hooks; i++) {
262 if (hooks[i].periodic_cb) {
263 hooks[i].periodic_cb(hooks[i].aux);
267 char *controller_name;
268 if (rconn_is_connectivity_questionable(remote_rconn)) {
269 discovery_question_connectivity(discovery);
271 if (discovery_run(discovery, &controller_name)) {
272 if (controller_name) {
273 rconn_connect(remote_rconn, controller_name);
275 rconn_disconnect(remote_rconn);
280 /* Wait for something to happen. */
281 LIST_FOR_EACH (r, struct relay, node, &relays) {
285 vconn_accept_wait(listen_vconn);
287 for (i = 0; i < n_hooks; i++) {
288 if (hooks[i].wait_cb) {
289 hooks[i].wait_cb(hooks[i].aux);
293 discovery_wait(discovery);
302 make_hook(bool (*packet_cb)(struct relay *, int half, void *aux),
303 void (*periodic_cb)(void *aux),
304 void (*wait_cb)(void *aux),
308 h.packet_cb = packet_cb;
309 h.periodic_cb = periodic_cb;
315 /* OpenFlow message relaying. */
317 static struct relay *
318 relay_accept(const struct settings *s, struct vconn *listen_vconn)
320 struct vconn *new_remote, *new_local;
321 char *nl_name_without_subscription;
322 struct rconn *r1, *r2;
325 retval = vconn_accept(listen_vconn, &new_remote);
327 if (retval != EAGAIN) {
328 VLOG_WARN("accept failed (%s)", strerror(retval));
333 /* nl:123 or nl:123:1 opens a netlink connection to local datapath 123. We
334 * only accept the former syntax in main().
336 * nl:123:0 opens a netlink connection to local datapath 123 without
337 * obtaining a subscription for ofp_packet_in or ofp_flow_expired
339 nl_name_without_subscription = xasprintf("%s:0", s->nl_name);
340 retval = vconn_open(nl_name_without_subscription, &new_local);
342 VLOG_ERR("could not connect to %s (%s)",
343 nl_name_without_subscription, strerror(retval));
344 vconn_close(new_remote);
345 free(nl_name_without_subscription);
349 /* Create and return relay. */
350 r1 = rconn_create(0, 0);
351 rconn_connect_unreliably(r1, nl_name_without_subscription, new_local);
352 free(nl_name_without_subscription);
354 r2 = rconn_create(0, 0);
355 rconn_connect_unreliably(r2, "passive", new_remote);
357 return relay_create(r1, r2, true);
360 static struct relay *
361 relay_create(struct rconn *local, struct rconn *remote, bool is_mgmt_conn)
363 struct relay *r = xcalloc(1, sizeof *r);
364 r->halves[HALF_LOCAL].rconn = local;
365 r->halves[HALF_REMOTE].rconn = remote;
366 r->is_mgmt_conn = is_mgmt_conn;
371 relay_run(struct relay *r, const struct hook hooks[], size_t n_hooks)
376 for (i = 0; i < 2; i++) {
377 rconn_run(r->halves[i].rconn);
380 /* Limit the number of iterations to prevent other tasks from starving. */
381 for (iteration = 0; iteration < 50; iteration++) {
382 bool progress = false;
383 for (i = 0; i < 2; i++) {
384 struct half *this = &r->halves[i];
385 struct half *peer = &r->halves[!i];
388 this->rxbuf = rconn_recv(this->rconn);
390 const struct hook *h;
391 for (h = hooks; h < &hooks[n_hooks]; h++) {
392 if (h->packet_cb(r, i, h->aux)) {
393 buffer_delete(this->rxbuf);
402 if (this->rxbuf && !this->n_txq) {
403 int retval = rconn_send(peer->rconn, this->rxbuf,
405 if (retval != EAGAIN) {
409 buffer_delete(this->rxbuf);
420 if (r->is_mgmt_conn) {
421 for (i = 0; i < 2; i++) {
422 struct half *this = &r->halves[i];
423 if (!rconn_is_alive(this->rconn)) {
432 relay_wait(struct relay *r)
436 for (i = 0; i < 2; i++) {
437 struct half *this = &r->halves[i];
439 rconn_run_wait(this->rconn);
441 rconn_recv_wait(this->rconn);
447 relay_destroy(struct relay *r)
451 list_remove(&r->node);
452 for (i = 0; i < 2; i++) {
453 struct half *this = &r->halves[i];
454 rconn_destroy(this->rconn);
455 buffer_delete(this->rxbuf);
460 /* In-band control. */
462 struct in_band_data {
463 const struct settings *s;
464 struct mac_learning *ml;
465 struct netdev *of_device;
466 uint8_t mac[ETH_ADDR_LEN];
471 queue_tx(struct rconn *rc, struct in_band_data *in_band, struct buffer *b)
473 rconn_send_with_limit(rc, b, &in_band->n_queued, 10);
476 static const uint8_t *
477 get_controller_mac(struct netdev *netdev, struct rconn *controller)
479 static uint32_t ip, last_nonzero_ip;
480 static uint8_t mac[ETH_ADDR_LEN], last_nonzero_mac[ETH_ADDR_LEN];
481 static time_t next_refresh = 0;
483 uint32_t last_ip = ip;
485 time_t now = time_now();
487 ip = rconn_get_ip(controller);
488 if (last_ip != ip || !next_refresh || now >= next_refresh) {
491 /* Look up MAC address. */
492 memset(mac, 0, sizeof mac);
494 int retval = netdev_arp_lookup(netdev, ip, mac);
496 VLOG_DBG("cannot look up controller hw address ("IP_FMT"): %s",
497 IP_ARGS(&ip), strerror(retval));
500 have_mac = !eth_addr_is_zero(mac);
502 /* Log changes in IP, MAC addresses. */
503 if (ip && ip != last_nonzero_ip) {
504 VLOG_DBG("controller IP address changed from "IP_FMT
505 " to "IP_FMT, IP_ARGS(&last_nonzero_ip), IP_ARGS(&ip));
506 last_nonzero_ip = ip;
508 if (have_mac && memcmp(last_nonzero_mac, mac, ETH_ADDR_LEN)) {
509 VLOG_DBG("controller MAC address changed from "ETH_ADDR_FMT" to "
511 ETH_ADDR_ARGS(last_nonzero_mac), ETH_ADDR_ARGS(mac));
512 memcpy(last_nonzero_mac, mac, ETH_ADDR_LEN);
515 /* Schedule next refresh.
517 * If we have an IP address but not a MAC address, then refresh
518 * quickly, since we probably will get a MAC address soon (via ARP).
519 * Otherwise, we can afford to wait a little while. */
520 next_refresh = now + (!ip || have_mac ? 10 : 1);
522 return !eth_addr_is_zero(mac) ? mac : NULL;
526 is_controller_mac(const uint8_t mac[ETH_ADDR_LEN],
527 const uint8_t *controller_mac)
529 return controller_mac && eth_addr_equals(mac, controller_mac);
533 in_band_packet_cb(struct relay *r, int half, void *in_band_)
535 struct in_band_data *in_band = in_band_;
536 struct rconn *rc = r->halves[HALF_LOCAL].rconn;
537 struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
538 struct ofp_packet_in *opi;
539 struct ofp_header *oh;
540 size_t pkt_ofs, pkt_len;
543 uint16_t in_port, out_port;
544 const uint8_t *controller_mac;
546 if (half != HALF_LOCAL || r->is_mgmt_conn) {
551 if (oh->type != OFPT_PACKET_IN) {
554 if (msg->size < offsetof (struct ofp_packet_in, data)) {
555 VLOG_WARN("packet too short (%zu bytes) for packet_in", msg->size);
559 /* Extract flow data from 'opi' into 'flow'. */
561 in_port = ntohs(opi->in_port);
562 pkt_ofs = offsetof(struct ofp_packet_in, data);
563 pkt_len = ntohs(opi->header.length) - pkt_ofs;
564 pkt.data = opi->data;
566 flow_extract(&pkt, in_port, &flow);
568 /* Deal with local stuff. */
569 controller_mac = get_controller_mac(in_band->of_device,
570 r->halves[HALF_REMOTE].rconn);
571 if (in_port == OFPP_LOCAL) {
572 /* Sent by secure channel. */
573 out_port = mac_learning_lookup(in_band->ml, flow.dl_dst);
574 } else if (eth_addr_equals(flow.dl_dst, in_band->mac)) {
575 /* Sent to secure channel. */
576 out_port = OFPP_LOCAL;
577 if (mac_learning_learn(in_band->ml, flow.dl_src, in_port)) {
578 VLOG_DBG("learned that "ETH_ADDR_FMT" is on port %"PRIu16,
579 ETH_ADDR_ARGS(flow.dl_src), in_port);
581 } else if (flow.dl_type == htons(ETH_TYPE_ARP)
582 && eth_addr_is_broadcast(flow.dl_dst)
583 && is_controller_mac(flow.dl_src, controller_mac)) {
584 /* ARP sent by controller. */
585 out_port = OFPP_FLOOD;
586 } else if (is_controller_mac(flow.dl_dst, controller_mac)
587 && in_port == mac_learning_lookup(in_band->ml,
589 /* Drop controller traffic that arrives on the controller port. */
590 queue_tx(rc, in_band, make_add_flow(&flow, ntohl(opi->buffer_id),
591 in_band->s->max_idle, 0));
597 if (out_port != OFPP_FLOOD) {
598 /* The output port is known, so add a new flow. */
599 queue_tx(rc, in_band,
600 make_add_simple_flow(&flow, ntohl(opi->buffer_id),
601 out_port, in_band->s->max_idle));
603 /* If the switch didn't buffer the packet, we need to send a copy. */
604 if (ntohl(opi->buffer_id) == UINT32_MAX) {
605 queue_tx(rc, in_band,
606 make_unbuffered_packet_out(&pkt, in_port, out_port));
609 /* We don't know that MAC. Send along the packet without setting up a
612 if (ntohl(opi->buffer_id) == UINT32_MAX) {
613 b = make_unbuffered_packet_out(&pkt, in_port, out_port);
615 b = make_buffered_packet_out(ntohl(opi->buffer_id),
618 queue_tx(rc, in_band, b);
624 in_band_hook_create(const struct settings *s)
626 struct in_band_data *in_band;
629 in_band = xcalloc(1, sizeof *in_band);
631 in_band->ml = mac_learning_create();
632 retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE,
633 &in_band->of_device);
635 fatal(retval, "Could not open %s device", s->of_name);
637 memcpy(in_band->mac, netdev_get_etheraddr(in_band->of_device),
640 return make_hook(in_band_packet_cb, NULL, NULL, in_band);
643 /* Fail open support. */
645 struct fail_open_data {
646 const struct settings *s;
647 struct rconn *local_rconn;
648 struct rconn *remote_rconn;
649 struct lswitch *lswitch;
650 int last_disconn_secs;
653 /* Causes 'r' to enter or leave fail-open mode, if appropriate. */
655 fail_open_periodic_cb(void *fail_open_)
657 struct fail_open_data *fail_open = fail_open_;
661 disconn_secs = rconn_disconnected_duration(fail_open->remote_rconn);
662 open = disconn_secs >= fail_open->s->probe_interval * 3;
663 if (open != (fail_open->lswitch != NULL)) {
665 VLOG_WARN("No longer in fail-open mode");
666 lswitch_destroy(fail_open->lswitch);
667 fail_open->lswitch = NULL;
669 VLOG_WARN("Could not connect to controller for %d seconds, "
670 "failing open", disconn_secs);
671 fail_open->lswitch = lswitch_create(fail_open->local_rconn, true,
672 fail_open->s->max_idle);
673 fail_open->last_disconn_secs = disconn_secs;
675 } else if (open && disconn_secs > fail_open->last_disconn_secs + 60) {
676 VLOG_WARN("Still in fail-open mode after %d seconds disconnected "
677 "from controller", disconn_secs);
678 fail_open->last_disconn_secs = disconn_secs;
683 fail_open_packet_cb(struct relay *r, int half, void *fail_open_)
685 struct fail_open_data *fail_open = fail_open_;
686 if (half != HALF_LOCAL || r->is_mgmt_conn || !fail_open->lswitch) {
689 lswitch_process_packet(fail_open->lswitch, fail_open->local_rconn,
690 r->halves[HALF_LOCAL].rxbuf);
691 rconn_run(fail_open->local_rconn);
697 fail_open_hook_create(const struct settings *s, struct rconn *local_rconn,
698 struct rconn *remote_rconn)
700 struct fail_open_data *fail_open = xmalloc(sizeof *fail_open);
702 fail_open->local_rconn = local_rconn;
703 fail_open->remote_rconn = remote_rconn;
704 fail_open->lswitch = NULL;
705 return make_hook(fail_open_packet_cb, fail_open_periodic_cb, NULL,
709 struct rate_limiter {
710 const struct settings *s;
711 struct rconn *remote_rconn;
713 /* One queue per physical port. */
714 struct queue queues[OFPP_MAX];
715 int n_queued; /* Sum over queues[*].n. */
716 int next_tx_port; /* Next port to check in round-robin. */
720 * It costs 1000 tokens to send a single packet_in message. A single token
721 * per message would be more straightforward, but this choice lets us avoid
722 * round-off error in refill_bucket()'s calculation of how many tokens to
723 * add to the bucket, since no division step is needed. */
724 long long int last_fill; /* Time at which we last added tokens. */
725 int tokens; /* Current number of tokens. */
727 /* Transmission queue. */
728 int n_txq; /* No. of packets waiting in rconn for tx. */
731 /* Drop a packet from the longest queue in 'rl'. */
733 drop_packet(struct rate_limiter *rl)
735 struct queue *longest; /* Queue currently selected as longest. */
736 int n_longest; /* # of queues of same length as 'longest'. */
739 longest = &rl->queues[0];
741 for (q = &rl->queues[0]; q < &rl->queues[OFPP_MAX]; q++) {
742 if (longest->n < q->n) {
745 } else if (longest->n == q->n) {
748 /* Randomly select one of the longest queues, with a uniform
749 * distribution (Knuth algorithm 3.4.2R). */
750 if (!random_range(n_longest)) {
756 /* FIXME: do we want to pop the tail instead? */
757 buffer_delete(queue_pop_head(longest));
761 /* Remove and return the next packet to transmit (in round-robin order). */
762 static struct buffer *
763 dequeue_packet(struct rate_limiter *rl)
767 for (i = 0; i < OFPP_MAX; i++) {
768 unsigned int port = (rl->next_tx_port + i) % OFPP_MAX;
769 struct queue *q = &rl->queues[port];
771 rl->next_tx_port = (port + 1) % OFPP_MAX;
773 return queue_pop_head(q);
779 /* Add tokens to the bucket based on elapsed time. */
781 refill_bucket(struct rate_limiter *rl)
783 const struct settings *s = rl->s;
784 long long int now = time_msec();
785 long long int tokens = (now - rl->last_fill) * s->rate_limit + rl->tokens;
786 if (tokens >= 1000) {
788 rl->tokens = MIN(tokens, s->burst_limit * 1000);
792 /* Attempts to remove enough tokens from 'rl' to transmit a packet. Returns
793 * true if successful, false otherwise. (In the latter case no tokens are
796 get_token(struct rate_limiter *rl)
798 if (rl->tokens >= 1000) {
807 rate_limit_packet_cb(struct relay *r, int half, void *rl_)
809 struct rate_limiter *rl = rl_;
810 const struct settings *s = rl->s;
811 struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
812 struct ofp_header *oh;
814 if (half == HALF_REMOTE) {
819 if (oh->type != OFPT_PACKET_IN) {
822 if (msg->size < offsetof(struct ofp_packet_in, data)) {
823 VLOG_WARN("packet too short (%zu bytes) for packet_in", msg->size);
827 if (!rl->n_queued && get_token(rl)) {
828 /* In the common case where we are not constrained by the rate limit,
829 * let the packet take the normal path. */
832 /* Otherwise queue it up for the periodic callback to drain out. */
833 struct ofp_packet_in *opi = msg->data;
834 int port = ntohs(opi->in_port) % OFPP_MAX;
835 if (rl->n_queued >= s->burst_limit) {
838 queue_push_tail(&rl->queues[port], buffer_clone(msg));
845 rate_limit_periodic_cb(void *rl_)
847 struct rate_limiter *rl = rl_;
850 /* Drain some packets out of the bucket if possible, but limit the number
851 * of iterations to allow other code to get work done too. */
853 for (i = 0; rl->n_queued && get_token(rl) && i < 50; i++) {
854 /* Use a small, arbitrary limit for the amount of queuing to do here,
855 * because the TCP connection is responsible for buffering and there is
856 * no point in trying to transmit faster than the TCP connection can
858 struct buffer *b = dequeue_packet(rl);
859 rconn_send_with_limit(rl->remote_rconn, b, &rl->n_txq, 10);
864 rate_limit_wait_cb(void *rl_)
866 struct rate_limiter *rl = rl_;
868 if (rl->tokens >= 1000) {
869 /* We can transmit more packets as soon as we're called again. */
870 poll_immediate_wake();
872 /* We have to wait for the bucket to re-fill. We could calculate
873 * the exact amount of time here for increased smoothness. */
874 poll_timer_wait(TIME_UPDATE_INTERVAL / 2);
880 rate_limit_hook_create(const struct settings *s,
882 struct rconn *remote)
884 struct rate_limiter *rl;
887 rl = xcalloc(1, sizeof *rl);
889 rl->remote_rconn = remote;
890 for (i = 0; i < ARRAY_SIZE(rl->queues); i++) {
891 queue_init(&rl->queues[i]);
893 rl->last_fill = time_msec();
894 rl->tokens = s->rate_limit * 100;
895 return make_hook(rate_limit_packet_cb, rate_limit_periodic_cb,
896 rate_limit_wait_cb, rl);
899 /* Controller discovery. */
903 const struct settings *s;
904 struct dhclient *dhcp;
905 bool ever_successful;
908 static struct discovery *
909 discovery_init(const struct settings *s)
911 struct netdev *netdev;
913 struct dhclient *dhcp;
916 /* Bring ofX network device up. */
917 retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
919 fatal(retval, "Could not open %s device", s->of_name);
921 retval = netdev_turn_flags_on(netdev, NETDEV_UP, true);
923 fatal(retval, "Could not bring %s device up", s->of_name);
925 netdev_close(netdev);
927 /* Initialize DHCP client. */
928 retval = dhclient_create(s->of_name, modify_dhcp_request,
929 validate_dhcp_offer, (void *) s, &dhcp);
931 fatal(retval, "Failed to initialize DHCP client");
933 dhclient_init(dhcp, 0);
935 d = xmalloc(sizeof *d);
938 d->ever_successful = false;
943 discovery_question_connectivity(struct discovery *d)
945 dhclient_force_renew(d->dhcp, 15);
949 discovery_run(struct discovery *d, char **controller_name)
951 dhclient_run(d->dhcp);
952 if (!dhclient_changed(d->dhcp)) {
956 dhclient_configure_netdev(d->dhcp);
957 if (d->s->update_resolv_conf) {
958 dhclient_update_resolv_conf(d->dhcp);
961 if (dhclient_is_bound(d->dhcp)) {
962 *controller_name = dhcp_msg_get_string(dhclient_get_config(d->dhcp),
963 DHCP_CODE_OFP_CONTROLLER_VCONN);
964 VLOG_WARN("%s: discovered controller", *controller_name);
965 d->ever_successful = true;
966 } else if (controller_name) {
967 *controller_name = NULL;
968 if (d->ever_successful) {
969 VLOG_WARN("discovered controller no longer available");
976 discovery_wait(struct discovery *d)
978 dhclient_wait(d->dhcp);
982 modify_dhcp_request(struct dhcp_msg *msg, void *aux)
984 dhcp_msg_put_string(msg, DHCP_CODE_VENDOR_CLASS, "OpenFlow");
988 validate_dhcp_offer(const struct dhcp_msg *msg, void *s_)
990 const struct settings *s = s_;
994 vconn_name = dhcp_msg_get_string(msg, DHCP_CODE_OFP_CONTROLLER_VCONN);
996 VLOG_WARN("rejecting DHCP offer missing controller vconn");
999 accept = !regexec(&s->accept_controller_regex, vconn_name, 0, NULL, 0);
1001 VLOG_WARN("rejecting controller vconn that fails to match %s",
1002 s->accept_controller_re);
1008 /* User interface. */
1011 parse_options(int argc, char *argv[], struct settings *s)
1014 OPT_ACCEPT_VCONN = UCHAR_MAX + 1,
1016 OPT_INACTIVITY_PROBE,
1022 static struct option long_options[] = {
1023 {"accept-vconn", required_argument, 0, OPT_ACCEPT_VCONN},
1024 {"no-resolv-conf", no_argument, 0, OPT_NO_RESOLV_CONF},
1025 {"fail", required_argument, 0, 'f'},
1026 {"inactivity-probe", required_argument, 0, OPT_INACTIVITY_PROBE},
1027 {"max-idle", required_argument, 0, OPT_MAX_IDLE},
1028 {"max-backoff", required_argument, 0, OPT_MAX_BACKOFF},
1029 {"listen", required_argument, 0, 'l'},
1030 {"rate-limit", optional_argument, 0, OPT_RATE_LIMIT},
1031 {"burst-limit", required_argument, 0, OPT_BURST_LIMIT},
1032 {"detach", no_argument, 0, 'D'},
1033 {"pidfile", optional_argument, 0, 'P'},
1034 {"verbose", optional_argument, 0, 'v'},
1035 {"help", no_argument, 0, 'h'},
1036 {"version", no_argument, 0, 'V'},
1037 VCONN_SSL_LONG_OPTIONS
1040 char *short_options = long_options_to_short_options(long_options);
1041 char *accept_re = NULL;
1044 /* Set defaults that we can figure out before parsing options. */
1045 s->listen_vconn_name = NULL;
1046 s->fail_mode = FAIL_OPEN;
1048 s->probe_interval = 15;
1049 s->max_backoff = 15;
1050 s->update_resolv_conf = true;
1056 c = getopt_long(argc, argv, short_options, long_options, NULL);
1062 case OPT_ACCEPT_VCONN:
1063 accept_re = optarg[0] == '^' ? optarg : xasprintf("^%s", optarg);
1066 case OPT_NO_RESOLV_CONF:
1067 s->update_resolv_conf = false;
1071 if (!strcmp(optarg, "open")) {
1072 s->fail_mode = FAIL_OPEN;
1073 } else if (!strcmp(optarg, "closed")) {
1074 s->fail_mode = FAIL_CLOSED;
1077 "-f or --fail argument must be \"open\" or \"closed\"");
1081 case OPT_INACTIVITY_PROBE:
1082 s->probe_interval = atoi(optarg);
1083 if (s->probe_interval < 5) {
1084 fatal(0, "--inactivity-probe argument must be at least 5");
1089 if (!strcmp(optarg, "permanent")) {
1090 s->max_idle = OFP_FLOW_PERMANENT;
1092 s->max_idle = atoi(optarg);
1093 if (s->max_idle < 1 || s->max_idle > 65535) {
1094 fatal(0, "--max-idle argument must be between 1 and "
1095 "65535 or the word 'permanent'");
1100 case OPT_MAX_BACKOFF:
1101 s->max_backoff = atoi(optarg);
1102 if (s->max_backoff < 1) {
1103 fatal(0, "--max-backoff argument must be at least 1");
1104 } else if (s->max_backoff > 3600) {
1105 s->max_backoff = 3600;
1109 case OPT_RATE_LIMIT:
1111 s->rate_limit = atoi(optarg);
1112 if (s->rate_limit < 1) {
1113 fatal(0, "--rate-limit argument must be at least 1");
1116 s->rate_limit = 1000;
1120 case OPT_BURST_LIMIT:
1121 s->burst_limit = atoi(optarg);
1122 if (s->burst_limit < 1) {
1123 fatal(0, "--burst-limit argument must be at least 1");
1132 set_pidfile(optarg);
1136 if (s->listen_vconn_name) {
1137 fatal(0, "-l or --listen may be only specified once");
1139 s->listen_vconn_name = optarg;
1146 printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
1150 vlog_set_verbosity(optarg);
1153 VCONN_SSL_OPTION_HANDLERS
1162 free(short_options);
1166 if (argc < 1 || argc > 2) {
1167 fatal(0, "need one or two non-option arguments; use --help for usage");
1170 /* Local and remote vconns. */
1171 s->nl_name = argv[0];
1172 if (strncmp(s->nl_name, "nl:", 3)
1173 || strlen(s->nl_name) < 4
1174 || s->nl_name[strspn(s->nl_name + 3, "0123456789") + 3]) {
1175 fatal(0, "%s: argument is not of the form \"nl:DP_IDX\"", s->nl_name);
1177 s->of_name = xasprintf("of%s", s->nl_name + 3);
1178 s->controller_name = argc > 1 ? xstrdup(argv[1]) : NULL;
1180 /* Set accept_controller_regex. */
1182 accept_re = vconn_ssl_is_configured() ? "^ssl:.*" : ".*";
1184 retval = regcomp(&s->accept_controller_regex, accept_re,
1185 REG_NOSUB | REG_EXTENDED);
1187 size_t length = regerror(retval, &s->accept_controller_regex, NULL, 0);
1188 char *buffer = xmalloc(length);
1189 regerror(retval, &s->accept_controller_regex, buffer, length);
1190 fatal(0, "%s: %s", accept_re, buffer);
1192 s->accept_controller_re = accept_re;
1194 /* Mode of operation. */
1195 s->discovery = s->controller_name == NULL;
1199 enum netdev_flags flags;
1200 struct netdev *netdev;
1202 retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
1204 fatal(retval, "Could not open %s device", s->of_name);
1207 retval = netdev_get_flags(netdev, &flags);
1209 fatal(retval, "Could not get flags for %s device", s->of_name);
1212 s->in_band = (flags & NETDEV_UP) != 0;
1213 if (s->in_band && netdev_get_in6(netdev, NULL)) {
1214 VLOG_WARN("Ignoring IPv6 address on %s device: IPv6 not supported",
1218 netdev_close(netdev);
1221 /* Rate limiting. */
1222 if (s->rate_limit) {
1223 if (s->rate_limit < 100) {
1224 VLOG_WARN("Rate limit set to unusually low value %d",
1227 if (!s->burst_limit) {
1228 s->burst_limit = s->rate_limit / 4;
1230 s->burst_limit = MAX(s->burst_limit, 1);
1231 s->burst_limit = MIN(s->burst_limit, INT_MAX / 1000);
1238 printf("%s: secure channel, a relay for OpenFlow messages.\n"
1239 "usage: %s [OPTIONS] nl:DP_IDX [CONTROLLER]\n"
1240 "where nl:DP_IDX is a datapath that has been added with dpctl.\n"
1241 "CONTROLLER is an active OpenFlow connection method; if it is\n"
1242 "omitted, then secchan performs controller discovery.\n",
1243 program_name, program_name);
1244 vconn_usage(true, true);
1245 printf("\nController discovery options:\n"
1246 " --accept-vconn=REGEX accept matching discovered controllers\n"
1247 " --no-resolv-conf do not update /etc/resolv.conf\n"
1248 "\nNetworking options:\n"
1249 " -f, --fail=open|closed when controller connection fails:\n"
1250 " closed: drop all packets\n"
1251 " open (default): act as learning switch\n"
1252 " --inactivity-probe=SECS time between inactivity probes\n"
1253 " --max-idle=SECS max idle for flows set up by secchan\n"
1254 " --max-backoff=SECS max time between controller connection\n"
1255 " attempts (default: 15 seconds)\n"
1256 " -l, --listen=METHOD allow management connections on METHOD\n"
1257 " (a passive OpenFlow connection method)\n"
1258 "\nRate-limiting of \"packet-in\" messages to the controller:\n"
1259 " --rate-limit[=PACKETS] max rate, in packets/s (default: 1000)\n"
1260 " --burst-limit=BURST limit on packet credit for idle time\n"
1261 "\nOther options:\n"
1262 " -D, --detach run in background as daemon\n"
1263 " -P, --pidfile[=FILE] create pidfile (default: %s/secchan.pid)\n"
1264 " -v, --verbose=MODULE[:FACILITY[:LEVEL]] set logging levels\n"
1265 " -v, --verbose set maximum verbosity level\n"
1266 " -h, --help display this help message\n"
1267 " -V, --version display version information\n",