Implement rate limiting in secchan.
[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 <string.h>
44 #include <time.h>
45 #include <unistd.h>
46
47 #include "buffer.h"
48 #include "command-line.h"
49 #include "compiler.h"
50 #include "daemon.h"
51 #include "dhcp.h"
52 #include "dhcp-client.h"
53 #include "dynamic-string.h"
54 #include "fault.h"
55 #include "flow.h"
56 #include "learning-switch.h"
57 #include "list.h"
58 #include "mac-learning.h"
59 #include "netdev.h"
60 #include "openflow.h"
61 #include "packets.h"
62 #include "poll-loop.h"
63 #include "rconn.h"
64 #include "timeval.h"
65 #include "util.h"
66 #include "vconn-ssl.h"
67 #include "vconn.h"
68 #include "vlog-socket.h"
69
70 #include "vlog.h"
71 #define THIS_MODULE VLM_secchan
72
73 /* Behavior when the connection to the controller fails. */
74 enum fail_mode {
75     FAIL_OPEN,                  /* Act as learning switch. */
76     FAIL_CLOSED                 /* Drop all packets. */
77 };
78
79 /* Settings that may be configured by the user. */
80 struct settings {
81     /* Overall mode of operation. */
82     bool discovery;           /* Discover the controller automatically? */
83     bool in_band;             /* Connect to controller in-band? */
84
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. */
90
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. */
96
97     /* Packet-in rate-limiting. */
98     int rate_limit;           /* Tokens added to bucket per second. */
99     int burst_limit;          /* Maximum number token bucket size. */
100
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? */
105 };
106
107 struct half {
108     struct rconn *rconn;
109     struct buffer *rxbuf;
110     int n_txq;                  /* No. of packets queued for tx on 'rconn'. */
111 };
112
113 struct relay {
114     struct list node;
115
116 #define HALF_LOCAL 0
117 #define HALF_REMOTE 1
118     struct half halves[2];
119
120     bool is_mgmt_conn;
121 };
122
123 struct hook {
124     bool (*packet_cb)(struct relay *, int half, void *aux);
125     void (*periodic_cb)(void *aux);
126     void (*wait_cb)(void *aux);
127     void *aux;
128 };
129
130 static void parse_options(int argc, char *argv[], struct settings *);
131 static void usage(void) NO_RETURN;
132
133 static struct relay *relay_create(struct rconn *local, struct rconn *remote,
134                                   bool is_mgmt_conn);
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 *);
139
140 static struct hook make_hook(bool (*packet_cb)(struct relay *, int, void *),
141                              void (*periodic_cb)(void *),
142                              void (*wait_cb)(void *),
143                              void *aux);
144
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 *);
149
150 static struct hook in_band_hook_create(const struct settings *);
151 static struct hook fail_open_hook_create(const struct settings *,
152                                          struct rconn *local,
153                                          struct rconn *remote);
154 static struct hook rate_limit_hook_create(const struct settings *,
155                                           struct rconn *local,
156                                           struct rconn *remote);
157
158 static void modify_dhcp_request(struct dhcp_msg *, void *aux);
159 static bool validate_dhcp_offer(const struct dhcp_msg *, void *aux);
160
161 int
162 main(int argc, char *argv[])
163 {
164     struct settings s;
165
166     struct list relays = LIST_INITIALIZER(&relays);
167
168     struct hook hooks[4];
169     size_t n_hooks;
170
171     struct rconn *local_rconn, *remote_rconn;
172     struct vconn *listen_vconn;
173     struct relay *controller_relay;
174     struct discovery *discovery;
175     int retval;
176
177     set_program_name(argv[0]);
178     register_fault_handlers();
179     time_init();
180     vlog_init();
181     parse_options(argc, argv, &s);
182
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);
188         }
189         if (!vconn_is_passive(listen_vconn)) {
190             fatal(0, "%s is not a passive vconn", s.listen_vconn_name);
191         }
192     } else {
193         listen_vconn = NULL;
194     }
195
196     /* Start controller discovery. */
197     discovery = s.discovery ? discovery_init(&s) : NULL;
198
199     /* Start listening for vlogconf requests. */
200     retval = vlog_server_listen(NULL, NULL);
201     if (retval) {
202         fatal(retval, "Could not listen for vlog connections");
203     }
204
205     daemonize();
206
207     /* Connect to datapath. */
208     local_rconn = rconn_create(0, s.max_backoff);
209     rconn_connect(local_rconn, s.nl_name);
210
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);
217         }
218     }
219
220     /* Start relaying. */
221     controller_relay = relay_create(local_rconn, remote_rconn, false);
222     list_push_back(&relays, &controller_relay->node);
223
224     /* Set up hooks. */
225     n_hooks = 0;
226     if (s.in_band) {
227         hooks[n_hooks++] = in_band_hook_create(&s);
228     }
229     if (s.fail_mode == FAIL_OPEN) {
230         hooks[n_hooks++] = fail_open_hook_create(&s,
231                                                  local_rconn, remote_rconn);
232     }
233     if (s.rate_limit) {
234         hooks[n_hooks++] = rate_limit_hook_create(&s,
235                                                   local_rconn, remote_rconn);
236     }
237     assert(n_hooks <= ARRAY_SIZE(hooks));
238
239     for (;;) {
240         struct relay *r, *n;
241         size_t i;
242
243         /* Do work. */
244         LIST_FOR_EACH_SAFE (r, n, struct relay, node, &relays) {
245             relay_run(r, hooks, n_hooks);
246         }
247         if (listen_vconn) {
248             for (;;) {
249                 struct relay *r = relay_accept(&s, listen_vconn);
250                 if (!r) {
251                     break;
252                 }
253                 list_push_back(&relays, &r->node);
254             }
255         }
256         for (i = 0; i < n_hooks; i++) {
257             if (hooks[i].periodic_cb) {
258                 hooks[i].periodic_cb(hooks[i].aux);
259             }
260         }
261         if (s.discovery) {
262             char *controller_name;
263             if (rconn_is_connectivity_questionable(remote_rconn)) {
264                 discovery_question_connectivity(discovery);
265             }
266             if (discovery_run(discovery, &controller_name)) {
267                 if (controller_name) {
268                     rconn_connect(remote_rconn, controller_name);
269                 } else {
270                     rconn_disconnect(remote_rconn);
271                 }
272             }
273         }
274
275         /* Wait for something to happen. */
276         LIST_FOR_EACH (r, struct relay, node, &relays) {
277             relay_wait(r);
278         }
279         if (listen_vconn) {
280             vconn_accept_wait(listen_vconn);
281         }
282         for (i = 0; i < n_hooks; i++) {
283             if (hooks[i].wait_cb) {
284                 hooks[i].wait_cb(hooks[i].aux);
285             }
286         }
287         if (discovery) {
288             discovery_wait(discovery);
289         }
290         poll_block();
291     }
292
293     return 0;
294 }
295
296 static struct hook
297 make_hook(bool (*packet_cb)(struct relay *, int half, void *aux),
298           void (*periodic_cb)(void *aux),
299           void (*wait_cb)(void *aux),
300           void *aux)
301 {
302     struct hook h;
303     h.packet_cb = packet_cb;
304     h.periodic_cb = periodic_cb;
305     h.wait_cb = wait_cb;
306     h.aux = aux;
307     return h;
308 }
309 \f
310 /* OpenFlow message relaying. */
311
312 static struct relay *
313 relay_accept(const struct settings *s, struct vconn *listen_vconn)
314 {
315     struct vconn *new_remote, *new_local;
316     char *nl_name_without_subscription;
317     struct rconn *r1, *r2;
318     int retval;
319
320     retval = vconn_accept(listen_vconn, &new_remote);
321     if (retval) {
322         if (retval != EAGAIN) {
323             VLOG_WARN("accept failed (%s)", strerror(retval));
324         }
325         return NULL;
326     }
327
328     /* nl:123 or nl:123:1 opens a netlink connection to local datapath 123.  We
329      * only accept the former syntax in main().
330      *
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
333      * messages.*/
334     nl_name_without_subscription = xasprintf("%s:0", s->nl_name);
335     retval = vconn_open(nl_name_without_subscription, &new_local);
336     if (retval) {
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);
341         return NULL;
342     }
343
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);
348
349     r2 = rconn_create(0, 0);
350     rconn_connect_unreliably(r2, "passive", new_remote);
351
352     return relay_create(r1, r2, true);
353 }
354
355 static struct relay *
356 relay_create(struct rconn *local, struct rconn *remote, bool is_mgmt_conn)
357 {
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;
362     return r;
363 }
364
365 static void
366 relay_run(struct relay *r, const struct hook hooks[], size_t n_hooks)
367 {
368     int iteration;
369     int i;
370
371     for (i = 0; i < 2; i++) {
372         rconn_run(r->halves[i].rconn);
373     }
374
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];
381
382             if (!this->rxbuf) {
383                 this->rxbuf = rconn_recv(this->rconn);
384                 if (this->rxbuf) {
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);
389                             this->rxbuf = NULL;
390                             progress = true;
391                             break;
392                         }
393                     }
394                 }
395             }
396
397             if (this->rxbuf && !this->n_txq) {
398                 int retval = rconn_send(peer->rconn, this->rxbuf,
399                                         &this->n_txq);
400                 if (retval != EAGAIN) {
401                     if (!retval) {
402                         progress = true;
403                     } else {
404                         buffer_delete(this->rxbuf);
405                     }
406                     this->rxbuf = NULL;
407                 }
408             }
409         }
410         if (!progress) {
411             break;
412         }
413     }
414
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)) {
419                 relay_destroy(r);
420                 return;
421             }
422         }
423     }
424 }
425
426 static void
427 relay_wait(struct relay *r)
428 {
429     int i;
430
431     for (i = 0; i < 2; i++) {
432         struct half *this = &r->halves[i];
433
434         rconn_run_wait(this->rconn);
435         if (!this->rxbuf) {
436             rconn_recv_wait(this->rconn);
437         }
438     }
439 }
440
441 static void
442 relay_destroy(struct relay *r)
443 {
444     int i;
445
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);
451     }
452     free(r);
453 }
454 \f
455 /* In-band control. */
456
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];
462     int n_queued;
463 };
464
465 static void
466 queue_tx(struct rconn *rc, struct in_band_data *in_band, struct buffer *b)
467 {
468     rconn_send_with_limit(rc, b, &in_band->n_queued, 10);
469 }
470
471 static const uint8_t *
472 get_controller_mac(struct netdev *netdev, struct rconn *controller)
473 {
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;
477
478     uint32_t last_ip = ip;
479
480     time_t now = time_now();
481
482     ip = rconn_get_ip(controller);
483     if (last_ip != ip || !next_refresh || now >= next_refresh) {
484         bool have_mac;
485
486         /* Look up MAC address. */
487         memset(mac, 0, sizeof mac);
488         if (ip) {
489             int retval = netdev_arp_lookup(netdev, ip, mac);
490             if (retval) {
491                 VLOG_DBG("cannot look up controller hw address ("IP_FMT"): %s",
492                          IP_ARGS(&ip), strerror(retval));
493             }
494         }
495         have_mac = !eth_addr_is_zero(mac);
496
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;
502         }
503         if (have_mac && memcmp(last_nonzero_mac, mac, ETH_ADDR_LEN)) {
504             VLOG_DBG("controller MAC address changed from "ETH_ADDR_FMT" to "
505                      ETH_ADDR_FMT,
506                      ETH_ADDR_ARGS(last_nonzero_mac), ETH_ADDR_ARGS(mac));
507             memcpy(last_nonzero_mac, mac, ETH_ADDR_LEN);
508         }
509
510         /* Schedule next refresh.
511          *
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);
516     }
517     return !eth_addr_is_zero(mac) ? mac : NULL;
518 }
519
520 static bool
521 is_controller_mac(const uint8_t mac[ETH_ADDR_LEN],
522                   const uint8_t *controller_mac)
523 {
524     return controller_mac && eth_addr_equals(mac, controller_mac);
525 }
526
527 static bool
528 in_band_packet_cb(struct relay *r, int half, void *in_band_)
529 {
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;
536     struct buffer pkt;
537     struct flow flow;
538     uint16_t in_port, out_port;
539     const uint8_t *controller_mac;
540
541     if (half != HALF_LOCAL || r->is_mgmt_conn) {
542         return false;
543     }
544
545     oh = msg->data;
546     if (oh->type != OFPT_PACKET_IN) {
547         return false;
548     }
549     if (msg->size < offsetof (struct ofp_packet_in, data)) {
550         VLOG_WARN("packet too short (%zu bytes) for packet_in", msg->size);
551         return false;
552     }
553
554     /* Extract flow data from 'opi' into 'flow'. */
555     opi = msg->data;
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;
560     pkt.size = pkt_len;
561     flow_extract(&pkt, in_port, &flow);
562
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);
575         }
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,
583                                                  controller_mac)) {
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));
587         return true;
588     } else {
589         return false;
590     }
591
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));
597
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));
602         }
603     } else {
604         /* We don't know that MAC.  Send along the packet without setting up a
605          * flow. */
606         struct buffer *b;
607         if (ntohl(opi->buffer_id) == UINT32_MAX) {
608             b = make_unbuffered_packet_out(&pkt, in_port, out_port);
609         } else {
610             b = make_buffered_packet_out(ntohl(opi->buffer_id),
611                                          in_port, out_port);
612         }
613         queue_tx(rc, in_band, b);
614     }
615     return true;
616 }
617
618 static struct hook
619 in_band_hook_create(const struct settings *s)
620 {
621     struct in_band_data *in_band;
622     int retval;
623
624     in_band = xcalloc(1, sizeof *in_band);
625     in_band->s = s;
626     in_band->ml = mac_learning_create();
627     retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE,
628                          &in_band->of_device);
629     if (retval) {
630         fatal(retval, "Could not open %s device", s->of_name);
631     }
632     memcpy(in_band->mac, netdev_get_etheraddr(in_band->of_device),
633            ETH_ADDR_LEN);
634
635     return make_hook(in_band_packet_cb, NULL, NULL, in_band);
636 }
637 \f
638 /* Fail open support. */
639
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;
646 };
647
648 /* Causes 'r' to enter or leave fail-open mode, if appropriate. */
649 static void
650 fail_open_periodic_cb(void *fail_open_)
651 {
652     struct fail_open_data *fail_open = fail_open_;
653     int disconn_secs;
654     bool open;
655
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)) {
659         if (!open) {
660             VLOG_WARN("No longer in fail-open mode");
661             lswitch_destroy(fail_open->lswitch);
662             fail_open->lswitch = NULL;
663         } else {
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;
669         }
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;
674     }
675 }
676
677 static bool
678 fail_open_packet_cb(struct relay *r, int half, void *fail_open_)
679 {
680     struct fail_open_data *fail_open = fail_open_;
681     if (half != HALF_LOCAL || r->is_mgmt_conn || !fail_open->lswitch) {
682         return false;
683     } else {
684         lswitch_process_packet(fail_open->lswitch, fail_open->local_rconn,
685                                r->halves[HALF_LOCAL].rxbuf);
686         rconn_run(fail_open->local_rconn);
687         return true;
688     }
689 }
690
691 static struct hook
692 fail_open_hook_create(const struct settings *s, struct rconn *local_rconn,
693                       struct rconn *remote_rconn)
694 {
695     struct fail_open_data *fail_open = xmalloc(sizeof *fail_open);
696     fail_open->s = s;
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,
701                      fail_open);
702 }
703 \f
704 struct rate_limiter {
705     const struct settings *s;
706     struct rconn *remote_rconn;
707
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. */
712
713     /* Token bucket.
714      *
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. */
721
722     /* Transmission queue. */
723     int n_txq;                  /* No. of packets waiting in rconn for tx. */
724 };
725
726 /* Drop a packet from the longest queue in 'rl'. */
727 static void
728 drop_packet(struct rate_limiter *rl)
729 {
730     struct queue *longest;      /* Queue currently selected as longest. */
731     int n_longest;              /* # of queues of same length as 'longest'. */
732     struct queue *q;
733
734     longest = &rl->queues[0];
735     n_longest = 1;
736     for (q = &rl->queues[0]; q < &rl->queues[OFPP_MAX]; q++) {
737         if (longest->n < q->n) {
738             longest = q;
739             n_longest = 1;
740         } else if (longest->n == q->n) {
741             n_longest++;
742
743             /* Randomly select one of the longest queues, with a uniform
744              * distribution (Knuth algorithm 3.4.2R). */
745             if (!random_range(n_longest)) {
746                 longest = q;
747             }
748         }
749     }
750
751     /* FIXME: do we want to pop the tail instead? */
752     buffer_delete(queue_pop_head(longest));
753     rl->n_queued--;
754 }
755
756 /* Remove and return the next packet to transmit (in round-robin order). */
757 static struct buffer *
758 dequeue_packet(struct rate_limiter *rl)
759 {
760     unsigned int i;
761
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];
765         if (q->n) {
766             rl->next_tx_port = (port + 1) % OFPP_MAX;
767             rl->n_queued--;
768             return queue_pop_head(q);
769         }
770     }
771     NOT_REACHED();
772 }
773
774 /* Add tokens to the bucket based on elapsed time. */
775 static void
776 refill_bucket(struct rate_limiter *rl)
777 {
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) {
782         rl->last_fill = now;
783         rl->tokens = MIN(tokens, s->burst_limit * 1000);
784     }
785 }
786
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
789  * removed.) */
790 static bool
791 get_token(struct rate_limiter *rl)
792 {
793     if (rl->tokens >= 1000) {
794         rl->tokens -= 1000;
795         return true;
796     } else {
797         return false;
798     }
799 }
800
801 static bool
802 rate_limit_packet_cb(struct relay *r, int half, void *rl_)
803 {
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;
808
809     if (half == HALF_REMOTE) {
810         return false;
811     }
812
813     oh = msg->data;
814     if (oh->type != OFPT_PACKET_IN) {
815         return false;
816     }
817     if (msg->size < offsetof(struct ofp_packet_in, data)) {
818         VLOG_WARN("packet too short (%zu bytes) for packet_in", msg->size);
819         return false;
820     }
821
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. */
825         return false;
826     } else {
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) {
831             drop_packet(rl);
832         }
833         queue_push_tail(&rl->queues[port], buffer_clone(msg));
834         rl->n_queued++;
835         return true;
836     }
837 }
838
839 static void
840 rate_limit_periodic_cb(void *rl_)
841 {
842     struct rate_limiter *rl = rl_;
843     int i;
844
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. */
847     refill_bucket(rl);
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
852          * handle. */
853         struct buffer *b = dequeue_packet(rl);
854         rconn_send_with_limit(rl->remote_rconn, b, &rl->n_txq, 10);
855     }
856 }
857
858 static void
859 rate_limit_wait_cb(void *rl_)
860 {
861     struct rate_limiter *rl = rl_;
862     if (rl->n_queued) {
863         if (rl->tokens >= 1000) {
864             /* We can transmit more packets as soon as we're called again. */
865             poll_immediate_wake();
866         } else {
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);
870         }
871     }
872 }
873
874 static struct hook
875 rate_limit_hook_create(const struct settings *s,
876                        struct rconn *local,
877                        struct rconn *remote)
878 {
879     struct rate_limiter *rl;
880     size_t i;
881
882     rl = xcalloc(1, sizeof *rl);
883     rl->s = s;
884     rl->remote_rconn = remote;
885     for (i = 0; i < ARRAY_SIZE(rl->queues); i++) {
886         queue_init(&rl->queues[i]);
887     }
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);
892 }
893 \f
894 /* Controller discovery. */
895
896 struct discovery
897 {
898     const struct settings *s;
899     struct dhclient *dhcp;
900     bool ever_successful;
901 };
902
903 static struct discovery *
904 discovery_init(const struct settings *s)
905 {
906     struct netdev *netdev;
907     struct discovery *d;
908     struct dhclient *dhcp;
909     int retval;
910
911     /* Bring ofX network device up. */
912     retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
913     if (retval) {
914         fatal(retval, "Could not open %s device", s->of_name);
915     }
916     retval = netdev_turn_flags_on(netdev, NETDEV_UP, true);
917     if (retval) {
918         fatal(retval, "Could not bring %s device up", s->of_name);
919     }
920     netdev_close(netdev);
921
922     /* Initialize DHCP client. */
923     retval = dhclient_create(s->of_name, modify_dhcp_request,
924                              validate_dhcp_offer, (void *) s, &dhcp);
925     if (retval) {
926         fatal(retval, "Failed to initialize DHCP client");
927     }
928     dhclient_init(dhcp, 0);
929
930     d = xmalloc(sizeof *d);
931     d->s = s;
932     d->dhcp = dhcp;
933     d->ever_successful = false;
934     return d;
935 }
936
937 static void
938 discovery_question_connectivity(struct discovery *d)
939 {
940     dhclient_force_renew(d->dhcp, 15);
941 }
942
943 static bool
944 discovery_run(struct discovery *d, char **controller_name)
945 {
946     dhclient_run(d->dhcp);
947     if (!dhclient_changed(d->dhcp)) {
948         return false;
949     }
950
951     dhclient_configure_netdev(d->dhcp);
952     if (d->s->update_resolv_conf) {
953         dhclient_update_resolv_conf(d->dhcp);
954     }
955
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");
965         }
966     }
967     return true;
968 }
969
970 static void
971 discovery_wait(struct discovery *d)
972 {
973     dhclient_wait(d->dhcp);
974 }
975
976 static void
977 modify_dhcp_request(struct dhcp_msg *msg, void *aux)
978 {
979     dhcp_msg_put_string(msg, DHCP_CODE_VENDOR_CLASS, "OpenFlow");
980 }
981
982 static bool
983 validate_dhcp_offer(const struct dhcp_msg *msg, void *s_)
984 {
985     const struct settings *s = s_;
986     char *vconn_name;
987     bool accept;
988
989     vconn_name = dhcp_msg_get_string(msg, DHCP_CODE_OFP_CONTROLLER_VCONN);
990     if (!vconn_name) {
991         VLOG_WARN("rejecting DHCP offer missing controller vconn");
992         return false;
993     }
994     accept = !regexec(&s->accept_controller_regex, vconn_name, 0, NULL, 0);
995     if (!accept) {
996         VLOG_WARN("rejecting controller vconn that fails to match %s",
997                   s->accept_controller_re);
998     }
999     free(vconn_name);
1000     return accept;
1001 }
1002 \f
1003 /* User interface. */
1004
1005 static void
1006 parse_options(int argc, char *argv[], struct settings *s)
1007 {
1008     enum {
1009         OPT_ACCEPT_VCONN = UCHAR_MAX + 1,
1010         OPT_NO_RESOLV_CONF,
1011         OPT_INACTIVITY_PROBE,
1012         OPT_MAX_IDLE,
1013         OPT_MAX_BACKOFF,
1014         OPT_RATE_LIMIT,
1015         OPT_BURST_LIMIT
1016     };
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
1033         {0, 0, 0, 0},
1034     };
1035     char *short_options = long_options_to_short_options(long_options);
1036     char *accept_re = NULL;
1037     int retval;
1038
1039     /* Set defaults that we can figure out before parsing options. */
1040     s->listen_vconn_name = NULL;
1041     s->fail_mode = FAIL_OPEN;
1042     s->max_idle = 15;
1043     s->probe_interval = 15;
1044     s->max_backoff = 15;
1045     s->update_resolv_conf = true;
1046     s->rate_limit = 0;
1047     s->burst_limit = 0;
1048     for (;;) {
1049         int c;
1050
1051         c = getopt_long(argc, argv, short_options, long_options, NULL);
1052         if (c == -1) {
1053             break;
1054         }
1055
1056         switch (c) {
1057         case OPT_ACCEPT_VCONN:
1058             accept_re = optarg[0] == '^' ? optarg : xasprintf("^%s", optarg);
1059             break;
1060
1061         case OPT_NO_RESOLV_CONF:
1062             s->update_resolv_conf = false;
1063             break;
1064
1065         case 'f':
1066             if (!strcmp(optarg, "open")) {
1067                 s->fail_mode = FAIL_OPEN;
1068             } else if (!strcmp(optarg, "closed")) {
1069                 s->fail_mode = FAIL_CLOSED;
1070             } else {
1071                 fatal(0,
1072                       "-f or --fail argument must be \"open\" or \"closed\"");
1073             }
1074             break;
1075
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");
1080             }
1081             break;
1082
1083         case OPT_MAX_IDLE:
1084             if (!strcmp(optarg, "permanent")) {
1085                 s->max_idle = OFP_FLOW_PERMANENT;
1086             } else {
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'");
1091                 }
1092             }
1093             break;
1094
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;
1101             }
1102             break;
1103
1104         case OPT_RATE_LIMIT:
1105             if (optarg) {
1106                 s->rate_limit = atoi(optarg);
1107                 if (s->rate_limit < 1) {
1108                     fatal(0, "--rate-limit argument must be at least 1");
1109                 }
1110             } else {
1111                 s->rate_limit = 1000;
1112             }
1113             break;
1114
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");
1119             }
1120             break;
1121
1122         case 'D':
1123             set_detach();
1124             break;
1125
1126         case 'P':
1127             set_pidfile(optarg);
1128             break;
1129
1130         case 'l':
1131             if (s->listen_vconn_name) {
1132                 fatal(0, "-l or --listen may be only specified once");
1133             }
1134             s->listen_vconn_name = optarg;
1135             break;
1136
1137         case 'h':
1138             usage();
1139
1140         case 'V':
1141             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
1142             exit(EXIT_SUCCESS);
1143
1144         case 'v':
1145             vlog_set_verbosity(optarg);
1146             break;
1147
1148         VCONN_SSL_OPTION_HANDLERS
1149
1150         case '?':
1151             exit(EXIT_FAILURE);
1152
1153         default:
1154             abort();
1155         }
1156     }
1157     free(short_options);
1158
1159     argc -= optind;
1160     argv += optind;
1161     if (argc < 1 || argc > 2) {
1162         fatal(0, "need one or two non-option arguments; use --help for usage");
1163     }
1164
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);
1171     }
1172     s->of_name = xasprintf("of%s", s->nl_name + 3);
1173     s->controller_name = argc > 1 ? xstrdup(argv[1]) : NULL;
1174
1175     /* Set accept_controller_regex. */
1176     if (!accept_re) {
1177         accept_re = vconn_ssl_is_configured() ? "^ssl:.*" : ".*";
1178     }
1179     retval = regcomp(&s->accept_controller_regex, accept_re,
1180                      REG_NOSUB | REG_EXTENDED);
1181     if (retval) {
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);
1186     }
1187     s->accept_controller_re = accept_re;
1188
1189     /* Mode of operation. */
1190     s->discovery = s->controller_name == NULL;
1191     if (s->discovery) {
1192         s->in_band = true;
1193     } else {
1194         enum netdev_flags flags;
1195         struct netdev *netdev;
1196
1197         retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
1198         if (retval) {
1199             fatal(retval, "Could not open %s device", s->of_name);
1200         }
1201
1202         retval = netdev_get_flags(netdev, &flags);
1203         if (retval) {
1204             fatal(retval, "Could not get flags for %s device", s->of_name);
1205         }
1206
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",
1210                       s->of_name);
1211         }
1212
1213         netdev_close(netdev);
1214     }
1215
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",
1220                       s->rate_limit);
1221         }
1222
1223         if (!s->burst_limit) {
1224             s->burst_limit = s->rate_limit * 2;
1225         } else if (s->burst_limit < s->rate_limit) {
1226             VLOG_WARN("Burst limit (%d) set lower than rate limit (%d)",
1227                       s->burst_limit, s->rate_limit);
1228         }
1229         s->burst_limit = MIN(s->burst_limit, INT_MAX / 1000);
1230     }
1231 }
1232
1233 static void
1234 usage(void)
1235 {
1236     printf("%s: secure channel, a relay for OpenFlow messages.\n"
1237            "usage: %s [OPTIONS] nl:DP_IDX [CONTROLLER]\n"
1238            "where nl:DP_IDX is a datapath that has been added with dpctl.\n"
1239            "CONTROLLER is an active OpenFlow connection method; if it is\n"
1240            "omitted, then secchan performs controller discovery.\n",
1241            program_name, program_name);
1242     vconn_usage(true, true);
1243     printf("\nController discovery options:\n"
1244            "  --accept-vconn=REGEX    accept matching discovered controllers\n"
1245            "  --no-resolv-conf        do not update /etc/resolv.conf\n"
1246            "\nNetworking options:\n"
1247            "  -f, --fail=open|closed  when controller connection fails:\n"
1248            "                            closed: drop all packets\n"
1249            "                            open (default): act as learning switch\n"
1250            "  --inactivity-probe=SECS time between inactivity probes\n"
1251            "  --max-idle=SECS         max idle for flows set up by secchan\n"
1252            "  --max-backoff=SECS      max time between controller connection\n"
1253            "                          attempts (default: 15 seconds)\n"
1254            "  -l, --listen=METHOD     allow management connections on METHOD\n"
1255            "                          (a passive OpenFlow connection method)\n"
1256            "\nRate-limiting of \"packet-in\" messages to the controller:\n"
1257            "  --rate-limit[=PACKETS]  max rate, in packets/s (default: 1000)\n"
1258            "  --burst-limit=BURST     limit on packet credit for idle time\n"
1259            "\nOther options:\n"
1260            "  -D, --detach            run in background as daemon\n"
1261            "  -P, --pidfile[=FILE]    create pidfile (default: %s/secchan.pid)\n"
1262            "  -v, --verbose=MODULE[:FACILITY[:LEVEL]]  set logging levels\n"
1263            "  -v, --verbose           set maximum verbosity level\n"
1264            "  -h, --help              display this help message\n"
1265            "  -V, --version           display version information\n",
1266            RUNDIR);
1267     exit(EXIT_SUCCESS);
1268 }