Print OpenFlow ref. impl. and protocol versions at secchan startup time.
[sliver-openvswitch.git] / secchan / secchan.c
1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  *
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:
16  *
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  *
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
27  * SOFTWARE.
28  *
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.
32  */
33
34 #include <config.h>
35 #include <assert.h>
36 #include <errno.h>
37 #include <getopt.h>
38 #include <inttypes.h>
39 #include <netinet/in.h>
40 #include <poll.h>
41 #include <regex.h>
42 #include <stdlib.h>
43 #include <signal.h>
44 #include <string.h>
45 #include <time.h>
46 #include <unistd.h>
47
48 #include "buffer.h"
49 #include "command-line.h"
50 #include "compiler.h"
51 #include "daemon.h"
52 #include "dhcp.h"
53 #include "dhcp-client.h"
54 #include "dynamic-string.h"
55 #include "fault.h"
56 #include "flow.h"
57 #include "learning-switch.h"
58 #include "list.h"
59 #include "mac-learning.h"
60 #include "netdev.h"
61 #include "openflow.h"
62 #include "packets.h"
63 #include "poll-loop.h"
64 #include "rconn.h"
65 #include "timeval.h"
66 #include "util.h"
67 #include "vconn-ssl.h"
68 #include "vconn.h"
69 #include "vlog-socket.h"
70
71 #include "vlog.h"
72 #define THIS_MODULE VLM_secchan
73
74 /* Behavior when the connection to the controller fails. */
75 enum fail_mode {
76     FAIL_OPEN,                  /* Act as learning switch. */
77     FAIL_CLOSED                 /* Drop all packets. */
78 };
79
80 /* Settings that may be configured by the user. */
81 struct settings {
82     /* Overall mode of operation. */
83     bool discovery;           /* Discover the controller automatically? */
84     bool in_band;             /* Connect to controller in-band? */
85
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. */
91
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. */
97
98     /* Packet-in rate-limiting. */
99     int rate_limit;           /* Tokens added to bucket per second. */
100     int burst_limit;          /* Maximum number token bucket size. */
101
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? */
106 };
107
108 struct half {
109     struct rconn *rconn;
110     struct buffer *rxbuf;
111     int n_txq;                  /* No. of packets queued for tx on 'rconn'. */
112 };
113
114 struct relay {
115     struct list node;
116
117 #define HALF_LOCAL 0
118 #define HALF_REMOTE 1
119     struct half halves[2];
120
121     bool is_mgmt_conn;
122 };
123
124 struct hook {
125     bool (*packet_cb)(struct relay *, int half, void *aux);
126     void (*periodic_cb)(void *aux);
127     void (*wait_cb)(void *aux);
128     void *aux;
129 };
130
131 static void parse_options(int argc, char *argv[], struct settings *);
132 static void usage(void) NO_RETURN;
133
134 static struct relay *relay_create(struct rconn *local, struct rconn *remote,
135                                   bool is_mgmt_conn);
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 *);
140
141 static struct hook make_hook(bool (*packet_cb)(struct relay *, int, void *),
142                              void (*periodic_cb)(void *),
143                              void (*wait_cb)(void *),
144                              void *aux);
145
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 *);
150
151 static struct hook in_band_hook_create(const struct settings *);
152 static struct hook fail_open_hook_create(const struct settings *,
153                                          struct rconn *local,
154                                          struct rconn *remote);
155 static struct hook rate_limit_hook_create(const struct settings *,
156                                           struct rconn *local,
157                                           struct rconn *remote);
158
159 static void modify_dhcp_request(struct dhcp_msg *, void *aux);
160 static bool validate_dhcp_offer(const struct dhcp_msg *, void *aux);
161
162 int
163 main(int argc, char *argv[])
164 {
165     struct settings s;
166
167     struct list relays = LIST_INITIALIZER(&relays);
168
169     struct hook hooks[4];
170     size_t n_hooks;
171
172     struct rconn *local_rconn, *remote_rconn;
173     struct vconn *listen_vconn;
174     struct relay *controller_relay;
175     struct discovery *discovery;
176     int retval;
177
178     set_program_name(argv[0]);
179     register_fault_handlers();
180     time_init();
181     vlog_init();
182     parse_options(argc, argv, &s);
183     signal(SIGPIPE, SIG_IGN);
184
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);
190         }
191         if (!vconn_is_passive(listen_vconn)) {
192             fatal(0, "%s is not a passive vconn", s.listen_vconn_name);
193         }
194     } else {
195         listen_vconn = NULL;
196     }
197
198     /* Start controller discovery. */
199     discovery = s.discovery ? discovery_init(&s) : NULL;
200
201     /* Start listening for vlogconf requests. */
202     retval = vlog_server_listen(NULL, NULL);
203     if (retval) {
204         fatal(retval, "Could not listen for vlog connections");
205     }
206
207     daemonize();
208
209     VLOG_WARN("OpenFlow reference implementation version %s", VERSION);
210     VLOG_WARN("OpenFlow protocol version 0x%02x", OFP_VERSION);
211
212     /* Connect to datapath. */
213     local_rconn = rconn_create(0, s.max_backoff);
214     rconn_connect(local_rconn, s.nl_name);
215
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);
222         }
223     }
224
225     /* Start relaying. */
226     controller_relay = relay_create(local_rconn, remote_rconn, false);
227     list_push_back(&relays, &controller_relay->node);
228
229     /* Set up hooks. */
230     n_hooks = 0;
231     if (s.in_band) {
232         hooks[n_hooks++] = in_band_hook_create(&s);
233     }
234     if (s.fail_mode == FAIL_OPEN) {
235         hooks[n_hooks++] = fail_open_hook_create(&s,
236                                                  local_rconn, remote_rconn);
237     }
238     if (s.rate_limit) {
239         hooks[n_hooks++] = rate_limit_hook_create(&s,
240                                                   local_rconn, remote_rconn);
241     }
242     assert(n_hooks <= ARRAY_SIZE(hooks));
243
244     for (;;) {
245         struct relay *r, *n;
246         size_t i;
247
248         /* Do work. */
249         LIST_FOR_EACH_SAFE (r, n, struct relay, node, &relays) {
250             relay_run(r, hooks, n_hooks);
251         }
252         if (listen_vconn) {
253             for (;;) {
254                 struct relay *r = relay_accept(&s, listen_vconn);
255                 if (!r) {
256                     break;
257                 }
258                 list_push_back(&relays, &r->node);
259             }
260         }
261         for (i = 0; i < n_hooks; i++) {
262             if (hooks[i].periodic_cb) {
263                 hooks[i].periodic_cb(hooks[i].aux);
264             }
265         }
266         if (s.discovery) {
267             char *controller_name;
268             if (rconn_is_connectivity_questionable(remote_rconn)) {
269                 discovery_question_connectivity(discovery);
270             }
271             if (discovery_run(discovery, &controller_name)) {
272                 if (controller_name) {
273                     rconn_connect(remote_rconn, controller_name);
274                 } else {
275                     rconn_disconnect(remote_rconn);
276                 }
277             }
278         }
279
280         /* Wait for something to happen. */
281         LIST_FOR_EACH (r, struct relay, node, &relays) {
282             relay_wait(r);
283         }
284         if (listen_vconn) {
285             vconn_accept_wait(listen_vconn);
286         }
287         for (i = 0; i < n_hooks; i++) {
288             if (hooks[i].wait_cb) {
289                 hooks[i].wait_cb(hooks[i].aux);
290             }
291         }
292         if (discovery) {
293             discovery_wait(discovery);
294         }
295         poll_block();
296     }
297
298     return 0;
299 }
300
301 static struct hook
302 make_hook(bool (*packet_cb)(struct relay *, int half, void *aux),
303           void (*periodic_cb)(void *aux),
304           void (*wait_cb)(void *aux),
305           void *aux)
306 {
307     struct hook h;
308     h.packet_cb = packet_cb;
309     h.periodic_cb = periodic_cb;
310     h.wait_cb = wait_cb;
311     h.aux = aux;
312     return h;
313 }
314 \f
315 /* OpenFlow message relaying. */
316
317 static struct relay *
318 relay_accept(const struct settings *s, struct vconn *listen_vconn)
319 {
320     struct vconn *new_remote, *new_local;
321     char *nl_name_without_subscription;
322     struct rconn *r1, *r2;
323     int retval;
324
325     retval = vconn_accept(listen_vconn, &new_remote);
326     if (retval) {
327         if (retval != EAGAIN) {
328             VLOG_WARN("accept failed (%s)", strerror(retval));
329         }
330         return NULL;
331     }
332
333     /* nl:123 or nl:123:1 opens a netlink connection to local datapath 123.  We
334      * only accept the former syntax in main().
335      *
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
338      * messages.*/
339     nl_name_without_subscription = xasprintf("%s:0", s->nl_name);
340     retval = vconn_open(nl_name_without_subscription, &new_local);
341     if (retval) {
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);
346         return NULL;
347     }
348
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);
353
354     r2 = rconn_create(0, 0);
355     rconn_connect_unreliably(r2, "passive", new_remote);
356
357     return relay_create(r1, r2, true);
358 }
359
360 static struct relay *
361 relay_create(struct rconn *local, struct rconn *remote, bool is_mgmt_conn)
362 {
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;
367     return r;
368 }
369
370 static void
371 relay_run(struct relay *r, const struct hook hooks[], size_t n_hooks)
372 {
373     int iteration;
374     int i;
375
376     for (i = 0; i < 2; i++) {
377         rconn_run(r->halves[i].rconn);
378     }
379
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];
386
387             if (!this->rxbuf) {
388                 this->rxbuf = rconn_recv(this->rconn);
389                 if (this->rxbuf) {
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);
394                             this->rxbuf = NULL;
395                             progress = true;
396                             break;
397                         }
398                     }
399                 }
400             }
401
402             if (this->rxbuf && !this->n_txq) {
403                 int retval = rconn_send(peer->rconn, this->rxbuf,
404                                         &this->n_txq);
405                 if (retval != EAGAIN) {
406                     if (!retval) {
407                         progress = true;
408                     } else {
409                         buffer_delete(this->rxbuf);
410                     }
411                     this->rxbuf = NULL;
412                 }
413             }
414         }
415         if (!progress) {
416             break;
417         }
418     }
419
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)) {
424                 relay_destroy(r);
425                 return;
426             }
427         }
428     }
429 }
430
431 static void
432 relay_wait(struct relay *r)
433 {
434     int i;
435
436     for (i = 0; i < 2; i++) {
437         struct half *this = &r->halves[i];
438
439         rconn_run_wait(this->rconn);
440         if (!this->rxbuf) {
441             rconn_recv_wait(this->rconn);
442         }
443     }
444 }
445
446 static void
447 relay_destroy(struct relay *r)
448 {
449     int i;
450
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);
456     }
457     free(r);
458 }
459 \f
460 /* In-band control. */
461
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];
467     int n_queued;
468 };
469
470 static void
471 queue_tx(struct rconn *rc, struct in_band_data *in_band, struct buffer *b)
472 {
473     rconn_send_with_limit(rc, b, &in_band->n_queued, 10);
474 }
475
476 static const uint8_t *
477 get_controller_mac(struct netdev *netdev, struct rconn *controller)
478 {
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;
482
483     uint32_t last_ip = ip;
484
485     time_t now = time_now();
486
487     ip = rconn_get_ip(controller);
488     if (last_ip != ip || !next_refresh || now >= next_refresh) {
489         bool have_mac;
490
491         /* Look up MAC address. */
492         memset(mac, 0, sizeof mac);
493         if (ip) {
494             int retval = netdev_arp_lookup(netdev, ip, mac);
495             if (retval) {
496                 VLOG_DBG("cannot look up controller hw address ("IP_FMT"): %s",
497                          IP_ARGS(&ip), strerror(retval));
498             }
499         }
500         have_mac = !eth_addr_is_zero(mac);
501
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;
507         }
508         if (have_mac && memcmp(last_nonzero_mac, mac, ETH_ADDR_LEN)) {
509             VLOG_DBG("controller MAC address changed from "ETH_ADDR_FMT" to "
510                      ETH_ADDR_FMT,
511                      ETH_ADDR_ARGS(last_nonzero_mac), ETH_ADDR_ARGS(mac));
512             memcpy(last_nonzero_mac, mac, ETH_ADDR_LEN);
513         }
514
515         /* Schedule next refresh.
516          *
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);
521     }
522     return !eth_addr_is_zero(mac) ? mac : NULL;
523 }
524
525 static bool
526 is_controller_mac(const uint8_t mac[ETH_ADDR_LEN],
527                   const uint8_t *controller_mac)
528 {
529     return controller_mac && eth_addr_equals(mac, controller_mac);
530 }
531
532 static bool
533 in_band_packet_cb(struct relay *r, int half, void *in_band_)
534 {
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;
541     struct buffer pkt;
542     struct flow flow;
543     uint16_t in_port, out_port;
544     const uint8_t *controller_mac;
545
546     if (half != HALF_LOCAL || r->is_mgmt_conn) {
547         return false;
548     }
549
550     oh = msg->data;
551     if (oh->type != OFPT_PACKET_IN) {
552         return false;
553     }
554     if (msg->size < offsetof (struct ofp_packet_in, data)) {
555         VLOG_WARN("packet too short (%zu bytes) for packet_in", msg->size);
556         return false;
557     }
558
559     /* Extract flow data from 'opi' into 'flow'. */
560     opi = msg->data;
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;
565     pkt.size = pkt_len;
566     flow_extract(&pkt, in_port, &flow);
567
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);
580         }
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,
588                                                  controller_mac)) {
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));
592         return true;
593     } else {
594         return false;
595     }
596
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));
602
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));
607         }
608     } else {
609         /* We don't know that MAC.  Send along the packet without setting up a
610          * flow. */
611         struct buffer *b;
612         if (ntohl(opi->buffer_id) == UINT32_MAX) {
613             b = make_unbuffered_packet_out(&pkt, in_port, out_port);
614         } else {
615             b = make_buffered_packet_out(ntohl(opi->buffer_id),
616                                          in_port, out_port);
617         }
618         queue_tx(rc, in_band, b);
619     }
620     return true;
621 }
622
623 static struct hook
624 in_band_hook_create(const struct settings *s)
625 {
626     struct in_band_data *in_band;
627     int retval;
628
629     in_band = xcalloc(1, sizeof *in_band);
630     in_band->s = s;
631     in_band->ml = mac_learning_create();
632     retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE,
633                          &in_band->of_device);
634     if (retval) {
635         fatal(retval, "Could not open %s device", s->of_name);
636     }
637     memcpy(in_band->mac, netdev_get_etheraddr(in_band->of_device),
638            ETH_ADDR_LEN);
639
640     return make_hook(in_band_packet_cb, NULL, NULL, in_band);
641 }
642 \f
643 /* Fail open support. */
644
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;
651 };
652
653 /* Causes 'r' to enter or leave fail-open mode, if appropriate. */
654 static void
655 fail_open_periodic_cb(void *fail_open_)
656 {
657     struct fail_open_data *fail_open = fail_open_;
658     int disconn_secs;
659     bool open;
660
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)) {
664         if (!open) {
665             VLOG_WARN("No longer in fail-open mode");
666             lswitch_destroy(fail_open->lswitch);
667             fail_open->lswitch = NULL;
668         } else {
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;
674         }
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;
679     }
680 }
681
682 static bool
683 fail_open_packet_cb(struct relay *r, int half, void *fail_open_)
684 {
685     struct fail_open_data *fail_open = fail_open_;
686     if (half != HALF_LOCAL || r->is_mgmt_conn || !fail_open->lswitch) {
687         return false;
688     } else {
689         lswitch_process_packet(fail_open->lswitch, fail_open->local_rconn,
690                                r->halves[HALF_LOCAL].rxbuf);
691         rconn_run(fail_open->local_rconn);
692         return true;
693     }
694 }
695
696 static struct hook
697 fail_open_hook_create(const struct settings *s, struct rconn *local_rconn,
698                       struct rconn *remote_rconn)
699 {
700     struct fail_open_data *fail_open = xmalloc(sizeof *fail_open);
701     fail_open->s = s;
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,
706                      fail_open);
707 }
708 \f
709 struct rate_limiter {
710     const struct settings *s;
711     struct rconn *remote_rconn;
712
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. */
717
718     /* Token bucket.
719      *
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. */
726
727     /* Transmission queue. */
728     int n_txq;                  /* No. of packets waiting in rconn for tx. */
729 };
730
731 /* Drop a packet from the longest queue in 'rl'. */
732 static void
733 drop_packet(struct rate_limiter *rl)
734 {
735     struct queue *longest;      /* Queue currently selected as longest. */
736     int n_longest;              /* # of queues of same length as 'longest'. */
737     struct queue *q;
738
739     longest = &rl->queues[0];
740     n_longest = 1;
741     for (q = &rl->queues[0]; q < &rl->queues[OFPP_MAX]; q++) {
742         if (longest->n < q->n) {
743             longest = q;
744             n_longest = 1;
745         } else if (longest->n == q->n) {
746             n_longest++;
747
748             /* Randomly select one of the longest queues, with a uniform
749              * distribution (Knuth algorithm 3.4.2R). */
750             if (!random_range(n_longest)) {
751                 longest = q;
752             }
753         }
754     }
755
756     /* FIXME: do we want to pop the tail instead? */
757     buffer_delete(queue_pop_head(longest));
758     rl->n_queued--;
759 }
760
761 /* Remove and return the next packet to transmit (in round-robin order). */
762 static struct buffer *
763 dequeue_packet(struct rate_limiter *rl)
764 {
765     unsigned int i;
766
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];
770         if (q->n) {
771             rl->next_tx_port = (port + 1) % OFPP_MAX;
772             rl->n_queued--;
773             return queue_pop_head(q);
774         }
775     }
776     NOT_REACHED();
777 }
778
779 /* Add tokens to the bucket based on elapsed time. */
780 static void
781 refill_bucket(struct rate_limiter *rl)
782 {
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) {
787         rl->last_fill = now;
788         rl->tokens = MIN(tokens, s->burst_limit * 1000);
789     }
790 }
791
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
794  * removed.) */
795 static bool
796 get_token(struct rate_limiter *rl)
797 {
798     if (rl->tokens >= 1000) {
799         rl->tokens -= 1000;
800         return true;
801     } else {
802         return false;
803     }
804 }
805
806 static bool
807 rate_limit_packet_cb(struct relay *r, int half, void *rl_)
808 {
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;
813
814     if (half == HALF_REMOTE) {
815         return false;
816     }
817
818     oh = msg->data;
819     if (oh->type != OFPT_PACKET_IN) {
820         return false;
821     }
822     if (msg->size < offsetof(struct ofp_packet_in, data)) {
823         VLOG_WARN("packet too short (%zu bytes) for packet_in", msg->size);
824         return false;
825     }
826
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. */
830         return false;
831     } else {
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) {
836             drop_packet(rl);
837         }
838         queue_push_tail(&rl->queues[port], buffer_clone(msg));
839         rl->n_queued++;
840         return true;
841     }
842 }
843
844 static void
845 rate_limit_periodic_cb(void *rl_)
846 {
847     struct rate_limiter *rl = rl_;
848     int i;
849
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. */
852     refill_bucket(rl);
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
857          * handle. */
858         struct buffer *b = dequeue_packet(rl);
859         rconn_send_with_limit(rl->remote_rconn, b, &rl->n_txq, 10);
860     }
861 }
862
863 static void
864 rate_limit_wait_cb(void *rl_)
865 {
866     struct rate_limiter *rl = rl_;
867     if (rl->n_queued) {
868         if (rl->tokens >= 1000) {
869             /* We can transmit more packets as soon as we're called again. */
870             poll_immediate_wake();
871         } else {
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);
875         }
876     }
877 }
878
879 static struct hook
880 rate_limit_hook_create(const struct settings *s,
881                        struct rconn *local,
882                        struct rconn *remote)
883 {
884     struct rate_limiter *rl;
885     size_t i;
886
887     rl = xcalloc(1, sizeof *rl);
888     rl->s = s;
889     rl->remote_rconn = remote;
890     for (i = 0; i < ARRAY_SIZE(rl->queues); i++) {
891         queue_init(&rl->queues[i]);
892     }
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);
897 }
898 \f
899 /* Controller discovery. */
900
901 struct discovery
902 {
903     const struct settings *s;
904     struct dhclient *dhcp;
905     bool ever_successful;
906 };
907
908 static struct discovery *
909 discovery_init(const struct settings *s)
910 {
911     struct netdev *netdev;
912     struct discovery *d;
913     struct dhclient *dhcp;
914     int retval;
915
916     /* Bring ofX network device up. */
917     retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
918     if (retval) {
919         fatal(retval, "Could not open %s device", s->of_name);
920     }
921     retval = netdev_turn_flags_on(netdev, NETDEV_UP, true);
922     if (retval) {
923         fatal(retval, "Could not bring %s device up", s->of_name);
924     }
925     netdev_close(netdev);
926
927     /* Initialize DHCP client. */
928     retval = dhclient_create(s->of_name, modify_dhcp_request,
929                              validate_dhcp_offer, (void *) s, &dhcp);
930     if (retval) {
931         fatal(retval, "Failed to initialize DHCP client");
932     }
933     dhclient_init(dhcp, 0);
934
935     d = xmalloc(sizeof *d);
936     d->s = s;
937     d->dhcp = dhcp;
938     d->ever_successful = false;
939     return d;
940 }
941
942 static void
943 discovery_question_connectivity(struct discovery *d)
944 {
945     dhclient_force_renew(d->dhcp, 15);
946 }
947
948 static bool
949 discovery_run(struct discovery *d, char **controller_name)
950 {
951     dhclient_run(d->dhcp);
952     if (!dhclient_changed(d->dhcp)) {
953         return false;
954     }
955
956     dhclient_configure_netdev(d->dhcp);
957     if (d->s->update_resolv_conf) {
958         dhclient_update_resolv_conf(d->dhcp);
959     }
960
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");
970         }
971     }
972     return true;
973 }
974
975 static void
976 discovery_wait(struct discovery *d)
977 {
978     dhclient_wait(d->dhcp);
979 }
980
981 static void
982 modify_dhcp_request(struct dhcp_msg *msg, void *aux)
983 {
984     dhcp_msg_put_string(msg, DHCP_CODE_VENDOR_CLASS, "OpenFlow");
985 }
986
987 static bool
988 validate_dhcp_offer(const struct dhcp_msg *msg, void *s_)
989 {
990     const struct settings *s = s_;
991     char *vconn_name;
992     bool accept;
993
994     vconn_name = dhcp_msg_get_string(msg, DHCP_CODE_OFP_CONTROLLER_VCONN);
995     if (!vconn_name) {
996         VLOG_WARN("rejecting DHCP offer missing controller vconn");
997         return false;
998     }
999     accept = !regexec(&s->accept_controller_regex, vconn_name, 0, NULL, 0);
1000     if (!accept) {
1001         VLOG_WARN("rejecting controller vconn that fails to match %s",
1002                   s->accept_controller_re);
1003     }
1004     free(vconn_name);
1005     return accept;
1006 }
1007 \f
1008 /* User interface. */
1009
1010 static void
1011 parse_options(int argc, char *argv[], struct settings *s)
1012 {
1013     enum {
1014         OPT_ACCEPT_VCONN = UCHAR_MAX + 1,
1015         OPT_NO_RESOLV_CONF,
1016         OPT_INACTIVITY_PROBE,
1017         OPT_MAX_IDLE,
1018         OPT_MAX_BACKOFF,
1019         OPT_RATE_LIMIT,
1020         OPT_BURST_LIMIT
1021     };
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
1038         {0, 0, 0, 0},
1039     };
1040     char *short_options = long_options_to_short_options(long_options);
1041     char *accept_re = NULL;
1042     int retval;
1043
1044     /* Set defaults that we can figure out before parsing options. */
1045     s->listen_vconn_name = NULL;
1046     s->fail_mode = FAIL_OPEN;
1047     s->max_idle = 15;
1048     s->probe_interval = 15;
1049     s->max_backoff = 15;
1050     s->update_resolv_conf = true;
1051     s->rate_limit = 0;
1052     s->burst_limit = 0;
1053     for (;;) {
1054         int c;
1055
1056         c = getopt_long(argc, argv, short_options, long_options, NULL);
1057         if (c == -1) {
1058             break;
1059         }
1060
1061         switch (c) {
1062         case OPT_ACCEPT_VCONN:
1063             accept_re = optarg[0] == '^' ? optarg : xasprintf("^%s", optarg);
1064             break;
1065
1066         case OPT_NO_RESOLV_CONF:
1067             s->update_resolv_conf = false;
1068             break;
1069
1070         case 'f':
1071             if (!strcmp(optarg, "open")) {
1072                 s->fail_mode = FAIL_OPEN;
1073             } else if (!strcmp(optarg, "closed")) {
1074                 s->fail_mode = FAIL_CLOSED;
1075             } else {
1076                 fatal(0,
1077                       "-f or --fail argument must be \"open\" or \"closed\"");
1078             }
1079             break;
1080
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");
1085             }
1086             break;
1087
1088         case OPT_MAX_IDLE:
1089             if (!strcmp(optarg, "permanent")) {
1090                 s->max_idle = OFP_FLOW_PERMANENT;
1091             } else {
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'");
1096                 }
1097             }
1098             break;
1099
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;
1106             }
1107             break;
1108
1109         case OPT_RATE_LIMIT:
1110             if (optarg) {
1111                 s->rate_limit = atoi(optarg);
1112                 if (s->rate_limit < 1) {
1113                     fatal(0, "--rate-limit argument must be at least 1");
1114                 }
1115             } else {
1116                 s->rate_limit = 1000;
1117             }
1118             break;
1119
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");
1124             }
1125             break;
1126
1127         case 'D':
1128             set_detach();
1129             break;
1130
1131         case 'P':
1132             set_pidfile(optarg);
1133             break;
1134
1135         case 'l':
1136             if (s->listen_vconn_name) {
1137                 fatal(0, "-l or --listen may be only specified once");
1138             }
1139             s->listen_vconn_name = optarg;
1140             break;
1141
1142         case 'h':
1143             usage();
1144
1145         case 'V':
1146             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
1147             exit(EXIT_SUCCESS);
1148
1149         case 'v':
1150             vlog_set_verbosity(optarg);
1151             break;
1152
1153         VCONN_SSL_OPTION_HANDLERS
1154
1155         case '?':
1156             exit(EXIT_FAILURE);
1157
1158         default:
1159             abort();
1160         }
1161     }
1162     free(short_options);
1163
1164     argc -= optind;
1165     argv += optind;
1166     if (argc < 1 || argc > 2) {
1167         fatal(0, "need one or two non-option arguments; use --help for usage");
1168     }
1169
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);
1176     }
1177     s->of_name = xasprintf("of%s", s->nl_name + 3);
1178     s->controller_name = argc > 1 ? xstrdup(argv[1]) : NULL;
1179
1180     /* Set accept_controller_regex. */
1181     if (!accept_re) {
1182         accept_re = vconn_ssl_is_configured() ? "^ssl:.*" : ".*";
1183     }
1184     retval = regcomp(&s->accept_controller_regex, accept_re,
1185                      REG_NOSUB | REG_EXTENDED);
1186     if (retval) {
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);
1191     }
1192     s->accept_controller_re = accept_re;
1193
1194     /* Mode of operation. */
1195     s->discovery = s->controller_name == NULL;
1196     if (s->discovery) {
1197         s->in_band = true;
1198     } else {
1199         enum netdev_flags flags;
1200         struct netdev *netdev;
1201
1202         retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
1203         if (retval) {
1204             fatal(retval, "Could not open %s device", s->of_name);
1205         }
1206
1207         retval = netdev_get_flags(netdev, &flags);
1208         if (retval) {
1209             fatal(retval, "Could not get flags for %s device", s->of_name);
1210         }
1211
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",
1215                       s->of_name);
1216         }
1217
1218         netdev_close(netdev);
1219     }
1220
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",
1225                       s->rate_limit);
1226         }
1227         if (!s->burst_limit) {
1228             s->burst_limit = s->rate_limit / 4;
1229         }
1230         s->burst_limit = MAX(s->burst_limit, 1);
1231         s->burst_limit = MIN(s->burst_limit, INT_MAX / 1000);
1232     }
1233 }
1234
1235 static void
1236 usage(void)
1237 {
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",
1268            RUNDIR);
1269     exit(EXIT_SUCCESS);
1270 }