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 /* Connect to datapath. */
210 local_rconn = rconn_create(0, s.max_backoff);
211 rconn_connect(local_rconn, s.nl_name);
213 /* Connect to controller. */
214 remote_rconn = rconn_create(s.probe_interval, s.max_backoff);
215 if (s.controller_name) {
216 retval = rconn_connect(remote_rconn, s.controller_name);
217 if (retval == EAFNOSUPPORT) {
218 fatal(0, "No support for %s vconn", s.controller_name);
222 /* Start relaying. */
223 controller_relay = relay_create(local_rconn, remote_rconn, false);
224 list_push_back(&relays, &controller_relay->node);
229 hooks[n_hooks++] = in_band_hook_create(&s);
231 if (s.fail_mode == FAIL_OPEN) {
232 hooks[n_hooks++] = fail_open_hook_create(&s,
233 local_rconn, remote_rconn);
236 hooks[n_hooks++] = rate_limit_hook_create(&s,
237 local_rconn, remote_rconn);
239 assert(n_hooks <= ARRAY_SIZE(hooks));
246 LIST_FOR_EACH_SAFE (r, n, struct relay, node, &relays) {
247 relay_run(r, hooks, n_hooks);
251 struct relay *r = relay_accept(&s, listen_vconn);
255 list_push_back(&relays, &r->node);
258 for (i = 0; i < n_hooks; i++) {
259 if (hooks[i].periodic_cb) {
260 hooks[i].periodic_cb(hooks[i].aux);
264 char *controller_name;
265 if (rconn_is_connectivity_questionable(remote_rconn)) {
266 discovery_question_connectivity(discovery);
268 if (discovery_run(discovery, &controller_name)) {
269 if (controller_name) {
270 rconn_connect(remote_rconn, controller_name);
272 rconn_disconnect(remote_rconn);
277 /* Wait for something to happen. */
278 LIST_FOR_EACH (r, struct relay, node, &relays) {
282 vconn_accept_wait(listen_vconn);
284 for (i = 0; i < n_hooks; i++) {
285 if (hooks[i].wait_cb) {
286 hooks[i].wait_cb(hooks[i].aux);
290 discovery_wait(discovery);
299 make_hook(bool (*packet_cb)(struct relay *, int half, void *aux),
300 void (*periodic_cb)(void *aux),
301 void (*wait_cb)(void *aux),
305 h.packet_cb = packet_cb;
306 h.periodic_cb = periodic_cb;
312 /* OpenFlow message relaying. */
314 static struct relay *
315 relay_accept(const struct settings *s, struct vconn *listen_vconn)
317 struct vconn *new_remote, *new_local;
318 char *nl_name_without_subscription;
319 struct rconn *r1, *r2;
322 retval = vconn_accept(listen_vconn, &new_remote);
324 if (retval != EAGAIN) {
325 VLOG_WARN("accept failed (%s)", strerror(retval));
330 /* nl:123 or nl:123:1 opens a netlink connection to local datapath 123. We
331 * only accept the former syntax in main().
333 * nl:123:0 opens a netlink connection to local datapath 123 without
334 * obtaining a subscription for ofp_packet_in or ofp_flow_expired
336 nl_name_without_subscription = xasprintf("%s:0", s->nl_name);
337 retval = vconn_open(nl_name_without_subscription, &new_local);
339 VLOG_ERR("could not connect to %s (%s)",
340 nl_name_without_subscription, strerror(retval));
341 vconn_close(new_remote);
342 free(nl_name_without_subscription);
346 /* Create and return relay. */
347 r1 = rconn_create(0, 0);
348 rconn_connect_unreliably(r1, nl_name_without_subscription, new_local);
349 free(nl_name_without_subscription);
351 r2 = rconn_create(0, 0);
352 rconn_connect_unreliably(r2, "passive", new_remote);
354 return relay_create(r1, r2, true);
357 static struct relay *
358 relay_create(struct rconn *local, struct rconn *remote, bool is_mgmt_conn)
360 struct relay *r = xcalloc(1, sizeof *r);
361 r->halves[HALF_LOCAL].rconn = local;
362 r->halves[HALF_REMOTE].rconn = remote;
363 r->is_mgmt_conn = is_mgmt_conn;
368 relay_run(struct relay *r, const struct hook hooks[], size_t n_hooks)
373 for (i = 0; i < 2; i++) {
374 rconn_run(r->halves[i].rconn);
377 /* Limit the number of iterations to prevent other tasks from starving. */
378 for (iteration = 0; iteration < 50; iteration++) {
379 bool progress = false;
380 for (i = 0; i < 2; i++) {
381 struct half *this = &r->halves[i];
382 struct half *peer = &r->halves[!i];
385 this->rxbuf = rconn_recv(this->rconn);
387 const struct hook *h;
388 for (h = hooks; h < &hooks[n_hooks]; h++) {
389 if (h->packet_cb(r, i, h->aux)) {
390 buffer_delete(this->rxbuf);
399 if (this->rxbuf && !this->n_txq) {
400 int retval = rconn_send(peer->rconn, this->rxbuf,
402 if (retval != EAGAIN) {
406 buffer_delete(this->rxbuf);
417 if (r->is_mgmt_conn) {
418 for (i = 0; i < 2; i++) {
419 struct half *this = &r->halves[i];
420 if (!rconn_is_alive(this->rconn)) {
429 relay_wait(struct relay *r)
433 for (i = 0; i < 2; i++) {
434 struct half *this = &r->halves[i];
436 rconn_run_wait(this->rconn);
438 rconn_recv_wait(this->rconn);
444 relay_destroy(struct relay *r)
448 list_remove(&r->node);
449 for (i = 0; i < 2; i++) {
450 struct half *this = &r->halves[i];
451 rconn_destroy(this->rconn);
452 buffer_delete(this->rxbuf);
457 /* In-band control. */
459 struct in_band_data {
460 const struct settings *s;
461 struct mac_learning *ml;
462 struct netdev *of_device;
463 uint8_t mac[ETH_ADDR_LEN];
468 queue_tx(struct rconn *rc, struct in_band_data *in_band, struct buffer *b)
470 rconn_send_with_limit(rc, b, &in_band->n_queued, 10);
473 static const uint8_t *
474 get_controller_mac(struct netdev *netdev, struct rconn *controller)
476 static uint32_t ip, last_nonzero_ip;
477 static uint8_t mac[ETH_ADDR_LEN], last_nonzero_mac[ETH_ADDR_LEN];
478 static time_t next_refresh = 0;
480 uint32_t last_ip = ip;
482 time_t now = time_now();
484 ip = rconn_get_ip(controller);
485 if (last_ip != ip || !next_refresh || now >= next_refresh) {
488 /* Look up MAC address. */
489 memset(mac, 0, sizeof mac);
491 int retval = netdev_arp_lookup(netdev, ip, mac);
493 VLOG_DBG("cannot look up controller hw address ("IP_FMT"): %s",
494 IP_ARGS(&ip), strerror(retval));
497 have_mac = !eth_addr_is_zero(mac);
499 /* Log changes in IP, MAC addresses. */
500 if (ip && ip != last_nonzero_ip) {
501 VLOG_DBG("controller IP address changed from "IP_FMT
502 " to "IP_FMT, IP_ARGS(&last_nonzero_ip), IP_ARGS(&ip));
503 last_nonzero_ip = ip;
505 if (have_mac && memcmp(last_nonzero_mac, mac, ETH_ADDR_LEN)) {
506 VLOG_DBG("controller MAC address changed from "ETH_ADDR_FMT" to "
508 ETH_ADDR_ARGS(last_nonzero_mac), ETH_ADDR_ARGS(mac));
509 memcpy(last_nonzero_mac, mac, ETH_ADDR_LEN);
512 /* Schedule next refresh.
514 * If we have an IP address but not a MAC address, then refresh
515 * quickly, since we probably will get a MAC address soon (via ARP).
516 * Otherwise, we can afford to wait a little while. */
517 next_refresh = now + (!ip || have_mac ? 10 : 1);
519 return !eth_addr_is_zero(mac) ? mac : NULL;
523 is_controller_mac(const uint8_t mac[ETH_ADDR_LEN],
524 const uint8_t *controller_mac)
526 return controller_mac && eth_addr_equals(mac, controller_mac);
530 in_band_packet_cb(struct relay *r, int half, void *in_band_)
532 struct in_band_data *in_band = in_band_;
533 struct rconn *rc = r->halves[HALF_LOCAL].rconn;
534 struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
535 struct ofp_packet_in *opi;
536 struct ofp_header *oh;
537 size_t pkt_ofs, pkt_len;
540 uint16_t in_port, out_port;
541 const uint8_t *controller_mac;
543 if (half != HALF_LOCAL || r->is_mgmt_conn) {
548 if (oh->type != OFPT_PACKET_IN) {
551 if (msg->size < offsetof (struct ofp_packet_in, data)) {
552 VLOG_WARN("packet too short (%zu bytes) for packet_in", msg->size);
556 /* Extract flow data from 'opi' into 'flow'. */
558 in_port = ntohs(opi->in_port);
559 pkt_ofs = offsetof(struct ofp_packet_in, data);
560 pkt_len = ntohs(opi->header.length) - pkt_ofs;
561 pkt.data = opi->data;
563 flow_extract(&pkt, in_port, &flow);
565 /* Deal with local stuff. */
566 controller_mac = get_controller_mac(in_band->of_device,
567 r->halves[HALF_REMOTE].rconn);
568 if (in_port == OFPP_LOCAL) {
569 /* Sent by secure channel. */
570 out_port = mac_learning_lookup(in_band->ml, flow.dl_dst);
571 } else if (eth_addr_equals(flow.dl_dst, in_band->mac)) {
572 /* Sent to secure channel. */
573 out_port = OFPP_LOCAL;
574 if (mac_learning_learn(in_band->ml, flow.dl_src, in_port)) {
575 VLOG_DBG("learned that "ETH_ADDR_FMT" is on port %"PRIu16,
576 ETH_ADDR_ARGS(flow.dl_src), in_port);
578 } else if (flow.dl_type == htons(ETH_TYPE_ARP)
579 && eth_addr_is_broadcast(flow.dl_dst)
580 && is_controller_mac(flow.dl_src, controller_mac)) {
581 /* ARP sent by controller. */
582 out_port = OFPP_FLOOD;
583 } else if (is_controller_mac(flow.dl_dst, controller_mac)
584 && in_port == mac_learning_lookup(in_band->ml,
586 /* Drop controller traffic that arrives on the controller port. */
587 queue_tx(rc, in_band, make_add_flow(&flow, ntohl(opi->buffer_id),
588 in_band->s->max_idle, 0));
594 if (out_port != OFPP_FLOOD) {
595 /* The output port is known, so add a new flow. */
596 queue_tx(rc, in_band,
597 make_add_simple_flow(&flow, ntohl(opi->buffer_id),
598 out_port, in_band->s->max_idle));
600 /* If the switch didn't buffer the packet, we need to send a copy. */
601 if (ntohl(opi->buffer_id) == UINT32_MAX) {
602 queue_tx(rc, in_band,
603 make_unbuffered_packet_out(&pkt, in_port, out_port));
606 /* We don't know that MAC. Send along the packet without setting up a
609 if (ntohl(opi->buffer_id) == UINT32_MAX) {
610 b = make_unbuffered_packet_out(&pkt, in_port, out_port);
612 b = make_buffered_packet_out(ntohl(opi->buffer_id),
615 queue_tx(rc, in_band, b);
621 in_band_hook_create(const struct settings *s)
623 struct in_band_data *in_band;
626 in_band = xcalloc(1, sizeof *in_band);
628 in_band->ml = mac_learning_create();
629 retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE,
630 &in_band->of_device);
632 fatal(retval, "Could not open %s device", s->of_name);
634 memcpy(in_band->mac, netdev_get_etheraddr(in_band->of_device),
637 return make_hook(in_band_packet_cb, NULL, NULL, in_band);
640 /* Fail open support. */
642 struct fail_open_data {
643 const struct settings *s;
644 struct rconn *local_rconn;
645 struct rconn *remote_rconn;
646 struct lswitch *lswitch;
647 int last_disconn_secs;
650 /* Causes 'r' to enter or leave fail-open mode, if appropriate. */
652 fail_open_periodic_cb(void *fail_open_)
654 struct fail_open_data *fail_open = fail_open_;
658 disconn_secs = rconn_disconnected_duration(fail_open->remote_rconn);
659 open = disconn_secs >= fail_open->s->probe_interval * 3;
660 if (open != (fail_open->lswitch != NULL)) {
662 VLOG_WARN("No longer in fail-open mode");
663 lswitch_destroy(fail_open->lswitch);
664 fail_open->lswitch = NULL;
666 VLOG_WARN("Could not connect to controller for %d seconds, "
667 "failing open", disconn_secs);
668 fail_open->lswitch = lswitch_create(fail_open->local_rconn, true,
669 fail_open->s->max_idle);
670 fail_open->last_disconn_secs = disconn_secs;
672 } else if (open && disconn_secs > fail_open->last_disconn_secs + 60) {
673 VLOG_WARN("Still in fail-open mode after %d seconds disconnected "
674 "from controller", disconn_secs);
675 fail_open->last_disconn_secs = disconn_secs;
680 fail_open_packet_cb(struct relay *r, int half, void *fail_open_)
682 struct fail_open_data *fail_open = fail_open_;
683 if (half != HALF_LOCAL || r->is_mgmt_conn || !fail_open->lswitch) {
686 lswitch_process_packet(fail_open->lswitch, fail_open->local_rconn,
687 r->halves[HALF_LOCAL].rxbuf);
688 rconn_run(fail_open->local_rconn);
694 fail_open_hook_create(const struct settings *s, struct rconn *local_rconn,
695 struct rconn *remote_rconn)
697 struct fail_open_data *fail_open = xmalloc(sizeof *fail_open);
699 fail_open->local_rconn = local_rconn;
700 fail_open->remote_rconn = remote_rconn;
701 fail_open->lswitch = NULL;
702 return make_hook(fail_open_packet_cb, fail_open_periodic_cb, NULL,
706 struct rate_limiter {
707 const struct settings *s;
708 struct rconn *remote_rconn;
710 /* One queue per physical port. */
711 struct queue queues[OFPP_MAX];
712 int n_queued; /* Sum over queues[*].n. */
713 int next_tx_port; /* Next port to check in round-robin. */
717 * It costs 1000 tokens to send a single packet_in message. A single token
718 * per message would be more straightforward, but this choice lets us avoid
719 * round-off error in refill_bucket()'s calculation of how many tokens to
720 * add to the bucket, since no division step is needed. */
721 long long int last_fill; /* Time at which we last added tokens. */
722 int tokens; /* Current number of tokens. */
724 /* Transmission queue. */
725 int n_txq; /* No. of packets waiting in rconn for tx. */
728 /* Drop a packet from the longest queue in 'rl'. */
730 drop_packet(struct rate_limiter *rl)
732 struct queue *longest; /* Queue currently selected as longest. */
733 int n_longest; /* # of queues of same length as 'longest'. */
736 longest = &rl->queues[0];
738 for (q = &rl->queues[0]; q < &rl->queues[OFPP_MAX]; q++) {
739 if (longest->n < q->n) {
742 } else if (longest->n == q->n) {
745 /* Randomly select one of the longest queues, with a uniform
746 * distribution (Knuth algorithm 3.4.2R). */
747 if (!random_range(n_longest)) {
753 /* FIXME: do we want to pop the tail instead? */
754 buffer_delete(queue_pop_head(longest));
758 /* Remove and return the next packet to transmit (in round-robin order). */
759 static struct buffer *
760 dequeue_packet(struct rate_limiter *rl)
764 for (i = 0; i < OFPP_MAX; i++) {
765 unsigned int port = (rl->next_tx_port + i) % OFPP_MAX;
766 struct queue *q = &rl->queues[port];
768 rl->next_tx_port = (port + 1) % OFPP_MAX;
770 return queue_pop_head(q);
776 /* Add tokens to the bucket based on elapsed time. */
778 refill_bucket(struct rate_limiter *rl)
780 const struct settings *s = rl->s;
781 long long int now = time_msec();
782 long long int tokens = (now - rl->last_fill) * s->rate_limit + rl->tokens;
783 if (tokens >= 1000) {
785 rl->tokens = MIN(tokens, s->burst_limit * 1000);
789 /* Attempts to remove enough tokens from 'rl' to transmit a packet. Returns
790 * true if successful, false otherwise. (In the latter case no tokens are
793 get_token(struct rate_limiter *rl)
795 if (rl->tokens >= 1000) {
804 rate_limit_packet_cb(struct relay *r, int half, void *rl_)
806 struct rate_limiter *rl = rl_;
807 const struct settings *s = rl->s;
808 struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
809 struct ofp_header *oh;
811 if (half == HALF_REMOTE) {
816 if (oh->type != OFPT_PACKET_IN) {
819 if (msg->size < offsetof(struct ofp_packet_in, data)) {
820 VLOG_WARN("packet too short (%zu bytes) for packet_in", msg->size);
824 if (!rl->n_queued && get_token(rl)) {
825 /* In the common case where we are not constrained by the rate limit,
826 * let the packet take the normal path. */
829 /* Otherwise queue it up for the periodic callback to drain out. */
830 struct ofp_packet_in *opi = msg->data;
831 int port = ntohs(opi->in_port) % OFPP_MAX;
832 if (rl->n_queued >= s->burst_limit) {
835 queue_push_tail(&rl->queues[port], buffer_clone(msg));
842 rate_limit_periodic_cb(void *rl_)
844 struct rate_limiter *rl = rl_;
847 /* Drain some packets out of the bucket if possible, but limit the number
848 * of iterations to allow other code to get work done too. */
850 for (i = 0; rl->n_queued && get_token(rl) && i < 50; i++) {
851 /* Use a small, arbitrary limit for the amount of queuing to do here,
852 * because the TCP connection is responsible for buffering and there is
853 * no point in trying to transmit faster than the TCP connection can
855 struct buffer *b = dequeue_packet(rl);
856 rconn_send_with_limit(rl->remote_rconn, b, &rl->n_txq, 10);
861 rate_limit_wait_cb(void *rl_)
863 struct rate_limiter *rl = rl_;
865 if (rl->tokens >= 1000) {
866 /* We can transmit more packets as soon as we're called again. */
867 poll_immediate_wake();
869 /* We have to wait for the bucket to re-fill. We could calculate
870 * the exact amount of time here for increased smoothness. */
871 poll_timer_wait(TIME_UPDATE_INTERVAL / 2);
877 rate_limit_hook_create(const struct settings *s,
879 struct rconn *remote)
881 struct rate_limiter *rl;
884 rl = xcalloc(1, sizeof *rl);
886 rl->remote_rconn = remote;
887 for (i = 0; i < ARRAY_SIZE(rl->queues); i++) {
888 queue_init(&rl->queues[i]);
890 rl->last_fill = time_msec();
891 rl->tokens = s->rate_limit * 100;
892 return make_hook(rate_limit_packet_cb, rate_limit_periodic_cb,
893 rate_limit_wait_cb, rl);
896 /* Controller discovery. */
900 const struct settings *s;
901 struct dhclient *dhcp;
902 bool ever_successful;
905 static struct discovery *
906 discovery_init(const struct settings *s)
908 struct netdev *netdev;
910 struct dhclient *dhcp;
913 /* Bring ofX network device up. */
914 retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
916 fatal(retval, "Could not open %s device", s->of_name);
918 retval = netdev_turn_flags_on(netdev, NETDEV_UP, true);
920 fatal(retval, "Could not bring %s device up", s->of_name);
922 netdev_close(netdev);
924 /* Initialize DHCP client. */
925 retval = dhclient_create(s->of_name, modify_dhcp_request,
926 validate_dhcp_offer, (void *) s, &dhcp);
928 fatal(retval, "Failed to initialize DHCP client");
930 dhclient_init(dhcp, 0);
932 d = xmalloc(sizeof *d);
935 d->ever_successful = false;
940 discovery_question_connectivity(struct discovery *d)
942 dhclient_force_renew(d->dhcp, 15);
946 discovery_run(struct discovery *d, char **controller_name)
948 dhclient_run(d->dhcp);
949 if (!dhclient_changed(d->dhcp)) {
953 dhclient_configure_netdev(d->dhcp);
954 if (d->s->update_resolv_conf) {
955 dhclient_update_resolv_conf(d->dhcp);
958 if (dhclient_is_bound(d->dhcp)) {
959 *controller_name = dhcp_msg_get_string(dhclient_get_config(d->dhcp),
960 DHCP_CODE_OFP_CONTROLLER_VCONN);
961 VLOG_WARN("%s: discovered controller", *controller_name);
962 d->ever_successful = true;
963 } else if (controller_name) {
964 *controller_name = NULL;
965 if (d->ever_successful) {
966 VLOG_WARN("discovered controller no longer available");
973 discovery_wait(struct discovery *d)
975 dhclient_wait(d->dhcp);
979 modify_dhcp_request(struct dhcp_msg *msg, void *aux)
981 dhcp_msg_put_string(msg, DHCP_CODE_VENDOR_CLASS, "OpenFlow");
985 validate_dhcp_offer(const struct dhcp_msg *msg, void *s_)
987 const struct settings *s = s_;
991 vconn_name = dhcp_msg_get_string(msg, DHCP_CODE_OFP_CONTROLLER_VCONN);
993 VLOG_WARN("rejecting DHCP offer missing controller vconn");
996 accept = !regexec(&s->accept_controller_regex, vconn_name, 0, NULL, 0);
998 VLOG_WARN("rejecting controller vconn that fails to match %s",
999 s->accept_controller_re);
1005 /* User interface. */
1008 parse_options(int argc, char *argv[], struct settings *s)
1011 OPT_ACCEPT_VCONN = UCHAR_MAX + 1,
1013 OPT_INACTIVITY_PROBE,
1019 static struct option long_options[] = {
1020 {"accept-vconn", required_argument, 0, OPT_ACCEPT_VCONN},
1021 {"no-resolv-conf", no_argument, 0, OPT_NO_RESOLV_CONF},
1022 {"fail", required_argument, 0, 'f'},
1023 {"inactivity-probe", required_argument, 0, OPT_INACTIVITY_PROBE},
1024 {"max-idle", required_argument, 0, OPT_MAX_IDLE},
1025 {"max-backoff", required_argument, 0, OPT_MAX_BACKOFF},
1026 {"listen", required_argument, 0, 'l'},
1027 {"rate-limit", optional_argument, 0, OPT_RATE_LIMIT},
1028 {"burst-limit", required_argument, 0, OPT_BURST_LIMIT},
1029 {"detach", no_argument, 0, 'D'},
1030 {"pidfile", optional_argument, 0, 'P'},
1031 {"verbose", optional_argument, 0, 'v'},
1032 {"help", no_argument, 0, 'h'},
1033 {"version", no_argument, 0, 'V'},
1034 VCONN_SSL_LONG_OPTIONS
1037 char *short_options = long_options_to_short_options(long_options);
1038 char *accept_re = NULL;
1041 /* Set defaults that we can figure out before parsing options. */
1042 s->listen_vconn_name = NULL;
1043 s->fail_mode = FAIL_OPEN;
1045 s->probe_interval = 15;
1046 s->max_backoff = 15;
1047 s->update_resolv_conf = true;
1053 c = getopt_long(argc, argv, short_options, long_options, NULL);
1059 case OPT_ACCEPT_VCONN:
1060 accept_re = optarg[0] == '^' ? optarg : xasprintf("^%s", optarg);
1063 case OPT_NO_RESOLV_CONF:
1064 s->update_resolv_conf = false;
1068 if (!strcmp(optarg, "open")) {
1069 s->fail_mode = FAIL_OPEN;
1070 } else if (!strcmp(optarg, "closed")) {
1071 s->fail_mode = FAIL_CLOSED;
1074 "-f or --fail argument must be \"open\" or \"closed\"");
1078 case OPT_INACTIVITY_PROBE:
1079 s->probe_interval = atoi(optarg);
1080 if (s->probe_interval < 5) {
1081 fatal(0, "--inactivity-probe argument must be at least 5");
1086 if (!strcmp(optarg, "permanent")) {
1087 s->max_idle = OFP_FLOW_PERMANENT;
1089 s->max_idle = atoi(optarg);
1090 if (s->max_idle < 1 || s->max_idle > 65535) {
1091 fatal(0, "--max-idle argument must be between 1 and "
1092 "65535 or the word 'permanent'");
1097 case OPT_MAX_BACKOFF:
1098 s->max_backoff = atoi(optarg);
1099 if (s->max_backoff < 1) {
1100 fatal(0, "--max-backoff argument must be at least 1");
1101 } else if (s->max_backoff > 3600) {
1102 s->max_backoff = 3600;
1106 case OPT_RATE_LIMIT:
1108 s->rate_limit = atoi(optarg);
1109 if (s->rate_limit < 1) {
1110 fatal(0, "--rate-limit argument must be at least 1");
1113 s->rate_limit = 1000;
1117 case OPT_BURST_LIMIT:
1118 s->burst_limit = atoi(optarg);
1119 if (s->burst_limit < 1) {
1120 fatal(0, "--burst-limit argument must be at least 1");
1129 set_pidfile(optarg);
1133 if (s->listen_vconn_name) {
1134 fatal(0, "-l or --listen may be only specified once");
1136 s->listen_vconn_name = optarg;
1143 printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
1147 vlog_set_verbosity(optarg);
1150 VCONN_SSL_OPTION_HANDLERS
1159 free(short_options);
1163 if (argc < 1 || argc > 2) {
1164 fatal(0, "need one or two non-option arguments; use --help for usage");
1167 /* Local and remote vconns. */
1168 s->nl_name = argv[0];
1169 if (strncmp(s->nl_name, "nl:", 3)
1170 || strlen(s->nl_name) < 4
1171 || s->nl_name[strspn(s->nl_name + 3, "0123456789") + 3]) {
1172 fatal(0, "%s: argument is not of the form \"nl:DP_IDX\"", s->nl_name);
1174 s->of_name = xasprintf("of%s", s->nl_name + 3);
1175 s->controller_name = argc > 1 ? xstrdup(argv[1]) : NULL;
1177 /* Set accept_controller_regex. */
1179 accept_re = vconn_ssl_is_configured() ? "^ssl:.*" : ".*";
1181 retval = regcomp(&s->accept_controller_regex, accept_re,
1182 REG_NOSUB | REG_EXTENDED);
1184 size_t length = regerror(retval, &s->accept_controller_regex, NULL, 0);
1185 char *buffer = xmalloc(length);
1186 regerror(retval, &s->accept_controller_regex, buffer, length);
1187 fatal(0, "%s: %s", accept_re, buffer);
1189 s->accept_controller_re = accept_re;
1191 /* Mode of operation. */
1192 s->discovery = s->controller_name == NULL;
1196 enum netdev_flags flags;
1197 struct netdev *netdev;
1199 retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
1201 fatal(retval, "Could not open %s device", s->of_name);
1204 retval = netdev_get_flags(netdev, &flags);
1206 fatal(retval, "Could not get flags for %s device", s->of_name);
1209 s->in_band = (flags & NETDEV_UP) != 0;
1210 if (s->in_band && netdev_get_in6(netdev, NULL)) {
1211 VLOG_WARN("Ignoring IPv6 address on %s device: IPv6 not supported",
1215 netdev_close(netdev);
1218 /* Rate limiting. */
1219 if (s->rate_limit) {
1220 if (s->rate_limit < 100) {
1221 VLOG_WARN("Rate limit set to unusually low value %d",
1224 if (!s->burst_limit) {
1225 s->burst_limit = s->rate_limit / 4;
1227 s->burst_limit = MAX(s->burst_limit, 1);
1228 s->burst_limit = MIN(s->burst_limit, INT_MAX / 1000);
1235 printf("%s: secure channel, a relay for OpenFlow messages.\n"
1236 "usage: %s [OPTIONS] nl:DP_IDX [CONTROLLER]\n"
1237 "where nl:DP_IDX is a datapath that has been added with dpctl.\n"
1238 "CONTROLLER is an active OpenFlow connection method; if it is\n"
1239 "omitted, then secchan performs controller discovery.\n",
1240 program_name, program_name);
1241 vconn_usage(true, true);
1242 printf("\nController discovery options:\n"
1243 " --accept-vconn=REGEX accept matching discovered controllers\n"
1244 " --no-resolv-conf do not update /etc/resolv.conf\n"
1245 "\nNetworking options:\n"
1246 " -f, --fail=open|closed when controller connection fails:\n"
1247 " closed: drop all packets\n"
1248 " open (default): act as learning switch\n"
1249 " --inactivity-probe=SECS time between inactivity probes\n"
1250 " --max-idle=SECS max idle for flows set up by secchan\n"
1251 " --max-backoff=SECS max time between controller connection\n"
1252 " attempts (default: 15 seconds)\n"
1253 " -l, --listen=METHOD allow management connections on METHOD\n"
1254 " (a passive OpenFlow connection method)\n"
1255 "\nRate-limiting of \"packet-in\" messages to the controller:\n"
1256 " --rate-limit[=PACKETS] max rate, in packets/s (default: 1000)\n"
1257 " --burst-limit=BURST limit on packet credit for idle time\n"
1258 "\nOther options:\n"
1259 " -D, --detach run in background as daemon\n"
1260 " -P, --pidfile[=FILE] create pidfile (default: %s/secchan.pid)\n"
1261 " -v, --verbose=MODULE[:FACILITY[:LEVEL]] set logging levels\n"
1262 " -v, --verbose set maximum verbosity level\n"
1263 " -h, --help display this help message\n"
1264 " -V, --version display version information\n",