1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
4 * We are making the OpenFlow specification and associated documentation
5 * (Software) available for public use and benefit with the expectation
6 * that others will use, modify and enhance the Software and contribute
7 * those enhancements back to the community. However, since we would
8 * like to make the Software available for broadest use, with as few
9 * restrictions as possible permission is hereby granted, free of
10 * charge, to any person obtaining a copy of this Software to deal in
11 * the Software under the copyrights without restriction, including
12 * without limitation the rights to use, copy, modify, merge, publish,
13 * distribute, sublicense, and/or sell copies of the Software, and to
14 * permit persons to whom the Software is furnished to do so, subject to
15 * the following conditions:
17 * The above copyright notice and this permission notice shall be
18 * included in all copies or substantial portions of the Software.
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 * The name and trademarks of copyright holder(s) may NOT be used in
30 * advertising or publicity pertaining to the Software or any
31 * derivatives without specific, written prior permission.
39 #include <netinet/in.h>
48 #include "command-line.h"
52 #include "dhcp-client.h"
53 #include "dynamic-string.h"
56 #include "learning-switch.h"
58 #include "mac-learning.h"
62 #include "poll-loop.h"
66 #include "vconn-ssl.h"
68 #include "vlog-socket.h"
71 #define THIS_MODULE VLM_secchan
73 /* Behavior when the connection to the controller fails. */
75 FAIL_OPEN, /* Act as learning switch. */
76 FAIL_CLOSED /* Drop all packets. */
79 /* Settings that may be configured by the user. */
81 /* Overall mode of operation. */
82 bool discovery; /* Discover the controller automatically? */
83 bool in_band; /* Connect to controller in-band? */
85 /* Related vconns and network devices. */
86 const char *nl_name; /* Local datapath (must be "nl:" vconn). */
87 char *of_name; /* ofX network device name. */
88 const char *controller_name; /* Controller (if not discovery mode). */
89 const char *listen_vconn_name; /* Listens for mgmt connections. */
91 /* Failure behavior. */
92 enum fail_mode fail_mode; /* Act as learning switch if no controller? */
93 int max_idle; /* Idle time for flows in fail-open mode. */
94 int probe_interval; /* # seconds idle before sending echo request. */
95 int max_backoff; /* Max # seconds between connection attempts. */
97 /* Packet-in rate-limiting. */
98 int rate_limit; /* Tokens added to bucket per second. */
99 int burst_limit; /* Maximum number token bucket size. */
101 /* Discovery behavior. */
102 regex_t accept_controller_regex; /* Controller vconns to accept. */
103 const char *accept_controller_re; /* String version of regex. */
104 bool update_resolv_conf; /* Update /etc/resolv.conf? */
109 struct buffer *rxbuf;
110 int n_txq; /* No. of packets queued for tx on 'rconn'. */
117 #define HALF_REMOTE 1
118 struct half halves[2];
124 bool (*packet_cb)(struct relay *, int half, void *aux);
125 void (*periodic_cb)(void *aux);
126 void (*wait_cb)(void *aux);
130 static void parse_options(int argc, char *argv[], struct settings *);
131 static void usage(void) NO_RETURN;
133 static struct relay *relay_create(struct rconn *local, struct rconn *remote,
135 static struct relay *relay_accept(const struct settings *, struct vconn *);
136 static void relay_run(struct relay *, const struct hook[], size_t n_hooks);
137 static void relay_wait(struct relay *);
138 static void relay_destroy(struct relay *);
140 static struct hook make_hook(bool (*packet_cb)(struct relay *, int, void *),
141 void (*periodic_cb)(void *),
142 void (*wait_cb)(void *),
145 static struct discovery *discovery_init(const struct settings *);
146 static void discovery_question_connectivity(struct discovery *);
147 static bool discovery_run(struct discovery *, char **controller_name);
148 static void discovery_wait(struct discovery *);
150 static struct hook in_band_hook_create(const struct settings *);
151 static struct hook fail_open_hook_create(const struct settings *,
153 struct rconn *remote);
154 static struct hook rate_limit_hook_create(const struct settings *,
156 struct rconn *remote);
158 static void modify_dhcp_request(struct dhcp_msg *, void *aux);
159 static bool validate_dhcp_offer(const struct dhcp_msg *, void *aux);
162 main(int argc, char *argv[])
166 struct list relays = LIST_INITIALIZER(&relays);
168 struct hook hooks[4];
171 struct rconn *local_rconn, *remote_rconn;
172 struct vconn *listen_vconn;
173 struct relay *controller_relay;
174 struct discovery *discovery;
177 set_program_name(argv[0]);
178 register_fault_handlers();
181 parse_options(argc, argv, &s);
183 /* Start listening for management connections. */
184 if (s.listen_vconn_name) {
185 retval = vconn_open(s.listen_vconn_name, &listen_vconn);
186 if (retval && retval != EAGAIN) {
187 fatal(retval, "opening %s", s.listen_vconn_name);
189 if (!vconn_is_passive(listen_vconn)) {
190 fatal(0, "%s is not a passive vconn", s.listen_vconn_name);
196 /* Start controller discovery. */
197 discovery = s.discovery ? discovery_init(&s) : NULL;
199 /* Start listening for vlogconf requests. */
200 retval = vlog_server_listen(NULL, NULL);
202 fatal(retval, "Could not listen for vlog connections");
207 /* Connect to datapath. */
208 local_rconn = rconn_create(0, s.max_backoff);
209 rconn_connect(local_rconn, s.nl_name);
211 /* Connect to controller. */
212 remote_rconn = rconn_create(s.probe_interval, s.max_backoff);
213 if (s.controller_name) {
214 retval = rconn_connect(remote_rconn, s.controller_name);
215 if (retval == EAFNOSUPPORT) {
216 fatal(0, "No support for %s vconn", s.controller_name);
220 /* Start relaying. */
221 controller_relay = relay_create(local_rconn, remote_rconn, false);
222 list_push_back(&relays, &controller_relay->node);
227 hooks[n_hooks++] = in_band_hook_create(&s);
229 if (s.fail_mode == FAIL_OPEN) {
230 hooks[n_hooks++] = fail_open_hook_create(&s,
231 local_rconn, remote_rconn);
234 hooks[n_hooks++] = rate_limit_hook_create(&s,
235 local_rconn, remote_rconn);
237 assert(n_hooks <= ARRAY_SIZE(hooks));
244 LIST_FOR_EACH_SAFE (r, n, struct relay, node, &relays) {
245 relay_run(r, hooks, n_hooks);
249 struct relay *r = relay_accept(&s, listen_vconn);
253 list_push_back(&relays, &r->node);
256 for (i = 0; i < n_hooks; i++) {
257 if (hooks[i].periodic_cb) {
258 hooks[i].periodic_cb(hooks[i].aux);
262 char *controller_name;
263 if (rconn_is_connectivity_questionable(remote_rconn)) {
264 discovery_question_connectivity(discovery);
266 if (discovery_run(discovery, &controller_name)) {
267 if (controller_name) {
268 rconn_connect(remote_rconn, controller_name);
270 rconn_disconnect(remote_rconn);
275 /* Wait for something to happen. */
276 LIST_FOR_EACH (r, struct relay, node, &relays) {
280 vconn_accept_wait(listen_vconn);
282 for (i = 0; i < n_hooks; i++) {
283 if (hooks[i].wait_cb) {
284 hooks[i].wait_cb(hooks[i].aux);
288 discovery_wait(discovery);
297 make_hook(bool (*packet_cb)(struct relay *, int half, void *aux),
298 void (*periodic_cb)(void *aux),
299 void (*wait_cb)(void *aux),
303 h.packet_cb = packet_cb;
304 h.periodic_cb = periodic_cb;
310 /* OpenFlow message relaying. */
312 static struct relay *
313 relay_accept(const struct settings *s, struct vconn *listen_vconn)
315 struct vconn *new_remote, *new_local;
316 char *nl_name_without_subscription;
317 struct rconn *r1, *r2;
320 retval = vconn_accept(listen_vconn, &new_remote);
322 if (retval != EAGAIN) {
323 VLOG_WARN("accept failed (%s)", strerror(retval));
328 /* nl:123 or nl:123:1 opens a netlink connection to local datapath 123. We
329 * only accept the former syntax in main().
331 * nl:123:0 opens a netlink connection to local datapath 123 without
332 * obtaining a subscription for ofp_packet_in or ofp_flow_expired
334 nl_name_without_subscription = xasprintf("%s:0", s->nl_name);
335 retval = vconn_open(nl_name_without_subscription, &new_local);
337 VLOG_ERR("could not connect to %s (%s)",
338 nl_name_without_subscription, strerror(retval));
339 vconn_close(new_remote);
340 free(nl_name_without_subscription);
344 /* Create and return relay. */
345 r1 = rconn_create(0, 0);
346 rconn_connect_unreliably(r1, nl_name_without_subscription, new_local);
347 free(nl_name_without_subscription);
349 r2 = rconn_create(0, 0);
350 rconn_connect_unreliably(r2, "passive", new_remote);
352 return relay_create(r1, r2, true);
355 static struct relay *
356 relay_create(struct rconn *local, struct rconn *remote, bool is_mgmt_conn)
358 struct relay *r = xcalloc(1, sizeof *r);
359 r->halves[HALF_LOCAL].rconn = local;
360 r->halves[HALF_REMOTE].rconn = remote;
361 r->is_mgmt_conn = is_mgmt_conn;
366 relay_run(struct relay *r, const struct hook hooks[], size_t n_hooks)
371 for (i = 0; i < 2; i++) {
372 rconn_run(r->halves[i].rconn);
375 /* Limit the number of iterations to prevent other tasks from starving. */
376 for (iteration = 0; iteration < 50; iteration++) {
377 bool progress = false;
378 for (i = 0; i < 2; i++) {
379 struct half *this = &r->halves[i];
380 struct half *peer = &r->halves[!i];
383 this->rxbuf = rconn_recv(this->rconn);
385 const struct hook *h;
386 for (h = hooks; h < &hooks[n_hooks]; h++) {
387 if (h->packet_cb(r, i, h->aux)) {
388 buffer_delete(this->rxbuf);
397 if (this->rxbuf && !this->n_txq) {
398 int retval = rconn_send(peer->rconn, this->rxbuf,
400 if (retval != EAGAIN) {
404 buffer_delete(this->rxbuf);
415 if (r->is_mgmt_conn) {
416 for (i = 0; i < 2; i++) {
417 struct half *this = &r->halves[i];
418 if (!rconn_is_alive(this->rconn)) {
427 relay_wait(struct relay *r)
431 for (i = 0; i < 2; i++) {
432 struct half *this = &r->halves[i];
434 rconn_run_wait(this->rconn);
436 rconn_recv_wait(this->rconn);
442 relay_destroy(struct relay *r)
446 list_remove(&r->node);
447 for (i = 0; i < 2; i++) {
448 struct half *this = &r->halves[i];
449 rconn_destroy(this->rconn);
450 buffer_delete(this->rxbuf);
455 /* In-band control. */
457 struct in_band_data {
458 const struct settings *s;
459 struct mac_learning *ml;
460 struct netdev *of_device;
461 uint8_t mac[ETH_ADDR_LEN];
466 queue_tx(struct rconn *rc, struct in_band_data *in_band, struct buffer *b)
468 rconn_send_with_limit(rc, b, &in_band->n_queued, 10);
471 static const uint8_t *
472 get_controller_mac(struct netdev *netdev, struct rconn *controller)
474 static uint32_t ip, last_nonzero_ip;
475 static uint8_t mac[ETH_ADDR_LEN], last_nonzero_mac[ETH_ADDR_LEN];
476 static time_t next_refresh = 0;
478 uint32_t last_ip = ip;
480 time_t now = time_now();
482 ip = rconn_get_ip(controller);
483 if (last_ip != ip || !next_refresh || now >= next_refresh) {
486 /* Look up MAC address. */
487 memset(mac, 0, sizeof mac);
489 int retval = netdev_arp_lookup(netdev, ip, mac);
491 VLOG_DBG("cannot look up controller hw address ("IP_FMT"): %s",
492 IP_ARGS(&ip), strerror(retval));
495 have_mac = !eth_addr_is_zero(mac);
497 /* Log changes in IP, MAC addresses. */
498 if (ip && ip != last_nonzero_ip) {
499 VLOG_DBG("controller IP address changed from "IP_FMT
500 " to "IP_FMT, IP_ARGS(&last_nonzero_ip), IP_ARGS(&ip));
501 last_nonzero_ip = ip;
503 if (have_mac && memcmp(last_nonzero_mac, mac, ETH_ADDR_LEN)) {
504 VLOG_DBG("controller MAC address changed from "ETH_ADDR_FMT" to "
506 ETH_ADDR_ARGS(last_nonzero_mac), ETH_ADDR_ARGS(mac));
507 memcpy(last_nonzero_mac, mac, ETH_ADDR_LEN);
510 /* Schedule next refresh.
512 * If we have an IP address but not a MAC address, then refresh
513 * quickly, since we probably will get a MAC address soon (via ARP).
514 * Otherwise, we can afford to wait a little while. */
515 next_refresh = now + (!ip || have_mac ? 10 : 1);
517 return !eth_addr_is_zero(mac) ? mac : NULL;
521 is_controller_mac(const uint8_t mac[ETH_ADDR_LEN],
522 const uint8_t *controller_mac)
524 return controller_mac && eth_addr_equals(mac, controller_mac);
528 in_band_packet_cb(struct relay *r, int half, void *in_band_)
530 struct in_band_data *in_band = in_band_;
531 struct rconn *rc = r->halves[HALF_LOCAL].rconn;
532 struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
533 struct ofp_packet_in *opi;
534 struct ofp_header *oh;
535 size_t pkt_ofs, pkt_len;
538 uint16_t in_port, out_port;
539 const uint8_t *controller_mac;
541 if (half != HALF_LOCAL || r->is_mgmt_conn) {
546 if (oh->type != OFPT_PACKET_IN) {
549 if (msg->size < offsetof (struct ofp_packet_in, data)) {
550 VLOG_WARN("packet too short (%zu bytes) for packet_in", msg->size);
554 /* Extract flow data from 'opi' into 'flow'. */
556 in_port = ntohs(opi->in_port);
557 pkt_ofs = offsetof(struct ofp_packet_in, data);
558 pkt_len = ntohs(opi->header.length) - pkt_ofs;
559 pkt.data = opi->data;
561 flow_extract(&pkt, in_port, &flow);
563 /* Deal with local stuff. */
564 controller_mac = get_controller_mac(in_band->of_device,
565 r->halves[HALF_REMOTE].rconn);
566 if (in_port == OFPP_LOCAL) {
567 /* Sent by secure channel. */
568 out_port = mac_learning_lookup(in_band->ml, flow.dl_dst);
569 } else if (eth_addr_equals(flow.dl_dst, in_band->mac)) {
570 /* Sent to secure channel. */
571 out_port = OFPP_LOCAL;
572 if (mac_learning_learn(in_band->ml, flow.dl_src, in_port)) {
573 VLOG_DBG("learned that "ETH_ADDR_FMT" is on port %"PRIu16,
574 ETH_ADDR_ARGS(flow.dl_src), in_port);
576 } else if (flow.dl_type == htons(ETH_TYPE_ARP)
577 && eth_addr_is_broadcast(flow.dl_dst)
578 && is_controller_mac(flow.dl_src, controller_mac)) {
579 /* ARP sent by controller. */
580 out_port = OFPP_FLOOD;
581 } else if (is_controller_mac(flow.dl_dst, controller_mac)
582 && in_port == mac_learning_lookup(in_band->ml,
584 /* Drop controller traffic that arrives on the controller port. */
585 queue_tx(rc, in_band, make_add_flow(&flow, ntohl(opi->buffer_id),
586 in_band->s->max_idle, 0));
592 if (out_port != OFPP_FLOOD) {
593 /* The output port is known, so add a new flow. */
594 queue_tx(rc, in_band,
595 make_add_simple_flow(&flow, ntohl(opi->buffer_id),
596 out_port, in_band->s->max_idle));
598 /* If the switch didn't buffer the packet, we need to send a copy. */
599 if (ntohl(opi->buffer_id) == UINT32_MAX) {
600 queue_tx(rc, in_band,
601 make_unbuffered_packet_out(&pkt, in_port, out_port));
604 /* We don't know that MAC. Send along the packet without setting up a
607 if (ntohl(opi->buffer_id) == UINT32_MAX) {
608 b = make_unbuffered_packet_out(&pkt, in_port, out_port);
610 b = make_buffered_packet_out(ntohl(opi->buffer_id),
613 queue_tx(rc, in_band, b);
619 in_band_hook_create(const struct settings *s)
621 struct in_band_data *in_band;
624 in_band = xcalloc(1, sizeof *in_band);
626 in_band->ml = mac_learning_create();
627 retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE,
628 &in_band->of_device);
630 fatal(retval, "Could not open %s device", s->of_name);
632 memcpy(in_band->mac, netdev_get_etheraddr(in_band->of_device),
635 return make_hook(in_band_packet_cb, NULL, NULL, in_band);
638 /* Fail open support. */
640 struct fail_open_data {
641 const struct settings *s;
642 struct rconn *local_rconn;
643 struct rconn *remote_rconn;
644 struct lswitch *lswitch;
645 int last_disconn_secs;
648 /* Causes 'r' to enter or leave fail-open mode, if appropriate. */
650 fail_open_periodic_cb(void *fail_open_)
652 struct fail_open_data *fail_open = fail_open_;
656 disconn_secs = rconn_disconnected_duration(fail_open->remote_rconn);
657 open = disconn_secs >= fail_open->s->probe_interval * 3;
658 if (open != (fail_open->lswitch != NULL)) {
660 VLOG_WARN("No longer in fail-open mode");
661 lswitch_destroy(fail_open->lswitch);
662 fail_open->lswitch = NULL;
664 VLOG_WARN("Could not connect to controller for %d seconds, "
665 "failing open", disconn_secs);
666 fail_open->lswitch = lswitch_create(fail_open->local_rconn, true,
667 fail_open->s->max_idle);
668 fail_open->last_disconn_secs = disconn_secs;
670 } else if (open && disconn_secs > fail_open->last_disconn_secs + 60) {
671 VLOG_WARN("Still in fail-open mode after %d seconds disconnected "
672 "from controller", disconn_secs);
673 fail_open->last_disconn_secs = disconn_secs;
678 fail_open_packet_cb(struct relay *r, int half, void *fail_open_)
680 struct fail_open_data *fail_open = fail_open_;
681 if (half != HALF_LOCAL || r->is_mgmt_conn || !fail_open->lswitch) {
684 lswitch_process_packet(fail_open->lswitch, fail_open->local_rconn,
685 r->halves[HALF_LOCAL].rxbuf);
686 rconn_run(fail_open->local_rconn);
692 fail_open_hook_create(const struct settings *s, struct rconn *local_rconn,
693 struct rconn *remote_rconn)
695 struct fail_open_data *fail_open = xmalloc(sizeof *fail_open);
697 fail_open->local_rconn = local_rconn;
698 fail_open->remote_rconn = remote_rconn;
699 fail_open->lswitch = NULL;
700 return make_hook(fail_open_packet_cb, fail_open_periodic_cb, NULL,
704 struct rate_limiter {
705 const struct settings *s;
706 struct rconn *remote_rconn;
708 /* One queue per physical port. */
709 struct queue queues[OFPP_MAX];
710 int n_queued; /* Sum over queues[*].n. */
711 int next_tx_port; /* Next port to check in round-robin. */
715 * It costs 1000 tokens to send a single packet_in message. A single token
716 * per message would be more straightforward, but this choice lets us avoid
717 * round-off error in refill_bucket()'s calculation of how many tokens to
718 * add to the bucket, since no division step is needed. */
719 long long int last_fill; /* Time at which we last added tokens. */
720 int tokens; /* Current number of tokens. */
722 /* Transmission queue. */
723 int n_txq; /* No. of packets waiting in rconn for tx. */
726 /* Drop a packet from the longest queue in 'rl'. */
728 drop_packet(struct rate_limiter *rl)
730 struct queue *longest; /* Queue currently selected as longest. */
731 int n_longest; /* # of queues of same length as 'longest'. */
734 longest = &rl->queues[0];
736 for (q = &rl->queues[0]; q < &rl->queues[OFPP_MAX]; q++) {
737 if (longest->n < q->n) {
740 } else if (longest->n == q->n) {
743 /* Randomly select one of the longest queues, with a uniform
744 * distribution (Knuth algorithm 3.4.2R). */
745 if (!random_range(n_longest)) {
751 /* FIXME: do we want to pop the tail instead? */
752 buffer_delete(queue_pop_head(longest));
756 /* Remove and return the next packet to transmit (in round-robin order). */
757 static struct buffer *
758 dequeue_packet(struct rate_limiter *rl)
762 for (i = 0; i < OFPP_MAX; i++) {
763 unsigned int port = (rl->next_tx_port + i) % OFPP_MAX;
764 struct queue *q = &rl->queues[port];
766 rl->next_tx_port = (port + 1) % OFPP_MAX;
768 return queue_pop_head(q);
774 /* Add tokens to the bucket based on elapsed time. */
776 refill_bucket(struct rate_limiter *rl)
778 const struct settings *s = rl->s;
779 long long int now = time_msec();
780 long long int tokens = (now - rl->last_fill) * s->rate_limit + rl->tokens;
781 if (tokens >= 1000) {
783 rl->tokens = MIN(tokens, s->burst_limit * 1000);
787 /* Attempts to remove enough tokens from 'rl' to transmit a packet. Returns
788 * true if successful, false otherwise. (In the latter case no tokens are
791 get_token(struct rate_limiter *rl)
793 if (rl->tokens >= 1000) {
802 rate_limit_packet_cb(struct relay *r, int half, void *rl_)
804 struct rate_limiter *rl = rl_;
805 const struct settings *s = rl->s;
806 struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
807 struct ofp_header *oh;
809 if (half == HALF_REMOTE) {
814 if (oh->type != OFPT_PACKET_IN) {
817 if (msg->size < offsetof(struct ofp_packet_in, data)) {
818 VLOG_WARN("packet too short (%zu bytes) for packet_in", msg->size);
822 if (!rl->n_queued && get_token(rl)) {
823 /* In the common case where we are not constrained by the rate limit,
824 * let the packet take the normal path. */
827 /* Otherwise queue it up for the periodic callback to drain out. */
828 struct ofp_packet_in *opi = msg->data;
829 int port = ntohs(opi->in_port) % OFPP_MAX;
830 if (rl->n_queued >= s->burst_limit) {
833 queue_push_tail(&rl->queues[port], buffer_clone(msg));
840 rate_limit_periodic_cb(void *rl_)
842 struct rate_limiter *rl = rl_;
845 /* Drain some packets out of the bucket if possible, but limit the number
846 * of iterations to allow other code to get work done too. */
848 for (i = 0; rl->n_queued && get_token(rl) && i < 50; i++) {
849 /* Use a small, arbitrary limit for the amount of queuing to do here,
850 * because the TCP connection is responsible for buffering and there is
851 * no point in trying to transmit faster than the TCP connection can
853 struct buffer *b = dequeue_packet(rl);
854 rconn_send_with_limit(rl->remote_rconn, b, &rl->n_txq, 10);
859 rate_limit_wait_cb(void *rl_)
861 struct rate_limiter *rl = rl_;
863 if (rl->tokens >= 1000) {
864 /* We can transmit more packets as soon as we're called again. */
865 poll_immediate_wake();
867 /* We have to wait for the bucket to re-fill. We could calculate
868 * the exact amount of time here for increased smoothness. */
869 poll_timer_wait(TIME_UPDATE_INTERVAL / 2);
875 rate_limit_hook_create(const struct settings *s,
877 struct rconn *remote)
879 struct rate_limiter *rl;
882 rl = xcalloc(1, sizeof *rl);
884 rl->remote_rconn = remote;
885 for (i = 0; i < ARRAY_SIZE(rl->queues); i++) {
886 queue_init(&rl->queues[i]);
888 rl->last_fill = time_msec();
889 rl->tokens = s->rate_limit * 100;
890 return make_hook(rate_limit_packet_cb, rate_limit_periodic_cb,
891 rate_limit_wait_cb, rl);
894 /* Controller discovery. */
898 const struct settings *s;
899 struct dhclient *dhcp;
900 bool ever_successful;
903 static struct discovery *
904 discovery_init(const struct settings *s)
906 struct netdev *netdev;
908 struct dhclient *dhcp;
911 /* Bring ofX network device up. */
912 retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
914 fatal(retval, "Could not open %s device", s->of_name);
916 retval = netdev_turn_flags_on(netdev, NETDEV_UP, true);
918 fatal(retval, "Could not bring %s device up", s->of_name);
920 netdev_close(netdev);
922 /* Initialize DHCP client. */
923 retval = dhclient_create(s->of_name, modify_dhcp_request,
924 validate_dhcp_offer, (void *) s, &dhcp);
926 fatal(retval, "Failed to initialize DHCP client");
928 dhclient_init(dhcp, 0);
930 d = xmalloc(sizeof *d);
933 d->ever_successful = false;
938 discovery_question_connectivity(struct discovery *d)
940 dhclient_force_renew(d->dhcp, 15);
944 discovery_run(struct discovery *d, char **controller_name)
946 dhclient_run(d->dhcp);
947 if (!dhclient_changed(d->dhcp)) {
951 dhclient_configure_netdev(d->dhcp);
952 if (d->s->update_resolv_conf) {
953 dhclient_update_resolv_conf(d->dhcp);
956 if (dhclient_is_bound(d->dhcp)) {
957 *controller_name = dhcp_msg_get_string(dhclient_get_config(d->dhcp),
958 DHCP_CODE_OFP_CONTROLLER_VCONN);
959 VLOG_WARN("%s: discovered controller", *controller_name);
960 d->ever_successful = true;
961 } else if (controller_name) {
962 *controller_name = NULL;
963 if (d->ever_successful) {
964 VLOG_WARN("discovered controller no longer available");
971 discovery_wait(struct discovery *d)
973 dhclient_wait(d->dhcp);
977 modify_dhcp_request(struct dhcp_msg *msg, void *aux)
979 dhcp_msg_put_string(msg, DHCP_CODE_VENDOR_CLASS, "OpenFlow");
983 validate_dhcp_offer(const struct dhcp_msg *msg, void *s_)
985 const struct settings *s = s_;
989 vconn_name = dhcp_msg_get_string(msg, DHCP_CODE_OFP_CONTROLLER_VCONN);
991 VLOG_WARN("rejecting DHCP offer missing controller vconn");
994 accept = !regexec(&s->accept_controller_regex, vconn_name, 0, NULL, 0);
996 VLOG_WARN("rejecting controller vconn that fails to match %s",
997 s->accept_controller_re);
1003 /* User interface. */
1006 parse_options(int argc, char *argv[], struct settings *s)
1009 OPT_ACCEPT_VCONN = UCHAR_MAX + 1,
1011 OPT_INACTIVITY_PROBE,
1017 static struct option long_options[] = {
1018 {"accept-vconn", required_argument, 0, OPT_ACCEPT_VCONN},
1019 {"no-resolv-conf", no_argument, 0, OPT_NO_RESOLV_CONF},
1020 {"fail", required_argument, 0, 'f'},
1021 {"inactivity-probe", required_argument, 0, OPT_INACTIVITY_PROBE},
1022 {"max-idle", required_argument, 0, OPT_MAX_IDLE},
1023 {"max-backoff", required_argument, 0, OPT_MAX_BACKOFF},
1024 {"listen", required_argument, 0, 'l'},
1025 {"rate-limit", optional_argument, 0, OPT_RATE_LIMIT},
1026 {"burst-limit", required_argument, 0, OPT_BURST_LIMIT},
1027 {"detach", no_argument, 0, 'D'},
1028 {"pidfile", optional_argument, 0, 'P'},
1029 {"verbose", optional_argument, 0, 'v'},
1030 {"help", no_argument, 0, 'h'},
1031 {"version", no_argument, 0, 'V'},
1032 VCONN_SSL_LONG_OPTIONS
1035 char *short_options = long_options_to_short_options(long_options);
1036 char *accept_re = NULL;
1039 /* Set defaults that we can figure out before parsing options. */
1040 s->listen_vconn_name = NULL;
1041 s->fail_mode = FAIL_OPEN;
1043 s->probe_interval = 15;
1044 s->max_backoff = 15;
1045 s->update_resolv_conf = true;
1051 c = getopt_long(argc, argv, short_options, long_options, NULL);
1057 case OPT_ACCEPT_VCONN:
1058 accept_re = optarg[0] == '^' ? optarg : xasprintf("^%s", optarg);
1061 case OPT_NO_RESOLV_CONF:
1062 s->update_resolv_conf = false;
1066 if (!strcmp(optarg, "open")) {
1067 s->fail_mode = FAIL_OPEN;
1068 } else if (!strcmp(optarg, "closed")) {
1069 s->fail_mode = FAIL_CLOSED;
1072 "-f or --fail argument must be \"open\" or \"closed\"");
1076 case OPT_INACTIVITY_PROBE:
1077 s->probe_interval = atoi(optarg);
1078 if (s->probe_interval < 5) {
1079 fatal(0, "--inactivity-probe argument must be at least 5");
1084 if (!strcmp(optarg, "permanent")) {
1085 s->max_idle = OFP_FLOW_PERMANENT;
1087 s->max_idle = atoi(optarg);
1088 if (s->max_idle < 1 || s->max_idle > 65535) {
1089 fatal(0, "--max-idle argument must be between 1 and "
1090 "65535 or the word 'permanent'");
1095 case OPT_MAX_BACKOFF:
1096 s->max_backoff = atoi(optarg);
1097 if (s->max_backoff < 1) {
1098 fatal(0, "--max-backoff argument must be at least 1");
1099 } else if (s->max_backoff > 3600) {
1100 s->max_backoff = 3600;
1104 case OPT_RATE_LIMIT:
1106 s->rate_limit = atoi(optarg);
1107 if (s->rate_limit < 1) {
1108 fatal(0, "--rate-limit argument must be at least 1");
1111 s->rate_limit = 1000;
1115 case OPT_BURST_LIMIT:
1116 s->burst_limit = atoi(optarg);
1117 if (s->burst_limit < 1) {
1118 fatal(0, "--burst-limit argument must be at least 1");
1127 set_pidfile(optarg);
1131 if (s->listen_vconn_name) {
1132 fatal(0, "-l or --listen may be only specified once");
1134 s->listen_vconn_name = optarg;
1141 printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
1145 vlog_set_verbosity(optarg);
1148 VCONN_SSL_OPTION_HANDLERS
1157 free(short_options);
1161 if (argc < 1 || argc > 2) {
1162 fatal(0, "need one or two non-option arguments; use --help for usage");
1165 /* Local and remote vconns. */
1166 s->nl_name = argv[0];
1167 if (strncmp(s->nl_name, "nl:", 3)
1168 || strlen(s->nl_name) < 4
1169 || s->nl_name[strspn(s->nl_name + 3, "0123456789") + 3]) {
1170 fatal(0, "%s: argument is not of the form \"nl:DP_IDX\"", s->nl_name);
1172 s->of_name = xasprintf("of%s", s->nl_name + 3);
1173 s->controller_name = argc > 1 ? xstrdup(argv[1]) : NULL;
1175 /* Set accept_controller_regex. */
1177 accept_re = vconn_ssl_is_configured() ? "^ssl:.*" : ".*";
1179 retval = regcomp(&s->accept_controller_regex, accept_re,
1180 REG_NOSUB | REG_EXTENDED);
1182 size_t length = regerror(retval, &s->accept_controller_regex, NULL, 0);
1183 char *buffer = xmalloc(length);
1184 regerror(retval, &s->accept_controller_regex, buffer, length);
1185 fatal(0, "%s: %s", accept_re, buffer);
1187 s->accept_controller_re = accept_re;
1189 /* Mode of operation. */
1190 s->discovery = s->controller_name == NULL;
1194 enum netdev_flags flags;
1195 struct netdev *netdev;
1197 retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
1199 fatal(retval, "Could not open %s device", s->of_name);
1202 retval = netdev_get_flags(netdev, &flags);
1204 fatal(retval, "Could not get flags for %s device", s->of_name);
1207 s->in_band = (flags & NETDEV_UP) != 0;
1208 if (s->in_band && netdev_get_in6(netdev, NULL)) {
1209 VLOG_WARN("Ignoring IPv6 address on %s device: IPv6 not supported",
1213 netdev_close(netdev);
1216 /* Rate limiting. */
1217 if (s->rate_limit) {
1218 if (s->rate_limit < 100) {
1219 VLOG_WARN("Rate limit set to unusually low value %d",
1222 if (!s->burst_limit) {
1223 s->burst_limit = s->rate_limit / 4;
1225 s->burst_limit = MAX(s->burst_limit, 1);
1226 s->burst_limit = MIN(s->burst_limit, INT_MAX / 1000);
1233 printf("%s: secure channel, a relay for OpenFlow messages.\n"
1234 "usage: %s [OPTIONS] nl:DP_IDX [CONTROLLER]\n"
1235 "where nl:DP_IDX is a datapath that has been added with dpctl.\n"
1236 "CONTROLLER is an active OpenFlow connection method; if it is\n"
1237 "omitted, then secchan performs controller discovery.\n",
1238 program_name, program_name);
1239 vconn_usage(true, true);
1240 printf("\nController discovery options:\n"
1241 " --accept-vconn=REGEX accept matching discovered controllers\n"
1242 " --no-resolv-conf do not update /etc/resolv.conf\n"
1243 "\nNetworking options:\n"
1244 " -f, --fail=open|closed when controller connection fails:\n"
1245 " closed: drop all packets\n"
1246 " open (default): act as learning switch\n"
1247 " --inactivity-probe=SECS time between inactivity probes\n"
1248 " --max-idle=SECS max idle for flows set up by secchan\n"
1249 " --max-backoff=SECS max time between controller connection\n"
1250 " attempts (default: 15 seconds)\n"
1251 " -l, --listen=METHOD allow management connections on METHOD\n"
1252 " (a passive OpenFlow connection method)\n"
1253 "\nRate-limiting of \"packet-in\" messages to the controller:\n"
1254 " --rate-limit[=PACKETS] max rate, in packets/s (default: 1000)\n"
1255 " --burst-limit=BURST limit on packet credit for idle time\n"
1256 "\nOther options:\n"
1257 " -D, --detach run in background as daemon\n"
1258 " -P, --pidfile[=FILE] create pidfile (default: %s/secchan.pid)\n"
1259 " -v, --verbose=MODULE[:FACILITY[:LEVEL]] set logging levels\n"
1260 " -v, --verbose set maximum verbosity level\n"
1261 " -h, --help display this help message\n"
1262 " -V, --version display version information\n",