Prevent the secchan from dying due to SIGPIPE.
[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     /* Connect to datapath. */
210     local_rconn = rconn_create(0, s.max_backoff);
211     rconn_connect(local_rconn, s.nl_name);
212
213     /* Connect to controller. */
214     remote_rconn = rconn_create(s.probe_interval, s.max_backoff);
215     if (s.controller_name) {
216         retval = rconn_connect(remote_rconn, s.controller_name);
217         if (retval == EAFNOSUPPORT) {
218             fatal(0, "No support for %s vconn", s.controller_name);
219         }
220     }
221
222     /* Start relaying. */
223     controller_relay = relay_create(local_rconn, remote_rconn, false);
224     list_push_back(&relays, &controller_relay->node);
225
226     /* Set up hooks. */
227     n_hooks = 0;
228     if (s.in_band) {
229         hooks[n_hooks++] = in_band_hook_create(&s);
230     }
231     if (s.fail_mode == FAIL_OPEN) {
232         hooks[n_hooks++] = fail_open_hook_create(&s,
233                                                  local_rconn, remote_rconn);
234     }
235     if (s.rate_limit) {
236         hooks[n_hooks++] = rate_limit_hook_create(&s,
237                                                   local_rconn, remote_rconn);
238     }
239     assert(n_hooks <= ARRAY_SIZE(hooks));
240
241     for (;;) {
242         struct relay *r, *n;
243         size_t i;
244
245         /* Do work. */
246         LIST_FOR_EACH_SAFE (r, n, struct relay, node, &relays) {
247             relay_run(r, hooks, n_hooks);
248         }
249         if (listen_vconn) {
250             for (;;) {
251                 struct relay *r = relay_accept(&s, listen_vconn);
252                 if (!r) {
253                     break;
254                 }
255                 list_push_back(&relays, &r->node);
256             }
257         }
258         for (i = 0; i < n_hooks; i++) {
259             if (hooks[i].periodic_cb) {
260                 hooks[i].periodic_cb(hooks[i].aux);
261             }
262         }
263         if (s.discovery) {
264             char *controller_name;
265             if (rconn_is_connectivity_questionable(remote_rconn)) {
266                 discovery_question_connectivity(discovery);
267             }
268             if (discovery_run(discovery, &controller_name)) {
269                 if (controller_name) {
270                     rconn_connect(remote_rconn, controller_name);
271                 } else {
272                     rconn_disconnect(remote_rconn);
273                 }
274             }
275         }
276
277         /* Wait for something to happen. */
278         LIST_FOR_EACH (r, struct relay, node, &relays) {
279             relay_wait(r);
280         }
281         if (listen_vconn) {
282             vconn_accept_wait(listen_vconn);
283         }
284         for (i = 0; i < n_hooks; i++) {
285             if (hooks[i].wait_cb) {
286                 hooks[i].wait_cb(hooks[i].aux);
287             }
288         }
289         if (discovery) {
290             discovery_wait(discovery);
291         }
292         poll_block();
293     }
294
295     return 0;
296 }
297
298 static struct hook
299 make_hook(bool (*packet_cb)(struct relay *, int half, void *aux),
300           void (*periodic_cb)(void *aux),
301           void (*wait_cb)(void *aux),
302           void *aux)
303 {
304     struct hook h;
305     h.packet_cb = packet_cb;
306     h.periodic_cb = periodic_cb;
307     h.wait_cb = wait_cb;
308     h.aux = aux;
309     return h;
310 }
311 \f
312 /* OpenFlow message relaying. */
313
314 static struct relay *
315 relay_accept(const struct settings *s, struct vconn *listen_vconn)
316 {
317     struct vconn *new_remote, *new_local;
318     char *nl_name_without_subscription;
319     struct rconn *r1, *r2;
320     int retval;
321
322     retval = vconn_accept(listen_vconn, &new_remote);
323     if (retval) {
324         if (retval != EAGAIN) {
325             VLOG_WARN("accept failed (%s)", strerror(retval));
326         }
327         return NULL;
328     }
329
330     /* nl:123 or nl:123:1 opens a netlink connection to local datapath 123.  We
331      * only accept the former syntax in main().
332      *
333      * nl:123:0 opens a netlink connection to local datapath 123 without
334      * obtaining a subscription for ofp_packet_in or ofp_flow_expired
335      * messages.*/
336     nl_name_without_subscription = xasprintf("%s:0", s->nl_name);
337     retval = vconn_open(nl_name_without_subscription, &new_local);
338     if (retval) {
339         VLOG_ERR("could not connect to %s (%s)",
340                  nl_name_without_subscription, strerror(retval));
341         vconn_close(new_remote);
342         free(nl_name_without_subscription);
343         return NULL;
344     }
345
346     /* Create and return relay. */
347     r1 = rconn_create(0, 0);
348     rconn_connect_unreliably(r1, nl_name_without_subscription, new_local);
349     free(nl_name_without_subscription);
350
351     r2 = rconn_create(0, 0);
352     rconn_connect_unreliably(r2, "passive", new_remote);
353
354     return relay_create(r1, r2, true);
355 }
356
357 static struct relay *
358 relay_create(struct rconn *local, struct rconn *remote, bool is_mgmt_conn)
359 {
360     struct relay *r = xcalloc(1, sizeof *r);
361     r->halves[HALF_LOCAL].rconn = local;
362     r->halves[HALF_REMOTE].rconn = remote;
363     r->is_mgmt_conn = is_mgmt_conn;
364     return r;
365 }
366
367 static void
368 relay_run(struct relay *r, const struct hook hooks[], size_t n_hooks)
369 {
370     int iteration;
371     int i;
372
373     for (i = 0; i < 2; i++) {
374         rconn_run(r->halves[i].rconn);
375     }
376
377     /* Limit the number of iterations to prevent other tasks from starving. */
378     for (iteration = 0; iteration < 50; iteration++) {
379         bool progress = false;
380         for (i = 0; i < 2; i++) {
381             struct half *this = &r->halves[i];
382             struct half *peer = &r->halves[!i];
383
384             if (!this->rxbuf) {
385                 this->rxbuf = rconn_recv(this->rconn);
386                 if (this->rxbuf) {
387                     const struct hook *h;
388                     for (h = hooks; h < &hooks[n_hooks]; h++) {
389                         if (h->packet_cb(r, i, h->aux)) {
390                             buffer_delete(this->rxbuf);
391                             this->rxbuf = NULL;
392                             progress = true;
393                             break;
394                         }
395                     }
396                 }
397             }
398
399             if (this->rxbuf && !this->n_txq) {
400                 int retval = rconn_send(peer->rconn, this->rxbuf,
401                                         &this->n_txq);
402                 if (retval != EAGAIN) {
403                     if (!retval) {
404                         progress = true;
405                     } else {
406                         buffer_delete(this->rxbuf);
407                     }
408                     this->rxbuf = NULL;
409                 }
410             }
411         }
412         if (!progress) {
413             break;
414         }
415     }
416
417     if (r->is_mgmt_conn) {
418         for (i = 0; i < 2; i++) {
419             struct half *this = &r->halves[i];
420             if (!rconn_is_alive(this->rconn)) {
421                 relay_destroy(r);
422                 return;
423             }
424         }
425     }
426 }
427
428 static void
429 relay_wait(struct relay *r)
430 {
431     int i;
432
433     for (i = 0; i < 2; i++) {
434         struct half *this = &r->halves[i];
435
436         rconn_run_wait(this->rconn);
437         if (!this->rxbuf) {
438             rconn_recv_wait(this->rconn);
439         }
440     }
441 }
442
443 static void
444 relay_destroy(struct relay *r)
445 {
446     int i;
447
448     list_remove(&r->node);
449     for (i = 0; i < 2; i++) {
450         struct half *this = &r->halves[i];
451         rconn_destroy(this->rconn);
452         buffer_delete(this->rxbuf);
453     }
454     free(r);
455 }
456 \f
457 /* In-band control. */
458
459 struct in_band_data {
460     const struct settings *s;
461     struct mac_learning *ml;
462     struct netdev *of_device;
463     uint8_t mac[ETH_ADDR_LEN];
464     int n_queued;
465 };
466
467 static void
468 queue_tx(struct rconn *rc, struct in_band_data *in_band, struct buffer *b)
469 {
470     rconn_send_with_limit(rc, b, &in_band->n_queued, 10);
471 }
472
473 static const uint8_t *
474 get_controller_mac(struct netdev *netdev, struct rconn *controller)
475 {
476     static uint32_t ip, last_nonzero_ip;
477     static uint8_t mac[ETH_ADDR_LEN], last_nonzero_mac[ETH_ADDR_LEN];
478     static time_t next_refresh = 0;
479
480     uint32_t last_ip = ip;
481
482     time_t now = time_now();
483
484     ip = rconn_get_ip(controller);
485     if (last_ip != ip || !next_refresh || now >= next_refresh) {
486         bool have_mac;
487
488         /* Look up MAC address. */
489         memset(mac, 0, sizeof mac);
490         if (ip) {
491             int retval = netdev_arp_lookup(netdev, ip, mac);
492             if (retval) {
493                 VLOG_DBG("cannot look up controller hw address ("IP_FMT"): %s",
494                          IP_ARGS(&ip), strerror(retval));
495             }
496         }
497         have_mac = !eth_addr_is_zero(mac);
498
499         /* Log changes in IP, MAC addresses. */
500         if (ip && ip != last_nonzero_ip) {
501             VLOG_DBG("controller IP address changed from "IP_FMT
502                      " to "IP_FMT, IP_ARGS(&last_nonzero_ip), IP_ARGS(&ip));
503             last_nonzero_ip = ip;
504         }
505         if (have_mac && memcmp(last_nonzero_mac, mac, ETH_ADDR_LEN)) {
506             VLOG_DBG("controller MAC address changed from "ETH_ADDR_FMT" to "
507                      ETH_ADDR_FMT,
508                      ETH_ADDR_ARGS(last_nonzero_mac), ETH_ADDR_ARGS(mac));
509             memcpy(last_nonzero_mac, mac, ETH_ADDR_LEN);
510         }
511
512         /* Schedule next refresh.
513          *
514          * If we have an IP address but not a MAC address, then refresh
515          * quickly, since we probably will get a MAC address soon (via ARP).
516          * Otherwise, we can afford to wait a little while. */
517         next_refresh = now + (!ip || have_mac ? 10 : 1);
518     }
519     return !eth_addr_is_zero(mac) ? mac : NULL;
520 }
521
522 static bool
523 is_controller_mac(const uint8_t mac[ETH_ADDR_LEN],
524                   const uint8_t *controller_mac)
525 {
526     return controller_mac && eth_addr_equals(mac, controller_mac);
527 }
528
529 static bool
530 in_band_packet_cb(struct relay *r, int half, void *in_band_)
531 {
532     struct in_band_data *in_band = in_band_;
533     struct rconn *rc = r->halves[HALF_LOCAL].rconn;
534     struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
535     struct ofp_packet_in *opi;
536     struct ofp_header *oh;
537     size_t pkt_ofs, pkt_len;
538     struct buffer pkt;
539     struct flow flow;
540     uint16_t in_port, out_port;
541     const uint8_t *controller_mac;
542
543     if (half != HALF_LOCAL || r->is_mgmt_conn) {
544         return false;
545     }
546
547     oh = msg->data;
548     if (oh->type != OFPT_PACKET_IN) {
549         return false;
550     }
551     if (msg->size < offsetof (struct ofp_packet_in, data)) {
552         VLOG_WARN("packet too short (%zu bytes) for packet_in", msg->size);
553         return false;
554     }
555
556     /* Extract flow data from 'opi' into 'flow'. */
557     opi = msg->data;
558     in_port = ntohs(opi->in_port);
559     pkt_ofs = offsetof(struct ofp_packet_in, data);
560     pkt_len = ntohs(opi->header.length) - pkt_ofs;
561     pkt.data = opi->data;
562     pkt.size = pkt_len;
563     flow_extract(&pkt, in_port, &flow);
564
565     /* Deal with local stuff. */
566     controller_mac = get_controller_mac(in_band->of_device,
567                                         r->halves[HALF_REMOTE].rconn);
568     if (in_port == OFPP_LOCAL) {
569         /* Sent by secure channel. */
570         out_port = mac_learning_lookup(in_band->ml, flow.dl_dst);
571     } else if (eth_addr_equals(flow.dl_dst, in_band->mac)) {
572         /* Sent to secure channel. */
573         out_port = OFPP_LOCAL;
574         if (mac_learning_learn(in_band->ml, flow.dl_src, in_port)) {
575             VLOG_DBG("learned that "ETH_ADDR_FMT" is on port %"PRIu16,
576                      ETH_ADDR_ARGS(flow.dl_src), in_port);
577         }
578     } else if (flow.dl_type == htons(ETH_TYPE_ARP)
579                && eth_addr_is_broadcast(flow.dl_dst)
580                && is_controller_mac(flow.dl_src, controller_mac)) {
581         /* ARP sent by controller. */
582         out_port = OFPP_FLOOD;
583     } else if (is_controller_mac(flow.dl_dst, controller_mac)
584                && in_port == mac_learning_lookup(in_band->ml,
585                                                  controller_mac)) {
586         /* Drop controller traffic that arrives on the controller port. */
587         queue_tx(rc, in_band, make_add_flow(&flow, ntohl(opi->buffer_id),
588                                             in_band->s->max_idle, 0));
589         return true;
590     } else {
591         return false;
592     }
593
594     if (out_port != OFPP_FLOOD) {
595         /* The output port is known, so add a new flow. */
596         queue_tx(rc, in_band,
597                  make_add_simple_flow(&flow, ntohl(opi->buffer_id),
598                                       out_port, in_band->s->max_idle));
599
600         /* If the switch didn't buffer the packet, we need to send a copy. */
601         if (ntohl(opi->buffer_id) == UINT32_MAX) {
602             queue_tx(rc, in_band,
603                      make_unbuffered_packet_out(&pkt, in_port, out_port));
604         }
605     } else {
606         /* We don't know that MAC.  Send along the packet without setting up a
607          * flow. */
608         struct buffer *b;
609         if (ntohl(opi->buffer_id) == UINT32_MAX) {
610             b = make_unbuffered_packet_out(&pkt, in_port, out_port);
611         } else {
612             b = make_buffered_packet_out(ntohl(opi->buffer_id),
613                                          in_port, out_port);
614         }
615         queue_tx(rc, in_band, b);
616     }
617     return true;
618 }
619
620 static struct hook
621 in_band_hook_create(const struct settings *s)
622 {
623     struct in_band_data *in_band;
624     int retval;
625
626     in_band = xcalloc(1, sizeof *in_band);
627     in_band->s = s;
628     in_band->ml = mac_learning_create();
629     retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE,
630                          &in_band->of_device);
631     if (retval) {
632         fatal(retval, "Could not open %s device", s->of_name);
633     }
634     memcpy(in_band->mac, netdev_get_etheraddr(in_band->of_device),
635            ETH_ADDR_LEN);
636
637     return make_hook(in_band_packet_cb, NULL, NULL, in_band);
638 }
639 \f
640 /* Fail open support. */
641
642 struct fail_open_data {
643     const struct settings *s;
644     struct rconn *local_rconn;
645     struct rconn *remote_rconn;
646     struct lswitch *lswitch;
647     int last_disconn_secs;
648 };
649
650 /* Causes 'r' to enter or leave fail-open mode, if appropriate. */
651 static void
652 fail_open_periodic_cb(void *fail_open_)
653 {
654     struct fail_open_data *fail_open = fail_open_;
655     int disconn_secs;
656     bool open;
657
658     disconn_secs = rconn_disconnected_duration(fail_open->remote_rconn);
659     open = disconn_secs >= fail_open->s->probe_interval * 3;
660     if (open != (fail_open->lswitch != NULL)) {
661         if (!open) {
662             VLOG_WARN("No longer in fail-open mode");
663             lswitch_destroy(fail_open->lswitch);
664             fail_open->lswitch = NULL;
665         } else {
666             VLOG_WARN("Could not connect to controller for %d seconds, "
667                       "failing open", disconn_secs);
668             fail_open->lswitch = lswitch_create(fail_open->local_rconn, true,
669                                                 fail_open->s->max_idle);
670             fail_open->last_disconn_secs = disconn_secs;
671         }
672     } else if (open && disconn_secs > fail_open->last_disconn_secs + 60) {
673         VLOG_WARN("Still in fail-open mode after %d seconds disconnected "
674                   "from controller", disconn_secs);
675         fail_open->last_disconn_secs = disconn_secs;
676     }
677 }
678
679 static bool
680 fail_open_packet_cb(struct relay *r, int half, void *fail_open_)
681 {
682     struct fail_open_data *fail_open = fail_open_;
683     if (half != HALF_LOCAL || r->is_mgmt_conn || !fail_open->lswitch) {
684         return false;
685     } else {
686         lswitch_process_packet(fail_open->lswitch, fail_open->local_rconn,
687                                r->halves[HALF_LOCAL].rxbuf);
688         rconn_run(fail_open->local_rconn);
689         return true;
690     }
691 }
692
693 static struct hook
694 fail_open_hook_create(const struct settings *s, struct rconn *local_rconn,
695                       struct rconn *remote_rconn)
696 {
697     struct fail_open_data *fail_open = xmalloc(sizeof *fail_open);
698     fail_open->s = s;
699     fail_open->local_rconn = local_rconn;
700     fail_open->remote_rconn = remote_rconn;
701     fail_open->lswitch = NULL;
702     return make_hook(fail_open_packet_cb, fail_open_periodic_cb, NULL,
703                      fail_open);
704 }
705 \f
706 struct rate_limiter {
707     const struct settings *s;
708     struct rconn *remote_rconn;
709
710     /* One queue per physical port. */
711     struct queue queues[OFPP_MAX];
712     int n_queued;               /* Sum over queues[*].n. */
713     int next_tx_port;           /* Next port to check in round-robin. */
714
715     /* Token bucket.
716      *
717      * It costs 1000 tokens to send a single packet_in message.  A single token
718      * per message would be more straightforward, but this choice lets us avoid
719      * round-off error in refill_bucket()'s calculation of how many tokens to
720      * add to the bucket, since no division step is needed. */
721     long long int last_fill;    /* Time at which we last added tokens. */
722     int tokens;                 /* Current number of tokens. */
723
724     /* Transmission queue. */
725     int n_txq;                  /* No. of packets waiting in rconn for tx. */
726 };
727
728 /* Drop a packet from the longest queue in 'rl'. */
729 static void
730 drop_packet(struct rate_limiter *rl)
731 {
732     struct queue *longest;      /* Queue currently selected as longest. */
733     int n_longest;              /* # of queues of same length as 'longest'. */
734     struct queue *q;
735
736     longest = &rl->queues[0];
737     n_longest = 1;
738     for (q = &rl->queues[0]; q < &rl->queues[OFPP_MAX]; q++) {
739         if (longest->n < q->n) {
740             longest = q;
741             n_longest = 1;
742         } else if (longest->n == q->n) {
743             n_longest++;
744
745             /* Randomly select one of the longest queues, with a uniform
746              * distribution (Knuth algorithm 3.4.2R). */
747             if (!random_range(n_longest)) {
748                 longest = q;
749             }
750         }
751     }
752
753     /* FIXME: do we want to pop the tail instead? */
754     buffer_delete(queue_pop_head(longest));
755     rl->n_queued--;
756 }
757
758 /* Remove and return the next packet to transmit (in round-robin order). */
759 static struct buffer *
760 dequeue_packet(struct rate_limiter *rl)
761 {
762     unsigned int i;
763
764     for (i = 0; i < OFPP_MAX; i++) {
765         unsigned int port = (rl->next_tx_port + i) % OFPP_MAX;
766         struct queue *q = &rl->queues[port];
767         if (q->n) {
768             rl->next_tx_port = (port + 1) % OFPP_MAX;
769             rl->n_queued--;
770             return queue_pop_head(q);
771         }
772     }
773     NOT_REACHED();
774 }
775
776 /* Add tokens to the bucket based on elapsed time. */
777 static void
778 refill_bucket(struct rate_limiter *rl)
779 {
780     const struct settings *s = rl->s;
781     long long int now = time_msec();
782     long long int tokens = (now - rl->last_fill) * s->rate_limit + rl->tokens;
783     if (tokens >= 1000) {
784         rl->last_fill = now;
785         rl->tokens = MIN(tokens, s->burst_limit * 1000);
786     }
787 }
788
789 /* Attempts to remove enough tokens from 'rl' to transmit a packet.  Returns
790  * true if successful, false otherwise.  (In the latter case no tokens are
791  * removed.) */
792 static bool
793 get_token(struct rate_limiter *rl)
794 {
795     if (rl->tokens >= 1000) {
796         rl->tokens -= 1000;
797         return true;
798     } else {
799         return false;
800     }
801 }
802
803 static bool
804 rate_limit_packet_cb(struct relay *r, int half, void *rl_)
805 {
806     struct rate_limiter *rl = rl_;
807     const struct settings *s = rl->s;
808     struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
809     struct ofp_header *oh;
810
811     if (half == HALF_REMOTE) {
812         return false;
813     }
814
815     oh = msg->data;
816     if (oh->type != OFPT_PACKET_IN) {
817         return false;
818     }
819     if (msg->size < offsetof(struct ofp_packet_in, data)) {
820         VLOG_WARN("packet too short (%zu bytes) for packet_in", msg->size);
821         return false;
822     }
823
824     if (!rl->n_queued && get_token(rl)) {
825         /* In the common case where we are not constrained by the rate limit,
826          * let the packet take the normal path. */
827         return false;
828     } else {
829         /* Otherwise queue it up for the periodic callback to drain out. */
830         struct ofp_packet_in *opi = msg->data;
831         int port = ntohs(opi->in_port) % OFPP_MAX;
832         if (rl->n_queued >= s->burst_limit) {
833             drop_packet(rl);
834         }
835         queue_push_tail(&rl->queues[port], buffer_clone(msg));
836         rl->n_queued++;
837         return true;
838     }
839 }
840
841 static void
842 rate_limit_periodic_cb(void *rl_)
843 {
844     struct rate_limiter *rl = rl_;
845     int i;
846
847     /* Drain some packets out of the bucket if possible, but limit the number
848      * of iterations to allow other code to get work done too. */
849     refill_bucket(rl);
850     for (i = 0; rl->n_queued && get_token(rl) && i < 50; i++) {
851         /* Use a small, arbitrary limit for the amount of queuing to do here,
852          * because the TCP connection is responsible for buffering and there is
853          * no point in trying to transmit faster than the TCP connection can
854          * handle. */
855         struct buffer *b = dequeue_packet(rl);
856         rconn_send_with_limit(rl->remote_rconn, b, &rl->n_txq, 10);
857     }
858 }
859
860 static void
861 rate_limit_wait_cb(void *rl_)
862 {
863     struct rate_limiter *rl = rl_;
864     if (rl->n_queued) {
865         if (rl->tokens >= 1000) {
866             /* We can transmit more packets as soon as we're called again. */
867             poll_immediate_wake();
868         } else {
869             /* We have to wait for the bucket to re-fill.  We could calculate
870              * the exact amount of time here for increased smoothness. */
871             poll_timer_wait(TIME_UPDATE_INTERVAL / 2);
872         }
873     }
874 }
875
876 static struct hook
877 rate_limit_hook_create(const struct settings *s,
878                        struct rconn *local,
879                        struct rconn *remote)
880 {
881     struct rate_limiter *rl;
882     size_t i;
883
884     rl = xcalloc(1, sizeof *rl);
885     rl->s = s;
886     rl->remote_rconn = remote;
887     for (i = 0; i < ARRAY_SIZE(rl->queues); i++) {
888         queue_init(&rl->queues[i]);
889     }
890     rl->last_fill = time_msec();
891     rl->tokens = s->rate_limit * 100;
892     return make_hook(rate_limit_packet_cb, rate_limit_periodic_cb,
893                      rate_limit_wait_cb, rl);
894 }
895 \f
896 /* Controller discovery. */
897
898 struct discovery
899 {
900     const struct settings *s;
901     struct dhclient *dhcp;
902     bool ever_successful;
903 };
904
905 static struct discovery *
906 discovery_init(const struct settings *s)
907 {
908     struct netdev *netdev;
909     struct discovery *d;
910     struct dhclient *dhcp;
911     int retval;
912
913     /* Bring ofX network device up. */
914     retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
915     if (retval) {
916         fatal(retval, "Could not open %s device", s->of_name);
917     }
918     retval = netdev_turn_flags_on(netdev, NETDEV_UP, true);
919     if (retval) {
920         fatal(retval, "Could not bring %s device up", s->of_name);
921     }
922     netdev_close(netdev);
923
924     /* Initialize DHCP client. */
925     retval = dhclient_create(s->of_name, modify_dhcp_request,
926                              validate_dhcp_offer, (void *) s, &dhcp);
927     if (retval) {
928         fatal(retval, "Failed to initialize DHCP client");
929     }
930     dhclient_init(dhcp, 0);
931
932     d = xmalloc(sizeof *d);
933     d->s = s;
934     d->dhcp = dhcp;
935     d->ever_successful = false;
936     return d;
937 }
938
939 static void
940 discovery_question_connectivity(struct discovery *d)
941 {
942     dhclient_force_renew(d->dhcp, 15);
943 }
944
945 static bool
946 discovery_run(struct discovery *d, char **controller_name)
947 {
948     dhclient_run(d->dhcp);
949     if (!dhclient_changed(d->dhcp)) {
950         return false;
951     }
952
953     dhclient_configure_netdev(d->dhcp);
954     if (d->s->update_resolv_conf) {
955         dhclient_update_resolv_conf(d->dhcp);
956     }
957
958     if (dhclient_is_bound(d->dhcp)) {
959         *controller_name = dhcp_msg_get_string(dhclient_get_config(d->dhcp),
960                                                DHCP_CODE_OFP_CONTROLLER_VCONN);
961         VLOG_WARN("%s: discovered controller", *controller_name);
962         d->ever_successful = true;
963     } else if (controller_name) {
964         *controller_name = NULL;
965         if (d->ever_successful) {
966             VLOG_WARN("discovered controller no longer available");
967         }
968     }
969     return true;
970 }
971
972 static void
973 discovery_wait(struct discovery *d)
974 {
975     dhclient_wait(d->dhcp);
976 }
977
978 static void
979 modify_dhcp_request(struct dhcp_msg *msg, void *aux)
980 {
981     dhcp_msg_put_string(msg, DHCP_CODE_VENDOR_CLASS, "OpenFlow");
982 }
983
984 static bool
985 validate_dhcp_offer(const struct dhcp_msg *msg, void *s_)
986 {
987     const struct settings *s = s_;
988     char *vconn_name;
989     bool accept;
990
991     vconn_name = dhcp_msg_get_string(msg, DHCP_CODE_OFP_CONTROLLER_VCONN);
992     if (!vconn_name) {
993         VLOG_WARN("rejecting DHCP offer missing controller vconn");
994         return false;
995     }
996     accept = !regexec(&s->accept_controller_regex, vconn_name, 0, NULL, 0);
997     if (!accept) {
998         VLOG_WARN("rejecting controller vconn that fails to match %s",
999                   s->accept_controller_re);
1000     }
1001     free(vconn_name);
1002     return accept;
1003 }
1004 \f
1005 /* User interface. */
1006
1007 static void
1008 parse_options(int argc, char *argv[], struct settings *s)
1009 {
1010     enum {
1011         OPT_ACCEPT_VCONN = UCHAR_MAX + 1,
1012         OPT_NO_RESOLV_CONF,
1013         OPT_INACTIVITY_PROBE,
1014         OPT_MAX_IDLE,
1015         OPT_MAX_BACKOFF,
1016         OPT_RATE_LIMIT,
1017         OPT_BURST_LIMIT
1018     };
1019     static struct option long_options[] = {
1020         {"accept-vconn", required_argument, 0, OPT_ACCEPT_VCONN},
1021         {"no-resolv-conf", no_argument, 0, OPT_NO_RESOLV_CONF},
1022         {"fail",        required_argument, 0, 'f'},
1023         {"inactivity-probe", required_argument, 0, OPT_INACTIVITY_PROBE},
1024         {"max-idle",    required_argument, 0, OPT_MAX_IDLE},
1025         {"max-backoff", required_argument, 0, OPT_MAX_BACKOFF},
1026         {"listen",      required_argument, 0, 'l'},
1027         {"rate-limit",  optional_argument, 0, OPT_RATE_LIMIT},
1028         {"burst-limit", required_argument, 0, OPT_BURST_LIMIT},
1029         {"detach",      no_argument, 0, 'D'},
1030         {"pidfile",     optional_argument, 0, 'P'},
1031         {"verbose",     optional_argument, 0, 'v'},
1032         {"help",        no_argument, 0, 'h'},
1033         {"version",     no_argument, 0, 'V'},
1034         VCONN_SSL_LONG_OPTIONS
1035         {0, 0, 0, 0},
1036     };
1037     char *short_options = long_options_to_short_options(long_options);
1038     char *accept_re = NULL;
1039     int retval;
1040
1041     /* Set defaults that we can figure out before parsing options. */
1042     s->listen_vconn_name = NULL;
1043     s->fail_mode = FAIL_OPEN;
1044     s->max_idle = 15;
1045     s->probe_interval = 15;
1046     s->max_backoff = 15;
1047     s->update_resolv_conf = true;
1048     s->rate_limit = 0;
1049     s->burst_limit = 0;
1050     for (;;) {
1051         int c;
1052
1053         c = getopt_long(argc, argv, short_options, long_options, NULL);
1054         if (c == -1) {
1055             break;
1056         }
1057
1058         switch (c) {
1059         case OPT_ACCEPT_VCONN:
1060             accept_re = optarg[0] == '^' ? optarg : xasprintf("^%s", optarg);
1061             break;
1062
1063         case OPT_NO_RESOLV_CONF:
1064             s->update_resolv_conf = false;
1065             break;
1066
1067         case 'f':
1068             if (!strcmp(optarg, "open")) {
1069                 s->fail_mode = FAIL_OPEN;
1070             } else if (!strcmp(optarg, "closed")) {
1071                 s->fail_mode = FAIL_CLOSED;
1072             } else {
1073                 fatal(0,
1074                       "-f or --fail argument must be \"open\" or \"closed\"");
1075             }
1076             break;
1077
1078         case OPT_INACTIVITY_PROBE:
1079             s->probe_interval = atoi(optarg);
1080             if (s->probe_interval < 5) {
1081                 fatal(0, "--inactivity-probe argument must be at least 5");
1082             }
1083             break;
1084
1085         case OPT_MAX_IDLE:
1086             if (!strcmp(optarg, "permanent")) {
1087                 s->max_idle = OFP_FLOW_PERMANENT;
1088             } else {
1089                 s->max_idle = atoi(optarg);
1090                 if (s->max_idle < 1 || s->max_idle > 65535) {
1091                     fatal(0, "--max-idle argument must be between 1 and "
1092                           "65535 or the word 'permanent'");
1093                 }
1094             }
1095             break;
1096
1097         case OPT_MAX_BACKOFF:
1098             s->max_backoff = atoi(optarg);
1099             if (s->max_backoff < 1) {
1100                 fatal(0, "--max-backoff argument must be at least 1");
1101             } else if (s->max_backoff > 3600) {
1102                 s->max_backoff = 3600;
1103             }
1104             break;
1105
1106         case OPT_RATE_LIMIT:
1107             if (optarg) {
1108                 s->rate_limit = atoi(optarg);
1109                 if (s->rate_limit < 1) {
1110                     fatal(0, "--rate-limit argument must be at least 1");
1111                 }
1112             } else {
1113                 s->rate_limit = 1000;
1114             }
1115             break;
1116
1117         case OPT_BURST_LIMIT:
1118             s->burst_limit = atoi(optarg);
1119             if (s->burst_limit < 1) {
1120                 fatal(0, "--burst-limit argument must be at least 1");
1121             }
1122             break;
1123
1124         case 'D':
1125             set_detach();
1126             break;
1127
1128         case 'P':
1129             set_pidfile(optarg);
1130             break;
1131
1132         case 'l':
1133             if (s->listen_vconn_name) {
1134                 fatal(0, "-l or --listen may be only specified once");
1135             }
1136             s->listen_vconn_name = optarg;
1137             break;
1138
1139         case 'h':
1140             usage();
1141
1142         case 'V':
1143             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
1144             exit(EXIT_SUCCESS);
1145
1146         case 'v':
1147             vlog_set_verbosity(optarg);
1148             break;
1149
1150         VCONN_SSL_OPTION_HANDLERS
1151
1152         case '?':
1153             exit(EXIT_FAILURE);
1154
1155         default:
1156             abort();
1157         }
1158     }
1159     free(short_options);
1160
1161     argc -= optind;
1162     argv += optind;
1163     if (argc < 1 || argc > 2) {
1164         fatal(0, "need one or two non-option arguments; use --help for usage");
1165     }
1166
1167     /* Local and remote vconns. */
1168     s->nl_name = argv[0];
1169     if (strncmp(s->nl_name, "nl:", 3)
1170         || strlen(s->nl_name) < 4
1171         || s->nl_name[strspn(s->nl_name + 3, "0123456789") + 3]) {
1172         fatal(0, "%s: argument is not of the form \"nl:DP_IDX\"", s->nl_name);
1173     }
1174     s->of_name = xasprintf("of%s", s->nl_name + 3);
1175     s->controller_name = argc > 1 ? xstrdup(argv[1]) : NULL;
1176
1177     /* Set accept_controller_regex. */
1178     if (!accept_re) {
1179         accept_re = vconn_ssl_is_configured() ? "^ssl:.*" : ".*";
1180     }
1181     retval = regcomp(&s->accept_controller_regex, accept_re,
1182                      REG_NOSUB | REG_EXTENDED);
1183     if (retval) {
1184         size_t length = regerror(retval, &s->accept_controller_regex, NULL, 0);
1185         char *buffer = xmalloc(length);
1186         regerror(retval, &s->accept_controller_regex, buffer, length);
1187         fatal(0, "%s: %s", accept_re, buffer);
1188     }
1189     s->accept_controller_re = accept_re;
1190
1191     /* Mode of operation. */
1192     s->discovery = s->controller_name == NULL;
1193     if (s->discovery) {
1194         s->in_band = true;
1195     } else {
1196         enum netdev_flags flags;
1197         struct netdev *netdev;
1198
1199         retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
1200         if (retval) {
1201             fatal(retval, "Could not open %s device", s->of_name);
1202         }
1203
1204         retval = netdev_get_flags(netdev, &flags);
1205         if (retval) {
1206             fatal(retval, "Could not get flags for %s device", s->of_name);
1207         }
1208
1209         s->in_band = (flags & NETDEV_UP) != 0;
1210         if (s->in_band && netdev_get_in6(netdev, NULL)) {
1211             VLOG_WARN("Ignoring IPv6 address on %s device: IPv6 not supported",
1212                       s->of_name);
1213         }
1214
1215         netdev_close(netdev);
1216     }
1217
1218     /* Rate limiting. */
1219     if (s->rate_limit) {
1220         if (s->rate_limit < 100) {
1221             VLOG_WARN("Rate limit set to unusually low value %d",
1222                       s->rate_limit);
1223         }
1224         if (!s->burst_limit) {
1225             s->burst_limit = s->rate_limit / 4;
1226         }
1227         s->burst_limit = MAX(s->burst_limit, 1);
1228         s->burst_limit = MIN(s->burst_limit, INT_MAX / 1000);
1229     }
1230 }
1231
1232 static void
1233 usage(void)
1234 {
1235     printf("%s: secure channel, a relay for OpenFlow messages.\n"
1236            "usage: %s [OPTIONS] nl:DP_IDX [CONTROLLER]\n"
1237            "where nl:DP_IDX is a datapath that has been added with dpctl.\n"
1238            "CONTROLLER is an active OpenFlow connection method; if it is\n"
1239            "omitted, then secchan performs controller discovery.\n",
1240            program_name, program_name);
1241     vconn_usage(true, true);
1242     printf("\nController discovery options:\n"
1243            "  --accept-vconn=REGEX    accept matching discovered controllers\n"
1244            "  --no-resolv-conf        do not update /etc/resolv.conf\n"
1245            "\nNetworking options:\n"
1246            "  -f, --fail=open|closed  when controller connection fails:\n"
1247            "                            closed: drop all packets\n"
1248            "                            open (default): act as learning switch\n"
1249            "  --inactivity-probe=SECS time between inactivity probes\n"
1250            "  --max-idle=SECS         max idle for flows set up by secchan\n"
1251            "  --max-backoff=SECS      max time between controller connection\n"
1252            "                          attempts (default: 15 seconds)\n"
1253            "  -l, --listen=METHOD     allow management connections on METHOD\n"
1254            "                          (a passive OpenFlow connection method)\n"
1255            "\nRate-limiting of \"packet-in\" messages to the controller:\n"
1256            "  --rate-limit[=PACKETS]  max rate, in packets/s (default: 1000)\n"
1257            "  --burst-limit=BURST     limit on packet credit for idle time\n"
1258            "\nOther options:\n"
1259            "  -D, --detach            run in background as daemon\n"
1260            "  -P, --pidfile[=FILE]    create pidfile (default: %s/secchan.pid)\n"
1261            "  -v, --verbose=MODULE[:FACILITY[:LEVEL]]  set logging levels\n"
1262            "  -v, --verbose           set maximum verbosity level\n"
1263            "  -h, --help              display this help message\n"
1264            "  -V, --version           display version information\n",
1265            RUNDIR);
1266     exit(EXIT_SUCCESS);
1267 }