Do not send in-band control traffic to the controller.
[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 /* Maximum number of management connection listeners. */
81 #define MAX_MGMT 8
82
83 /* Settings that may be configured by the user. */
84 struct settings {
85     /* Overall mode of operation. */
86     bool discovery;           /* Discover the controller automatically? */
87     bool in_band;             /* Connect to controller in-band? */
88
89     /* Related vconns and network devices. */
90     const char *nl_name;        /* Local datapath (must be "nl:" vconn). */
91     char *of_name;              /* ofX network device name. */
92     const char *controller_name; /* Controller (if not discovery mode). */
93     const char *listener_names[MAX_MGMT]; /* Listen for mgmt connections. */
94     size_t n_listeners;          /* Number of mgmt connection listeners. */
95
96     /* Failure behavior. */
97     enum fail_mode fail_mode; /* Act as learning switch if no controller? */
98     int max_idle;             /* Idle time for flows in fail-open mode. */
99     int probe_interval;       /* # seconds idle before sending echo request. */
100     int max_backoff;          /* Max # seconds between connection attempts. */
101
102     /* Packet-in rate-limiting. */
103     int rate_limit;           /* Tokens added to bucket per second. */
104     int burst_limit;          /* Maximum number token bucket size. */
105
106     /* Discovery behavior. */
107     regex_t accept_controller_regex;  /* Controller vconns to accept. */
108     const char *accept_controller_re; /* String version of regex. */
109     bool update_resolv_conf;          /* Update /etc/resolv.conf? */
110 };
111
112 struct half {
113     struct rconn *rconn;
114     struct buffer *rxbuf;
115     int n_txq;                  /* No. of packets queued for tx on 'rconn'. */
116 };
117
118 struct relay {
119     struct list node;
120
121 #define HALF_LOCAL 0
122 #define HALF_REMOTE 1
123     struct half halves[2];
124
125     bool is_mgmt_conn;
126 };
127
128 struct hook {
129     bool (*packet_cb)(struct relay *, int half, void *aux);
130     void (*periodic_cb)(void *aux);
131     void (*wait_cb)(void *aux);
132     void *aux;
133 };
134
135 static struct vlog_rate_limit vrl = VLOG_RATE_LIMIT_INIT(60, 60);
136
137 static void parse_options(int argc, char *argv[], struct settings *);
138 static void usage(void) NO_RETURN;
139
140 static struct relay *relay_create(struct rconn *local, struct rconn *remote,
141                                   bool is_mgmt_conn);
142 static struct relay *relay_accept(const struct settings *, struct vconn *);
143 static void relay_run(struct relay *, const struct hook[], size_t n_hooks);
144 static void relay_wait(struct relay *);
145 static void relay_destroy(struct relay *);
146
147 static struct hook make_hook(bool (*packet_cb)(struct relay *, int, void *),
148                              void (*periodic_cb)(void *),
149                              void (*wait_cb)(void *),
150                              void *aux);
151
152 struct switch_status;
153 struct status_reply;
154 static struct hook switch_status_hook_create(const struct settings *,
155                                              struct switch_status **);
156 static void switch_status_register_category(struct switch_status *,
157                                             const char *category,
158                                             void (*cb)(struct status_reply *,
159                                                        void *aux),
160                                             void *aux);
161 static void status_reply_put(struct status_reply *, const char *, ...)
162     PRINTF_FORMAT(2, 3);
163
164 static void rconn_status_cb(struct status_reply *, void *rconn_);
165
166 static struct discovery *discovery_init(const struct settings *,
167                                         struct switch_status *);
168 static void discovery_question_connectivity(struct discovery *);
169 static bool discovery_run(struct discovery *, char **controller_name);
170 static void discovery_wait(struct discovery *);
171
172 static struct hook in_band_hook_create(const struct settings *,
173                                        struct switch_status *,
174                                        struct rconn *remote);
175 static struct hook fail_open_hook_create(const struct settings *,
176                                          struct switch_status *,
177                                          struct rconn *local,
178                                          struct rconn *remote);
179 static struct hook rate_limit_hook_create(const struct settings *,
180                                           struct switch_status *,
181                                           struct rconn *local,
182                                           struct rconn *remote);
183
184
185 static void modify_dhcp_request(struct dhcp_msg *, void *aux);
186 static bool validate_dhcp_offer(const struct dhcp_msg *, void *aux);
187
188 int
189 main(int argc, char *argv[])
190 {
191     struct settings s;
192
193     struct list relays = LIST_INITIALIZER(&relays);
194
195     struct hook hooks[8];
196     size_t n_hooks = 0;
197
198     struct vconn *listeners[MAX_MGMT];
199     size_t n_listeners;
200
201     struct rconn *local_rconn, *remote_rconn;
202     struct relay *controller_relay;
203     struct discovery *discovery;
204     struct switch_status *switch_status;
205     int i;
206     int retval;
207
208     set_program_name(argv[0]);
209     register_fault_handlers();
210     time_init();
211     vlog_init();
212     parse_options(argc, argv, &s);
213     signal(SIGPIPE, SIG_IGN);
214
215     /* Start listening for management connections. */
216     n_listeners = 0;
217     for (i = 0; i < s.n_listeners; i++) {
218         const char *name = s.listener_names[i];
219         struct vconn *listener;
220         retval = vconn_open(name, &listener);
221         if (retval && retval != EAGAIN) {
222             fatal(retval, "opening %s", name);
223         }
224         if (!vconn_is_passive(listener)) {
225             fatal(0, "%s is not a passive vconn", name);
226         }
227         listeners[n_listeners++] = listener;
228     }
229
230     /* Initialize switch status hook. */
231     hooks[n_hooks++] = switch_status_hook_create(&s, &switch_status);
232
233     /* Start controller discovery. */
234     discovery = s.discovery ? discovery_init(&s, switch_status) : NULL;
235
236     /* Start listening for vlogconf requests. */
237     retval = vlog_server_listen(NULL, NULL);
238     if (retval) {
239         fatal(retval, "Could not listen for vlog connections");
240     }
241
242     die_if_already_running();
243     daemonize();
244
245     VLOG_WARN("OpenFlow reference implementation version %s", VERSION);
246     VLOG_WARN("OpenFlow protocol version 0x%02x", OFP_VERSION);
247
248     /* Connect to datapath. */
249     local_rconn = rconn_create(0, s.max_backoff);
250     rconn_connect(local_rconn, s.nl_name);
251     switch_status_register_category(switch_status, "local",
252                                     rconn_status_cb, local_rconn);
253
254     /* Connect to controller. */
255     remote_rconn = rconn_create(s.probe_interval, s.max_backoff);
256     if (s.controller_name) {
257         retval = rconn_connect(remote_rconn, s.controller_name);
258         if (retval == EAFNOSUPPORT) {
259             fatal(0, "No support for %s vconn", s.controller_name);
260         }
261     }
262     switch_status_register_category(switch_status, "remote",
263                                     rconn_status_cb, remote_rconn);
264
265     /* Start relaying. */
266     controller_relay = relay_create(local_rconn, remote_rconn, false);
267     list_push_back(&relays, &controller_relay->node);
268
269     /* Set up hooks. */
270     if (s.in_band) {
271         hooks[n_hooks++] = in_band_hook_create(&s, switch_status,
272                                                remote_rconn);
273     }
274     if (s.fail_mode == FAIL_OPEN) {
275         hooks[n_hooks++] = fail_open_hook_create(&s, switch_status,
276                                                  local_rconn, remote_rconn);
277     }
278     if (s.rate_limit) {
279         hooks[n_hooks++] = rate_limit_hook_create(&s, switch_status,
280                                                   local_rconn, remote_rconn);
281     }
282     assert(n_hooks <= ARRAY_SIZE(hooks));
283
284     for (;;) {
285         struct relay *r, *n;
286         size_t i;
287
288         /* Do work. */
289         LIST_FOR_EACH_SAFE (r, n, struct relay, node, &relays) {
290             relay_run(r, hooks, n_hooks);
291         }
292         for (i = 0; i < n_listeners; i++) {
293             for (;;) {
294                 struct relay *r = relay_accept(&s, listeners[i]);
295                 if (!r) {
296                     break;
297                 }
298                 list_push_back(&relays, &r->node);
299             }
300         }
301         for (i = 0; i < n_hooks; i++) {
302             if (hooks[i].periodic_cb) {
303                 hooks[i].periodic_cb(hooks[i].aux);
304             }
305         }
306         if (s.discovery) {
307             char *controller_name;
308             if (rconn_is_connectivity_questionable(remote_rconn)) {
309                 discovery_question_connectivity(discovery);
310             }
311             if (discovery_run(discovery, &controller_name)) {
312                 if (controller_name) {
313                     rconn_connect(remote_rconn, controller_name);
314                 } else {
315                     rconn_disconnect(remote_rconn);
316                 }
317             }
318         }
319
320         /* Wait for something to happen. */
321         LIST_FOR_EACH (r, struct relay, node, &relays) {
322             relay_wait(r);
323         }
324         for (i = 0; i < n_listeners; i++) {
325             vconn_accept_wait(listeners[i]);
326         }
327         for (i = 0; i < n_hooks; i++) {
328             if (hooks[i].wait_cb) {
329                 hooks[i].wait_cb(hooks[i].aux);
330             }
331         }
332         if (discovery) {
333             discovery_wait(discovery);
334         }
335         poll_block();
336     }
337
338     return 0;
339 }
340
341 static struct hook
342 make_hook(bool (*packet_cb)(struct relay *, int half, void *aux),
343           void (*periodic_cb)(void *aux),
344           void (*wait_cb)(void *aux),
345           void *aux)
346 {
347     struct hook h;
348     h.packet_cb = packet_cb;
349     h.periodic_cb = periodic_cb;
350     h.wait_cb = wait_cb;
351     h.aux = aux;
352     return h;
353 }
354 \f
355 /* OpenFlow message relaying. */
356
357 static struct relay *
358 relay_accept(const struct settings *s, struct vconn *listen_vconn)
359 {
360     struct vconn *new_remote, *new_local;
361     char *nl_name_without_subscription;
362     struct rconn *r1, *r2;
363     int retval;
364
365     retval = vconn_accept(listen_vconn, &new_remote);
366     if (retval) {
367         if (retval != EAGAIN) {
368             VLOG_WARN_RL(&vrl, "accept failed (%s)", strerror(retval));
369         }
370         return NULL;
371     }
372
373     /* nl:123 or nl:123:1 opens a netlink connection to local datapath 123.  We
374      * only accept the former syntax in main().
375      *
376      * nl:123:0 opens a netlink connection to local datapath 123 without
377      * obtaining a subscription for ofp_packet_in or ofp_flow_expired
378      * messages.*/
379     nl_name_without_subscription = xasprintf("%s:0", s->nl_name);
380     retval = vconn_open(nl_name_without_subscription, &new_local);
381     if (retval) {
382         VLOG_ERR_RL(&vrl, "could not connect to %s (%s)",
383                     nl_name_without_subscription, strerror(retval));
384         vconn_close(new_remote);
385         free(nl_name_without_subscription);
386         return NULL;
387     }
388
389     /* Create and return relay. */
390     r1 = rconn_create(0, 0);
391     rconn_connect_unreliably(r1, nl_name_without_subscription, new_local);
392     free(nl_name_without_subscription);
393
394     r2 = rconn_create(0, 0);
395     rconn_connect_unreliably(r2, "passive", new_remote);
396
397     return relay_create(r1, r2, true);
398 }
399
400 static struct relay *
401 relay_create(struct rconn *local, struct rconn *remote, bool is_mgmt_conn)
402 {
403     struct relay *r = xcalloc(1, sizeof *r);
404     r->halves[HALF_LOCAL].rconn = local;
405     r->halves[HALF_REMOTE].rconn = remote;
406     r->is_mgmt_conn = is_mgmt_conn;
407     return r;
408 }
409
410 static void
411 relay_run(struct relay *r, const struct hook hooks[], size_t n_hooks)
412 {
413     int iteration;
414     int i;
415
416     for (i = 0; i < 2; i++) {
417         rconn_run(r->halves[i].rconn);
418     }
419
420     /* Limit the number of iterations to prevent other tasks from starving. */
421     for (iteration = 0; iteration < 50; iteration++) {
422         bool progress = false;
423         for (i = 0; i < 2; i++) {
424             struct half *this = &r->halves[i];
425             struct half *peer = &r->halves[!i];
426
427             if (!this->rxbuf) {
428                 this->rxbuf = rconn_recv(this->rconn);
429                 if (this->rxbuf) {
430                     const struct hook *h;
431                     for (h = hooks; h < &hooks[n_hooks]; h++) {
432                         if (h->packet_cb(r, i, h->aux)) {
433                             buffer_delete(this->rxbuf);
434                             this->rxbuf = NULL;
435                             progress = true;
436                             break;
437                         }
438                     }
439                 }
440             }
441
442             if (this->rxbuf && !this->n_txq) {
443                 int retval = rconn_send(peer->rconn, this->rxbuf,
444                                         &this->n_txq);
445                 if (retval != EAGAIN) {
446                     if (!retval) {
447                         progress = true;
448                     } else {
449                         buffer_delete(this->rxbuf);
450                     }
451                     this->rxbuf = NULL;
452                 }
453             }
454         }
455         if (!progress) {
456             break;
457         }
458     }
459
460     if (r->is_mgmt_conn) {
461         for (i = 0; i < 2; i++) {
462             struct half *this = &r->halves[i];
463             if (!rconn_is_alive(this->rconn)) {
464                 relay_destroy(r);
465                 return;
466             }
467         }
468     }
469 }
470
471 static void
472 relay_wait(struct relay *r)
473 {
474     int i;
475
476     for (i = 0; i < 2; i++) {
477         struct half *this = &r->halves[i];
478
479         rconn_run_wait(this->rconn);
480         if (!this->rxbuf) {
481             rconn_recv_wait(this->rconn);
482         }
483     }
484 }
485
486 static void
487 relay_destroy(struct relay *r)
488 {
489     int i;
490
491     list_remove(&r->node);
492     for (i = 0; i < 2; i++) {
493         struct half *this = &r->halves[i];
494         rconn_destroy(this->rconn);
495         buffer_delete(this->rxbuf);
496     }
497     free(r);
498 }
499 \f
500 /* In-band control. */
501
502 struct in_band_data {
503     const struct settings *s;
504     struct mac_learning *ml;
505     struct netdev *of_device;
506     struct rconn *controller;
507     uint8_t mac[ETH_ADDR_LEN];
508     int n_queued;
509 };
510
511 static void
512 queue_tx(struct rconn *rc, struct in_band_data *in_band, struct buffer *b)
513 {
514     rconn_send_with_limit(rc, b, &in_band->n_queued, 10);
515 }
516
517 static const uint8_t *
518 get_controller_mac(struct in_band_data *in_band)
519 {
520     static uint32_t ip, last_nonzero_ip;
521     static uint8_t mac[ETH_ADDR_LEN], last_nonzero_mac[ETH_ADDR_LEN];
522     static time_t next_refresh = 0;
523
524     uint32_t last_ip = ip;
525
526     time_t now = time_now();
527
528     ip = rconn_get_ip(in_band->controller);
529     if (last_ip != ip || !next_refresh || now >= next_refresh) {
530         bool have_mac;
531
532         /* Look up MAC address. */
533         memset(mac, 0, sizeof mac);
534         if (ip) {
535             int retval = netdev_arp_lookup(in_band->of_device, ip, mac);
536             if (retval) {
537                 VLOG_DBG("cannot look up controller hw address ("IP_FMT"): %s",
538                          IP_ARGS(&ip), strerror(retval));
539             }
540         }
541         have_mac = !eth_addr_is_zero(mac);
542
543         /* Log changes in IP, MAC addresses. */
544         if (ip && ip != last_nonzero_ip) {
545             VLOG_DBG("controller IP address changed from "IP_FMT
546                      " to "IP_FMT, IP_ARGS(&last_nonzero_ip), IP_ARGS(&ip));
547             last_nonzero_ip = ip;
548         }
549         if (have_mac && memcmp(last_nonzero_mac, mac, ETH_ADDR_LEN)) {
550             VLOG_DBG("controller MAC address changed from "ETH_ADDR_FMT" to "
551                      ETH_ADDR_FMT,
552                      ETH_ADDR_ARGS(last_nonzero_mac), ETH_ADDR_ARGS(mac));
553             memcpy(last_nonzero_mac, mac, ETH_ADDR_LEN);
554         }
555
556         /* Schedule next refresh.
557          *
558          * If we have an IP address but not a MAC address, then refresh
559          * quickly, since we probably will get a MAC address soon (via ARP).
560          * Otherwise, we can afford to wait a little while. */
561         next_refresh = now + (!ip || have_mac ? 10 : 1);
562     }
563     return !eth_addr_is_zero(mac) ? mac : NULL;
564 }
565
566 static bool
567 is_controller_mac(const uint8_t dl_addr[ETH_ADDR_LEN],
568                   struct in_band_data *in_band)
569 {
570     const uint8_t *mac = get_controller_mac(in_band);
571     return mac && eth_addr_equals(mac, dl_addr);
572 }
573
574 static void
575 in_band_learn_mac(struct in_band_data *in_band, const struct flow *flow)
576 {
577     uint16_t in_port = ntohs(flow->in_port);
578     if (mac_learning_learn(in_band->ml, flow->dl_src, in_port)) {
579         VLOG_DBG_RL(&vrl, "learned that "ETH_ADDR_FMT" is on port %"PRIu16,
580                     ETH_ADDR_ARGS(flow->dl_src), in_port);
581     }
582 }
583
584 static bool
585 in_band_packet_cb(struct relay *r, int half, void *in_band_)
586 {
587     struct in_band_data *in_band = in_band_;
588     struct rconn *rc = r->halves[HALF_LOCAL].rconn;
589     struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
590     struct ofp_packet_in *opi;
591     struct ofp_header *oh;
592     size_t pkt_ofs, pkt_len;
593     struct buffer pkt;
594     struct flow flow;
595     uint16_t in_port, out_port;
596     const uint8_t *controller_mac;
597
598     if (half != HALF_LOCAL || r->is_mgmt_conn) {
599         return false;
600     }
601
602     oh = msg->data;
603     if (oh->type != OFPT_PACKET_IN) {
604         return false;
605     }
606     if (msg->size < offsetof(struct ofp_packet_in, data)) {
607         VLOG_WARN_RL(&vrl, "packet too short (%zu bytes) for packet_in",
608                      msg->size);
609         return false;
610     }
611
612     /* Extract flow data from 'opi' into 'flow'. */
613     opi = msg->data;
614     in_port = ntohs(opi->in_port);
615     pkt_ofs = offsetof(struct ofp_packet_in, data);
616     pkt_len = ntohs(opi->header.length) - pkt_ofs;
617     pkt.data = opi->data;
618     pkt.size = pkt_len;
619     flow_extract(&pkt, in_port, &flow);
620
621     /* Deal with local stuff. */
622     controller_mac = get_controller_mac(in_band);
623     if (in_port == OFPP_LOCAL) {
624         /* Sent by secure channel. */
625         out_port = mac_learning_lookup(in_band->ml, flow.dl_dst);
626     } else if (eth_addr_equals(flow.dl_dst, in_band->mac)) {
627         /* Sent to secure channel. */
628         out_port = OFPP_LOCAL;
629         in_band_learn_mac(in_band, &flow);
630     } else if (flow.dl_type == htons(ETH_TYPE_ARP)
631                && eth_addr_is_broadcast(flow.dl_dst)
632                && is_controller_mac(flow.dl_src, in_band)) {
633         /* ARP sent by controller. */
634         out_port = OFPP_FLOOD;
635     } else if (is_controller_mac(flow.dl_dst, in_band)
636                || is_controller_mac(flow.dl_src, in_band)) {
637         /* Traffic to or from controller.  Switch it by hand. */
638         in_band_learn_mac(in_band, &flow);
639         out_port = mac_learning_lookup(in_band->ml, controller_mac);
640     } else {
641         return false;
642     }
643
644     if (in_port == out_port) {
645         /* The input and output port match.  Set up a flow to drop packets. */
646         queue_tx(rc, in_band, make_add_flow(&flow, ntohl(opi->buffer_id),
647                                           in_band->s->max_idle, 0));
648     } else if (out_port != OFPP_FLOOD) {
649         /* The output port is known, so add a new flow. */
650         queue_tx(rc, in_band,
651                  make_add_simple_flow(&flow, ntohl(opi->buffer_id),
652                                       out_port, in_band->s->max_idle));
653
654         /* If the switch didn't buffer the packet, we need to send a copy. */
655         if (ntohl(opi->buffer_id) == UINT32_MAX) {
656             queue_tx(rc, in_band,
657                      make_unbuffered_packet_out(&pkt, in_port, out_port));
658         }
659     } else {
660         /* We don't know that MAC.  Send along the packet without setting up a
661          * flow. */
662         struct buffer *b;
663         if (ntohl(opi->buffer_id) == UINT32_MAX) {
664             b = make_unbuffered_packet_out(&pkt, in_port, out_port);
665         } else {
666             b = make_buffered_packet_out(ntohl(opi->buffer_id),
667                                          in_port, out_port);
668         }
669         queue_tx(rc, in_band, b);
670     }
671     return true;
672 }
673
674 static void
675 in_band_status_cb(struct status_reply *sr, void *in_band_)
676 {
677     struct in_band_data *in_band = in_band_;
678     struct in_addr local_ip;
679     uint32_t controller_ip;
680     const uint8_t *controller_mac;
681
682     if (netdev_get_in4(in_band->of_device, &local_ip)) {
683         status_reply_put(sr, "local-ip="IP_FMT, IP_ARGS(&local_ip.s_addr));
684     }
685     status_reply_put(sr, "local-mac="ETH_ADDR_FMT,
686                      ETH_ADDR_ARGS(in_band->mac));
687
688     controller_ip = rconn_get_ip(in_band->controller);
689     if (controller_ip) {
690         status_reply_put(sr, "controller-ip="IP_FMT,
691                       IP_ARGS(&controller_ip));
692     }
693     controller_mac = get_controller_mac(in_band);
694     if (controller_mac) {
695         status_reply_put(sr, "controller-mac="ETH_ADDR_FMT,
696                       ETH_ADDR_ARGS(controller_mac));
697     }
698 }
699
700 static struct hook
701 in_band_hook_create(const struct settings *s, struct switch_status *ss,
702                     struct rconn *remote)
703 {
704     struct in_band_data *in_band;
705     int retval;
706
707     in_band = xcalloc(1, sizeof *in_band);
708     in_band->s = s;
709     in_band->ml = mac_learning_create();
710     retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE,
711                          &in_band->of_device);
712     if (retval) {
713         fatal(retval, "Could not open %s device", s->of_name);
714     }
715     memcpy(in_band->mac, netdev_get_etheraddr(in_band->of_device),
716            ETH_ADDR_LEN);
717     in_band->controller = remote;
718     switch_status_register_category(ss, "in-band", in_band_status_cb, in_band);
719     return make_hook(in_band_packet_cb, NULL, NULL, in_band);
720 }
721 \f
722 /* Fail open support. */
723
724 struct fail_open_data {
725     const struct settings *s;
726     struct rconn *local_rconn;
727     struct rconn *remote_rconn;
728     struct lswitch *lswitch;
729     int last_disconn_secs;
730 };
731
732 /* Causes 'r' to enter or leave fail-open mode, if appropriate. */
733 static void
734 fail_open_periodic_cb(void *fail_open_)
735 {
736     struct fail_open_data *fail_open = fail_open_;
737     int disconn_secs;
738     bool open;
739
740     disconn_secs = rconn_disconnected_duration(fail_open->remote_rconn);
741     open = disconn_secs >= fail_open->s->probe_interval * 3;
742     if (open != (fail_open->lswitch != NULL)) {
743         if (!open) {
744             VLOG_WARN("No longer in fail-open mode");
745             lswitch_destroy(fail_open->lswitch);
746             fail_open->lswitch = NULL;
747         } else {
748             VLOG_WARN("Could not connect to controller for %d seconds, "
749                       "failing open", disconn_secs);
750             fail_open->lswitch = lswitch_create(fail_open->local_rconn, true,
751                                                 fail_open->s->max_idle);
752             fail_open->last_disconn_secs = disconn_secs;
753         }
754     } else if (open && disconn_secs > fail_open->last_disconn_secs + 60) {
755         VLOG_WARN("Still in fail-open mode after %d seconds disconnected "
756                   "from controller", disconn_secs);
757         fail_open->last_disconn_secs = disconn_secs;
758     }
759 }
760
761 static bool
762 fail_open_packet_cb(struct relay *r, int half, void *fail_open_)
763 {
764     struct fail_open_data *fail_open = fail_open_;
765     if (half != HALF_LOCAL || r->is_mgmt_conn || !fail_open->lswitch) {
766         return false;
767     } else {
768         lswitch_process_packet(fail_open->lswitch, fail_open->local_rconn,
769                                r->halves[HALF_LOCAL].rxbuf);
770         rconn_run(fail_open->local_rconn);
771         return true;
772     }
773 }
774
775 static void
776 fail_open_status_cb(struct status_reply *sr, void *fail_open_)
777 {
778     struct fail_open_data *fail_open = fail_open_;
779     const struct settings *s = fail_open->s;
780     int trigger_duration = s->probe_interval * 3;
781     int cur_duration = rconn_disconnected_duration(fail_open->remote_rconn);
782
783     status_reply_put(sr, "trigger-duration=%d", trigger_duration);
784     status_reply_put(sr, "current-duration=%d", cur_duration);
785     status_reply_put(sr, "triggered=%s",
786                      cur_duration >= trigger_duration ? "true" : "false");
787     status_reply_put(sr, "max-idle=%d", s->max_idle);
788 }
789
790 static struct hook
791 fail_open_hook_create(const struct settings *s, struct switch_status *ss,
792                       struct rconn *local_rconn, struct rconn *remote_rconn)
793 {
794     struct fail_open_data *fail_open = xmalloc(sizeof *fail_open);
795     fail_open->s = s;
796     fail_open->local_rconn = local_rconn;
797     fail_open->remote_rconn = remote_rconn;
798     fail_open->lswitch = NULL;
799     switch_status_register_category(ss, "fail-open",
800                                     fail_open_status_cb, fail_open);
801     return make_hook(fail_open_packet_cb, fail_open_periodic_cb, NULL,
802                      fail_open);
803 }
804 \f
805 struct rate_limiter {
806     const struct settings *s;
807     struct rconn *remote_rconn;
808
809     /* One queue per physical port. */
810     struct queue queues[OFPP_MAX];
811     int n_queued;               /* Sum over queues[*].n. */
812     int next_tx_port;           /* Next port to check in round-robin. */
813
814     /* Token bucket.
815      *
816      * It costs 1000 tokens to send a single packet_in message.  A single token
817      * per message would be more straightforward, but this choice lets us avoid
818      * round-off error in refill_bucket()'s calculation of how many tokens to
819      * add to the bucket, since no division step is needed. */
820     long long int last_fill;    /* Time at which we last added tokens. */
821     int tokens;                 /* Current number of tokens. */
822
823     /* Transmission queue. */
824     int n_txq;                  /* No. of packets waiting in rconn for tx. */
825
826     /* Statistics reporting. */
827     unsigned long long n_normal;        /* # txed w/o rate limit queuing. */
828     unsigned long long n_limited;       /* # queued for rate limiting. */
829     unsigned long long n_queue_dropped; /* # dropped due to queue overflow. */
830     unsigned long long n_tx_dropped;    /* # dropped due to tx overflow. */
831 };
832
833 /* Drop a packet from the longest queue in 'rl'. */
834 static void
835 drop_packet(struct rate_limiter *rl)
836 {
837     struct queue *longest;      /* Queue currently selected as longest. */
838     int n_longest;              /* # of queues of same length as 'longest'. */
839     struct queue *q;
840
841     longest = &rl->queues[0];
842     n_longest = 1;
843     for (q = &rl->queues[0]; q < &rl->queues[OFPP_MAX]; q++) {
844         if (longest->n < q->n) {
845             longest = q;
846             n_longest = 1;
847         } else if (longest->n == q->n) {
848             n_longest++;
849
850             /* Randomly select one of the longest queues, with a uniform
851              * distribution (Knuth algorithm 3.4.2R). */
852             if (!random_range(n_longest)) {
853                 longest = q;
854             }
855         }
856     }
857
858     /* FIXME: do we want to pop the tail instead? */
859     buffer_delete(queue_pop_head(longest));
860     rl->n_queued--;
861 }
862
863 /* Remove and return the next packet to transmit (in round-robin order). */
864 static struct buffer *
865 dequeue_packet(struct rate_limiter *rl)
866 {
867     unsigned int i;
868
869     for (i = 0; i < OFPP_MAX; i++) {
870         unsigned int port = (rl->next_tx_port + i) % OFPP_MAX;
871         struct queue *q = &rl->queues[port];
872         if (q->n) {
873             rl->next_tx_port = (port + 1) % OFPP_MAX;
874             rl->n_queued--;
875             return queue_pop_head(q);
876         }
877     }
878     NOT_REACHED();
879 }
880
881 /* Add tokens to the bucket based on elapsed time. */
882 static void
883 refill_bucket(struct rate_limiter *rl)
884 {
885     const struct settings *s = rl->s;
886     long long int now = time_msec();
887     long long int tokens = (now - rl->last_fill) * s->rate_limit + rl->tokens;
888     if (tokens >= 1000) {
889         rl->last_fill = now;
890         rl->tokens = MIN(tokens, s->burst_limit * 1000);
891     }
892 }
893
894 /* Attempts to remove enough tokens from 'rl' to transmit a packet.  Returns
895  * true if successful, false otherwise.  (In the latter case no tokens are
896  * removed.) */
897 static bool
898 get_token(struct rate_limiter *rl)
899 {
900     if (rl->tokens >= 1000) {
901         rl->tokens -= 1000;
902         return true;
903     } else {
904         return false;
905     }
906 }
907
908 static bool
909 rate_limit_packet_cb(struct relay *r, int half, void *rl_)
910 {
911     struct rate_limiter *rl = rl_;
912     const struct settings *s = rl->s;
913     struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
914     struct ofp_header *oh;
915
916     if (half == HALF_REMOTE) {
917         return false;
918     }
919
920     oh = msg->data;
921     if (oh->type != OFPT_PACKET_IN) {
922         return false;
923     }
924     if (msg->size < offsetof(struct ofp_packet_in, data)) {
925         VLOG_WARN_RL(&vrl, "packet too short (%zu bytes) for packet_in",
926                      msg->size);
927         return false;
928     }
929
930     if (!rl->n_queued && get_token(rl)) {
931         /* In the common case where we are not constrained by the rate limit,
932          * let the packet take the normal path. */
933         rl->n_normal++;
934         return false;
935     } else {
936         /* Otherwise queue it up for the periodic callback to drain out. */
937         struct ofp_packet_in *opi = msg->data;
938         int port = ntohs(opi->in_port) % OFPP_MAX;
939         if (rl->n_queued >= s->burst_limit) {
940             drop_packet(rl);
941         }
942         queue_push_tail(&rl->queues[port], buffer_clone(msg));
943         rl->n_queued++;
944         rl->n_limited++;
945         return true;
946     }
947 }
948
949 static void
950 rate_limit_status_cb(struct status_reply *sr, void *rl_)
951 {
952     struct rate_limiter *rl = rl_;
953
954     status_reply_put(sr, "normal=%llu", rl->n_normal);
955     status_reply_put(sr, "limited=%llu", rl->n_limited);
956     status_reply_put(sr, "queue-dropped=%llu", rl->n_queue_dropped);
957     status_reply_put(sr, "tx-dropped=%llu", rl->n_tx_dropped);
958 }
959
960 static void
961 rate_limit_periodic_cb(void *rl_)
962 {
963     struct rate_limiter *rl = rl_;
964     int i;
965
966     /* Drain some packets out of the bucket if possible, but limit the number
967      * of iterations to allow other code to get work done too. */
968     refill_bucket(rl);
969     for (i = 0; rl->n_queued && get_token(rl) && i < 50; i++) {
970         /* Use a small, arbitrary limit for the amount of queuing to do here,
971          * because the TCP connection is responsible for buffering and there is
972          * no point in trying to transmit faster than the TCP connection can
973          * handle. */
974         struct buffer *b = dequeue_packet(rl);
975         if (rconn_send_with_limit(rl->remote_rconn, b, &rl->n_txq, 10)) {
976             rl->n_tx_dropped++;
977         }
978     }
979 }
980
981 static void
982 rate_limit_wait_cb(void *rl_)
983 {
984     struct rate_limiter *rl = rl_;
985     if (rl->n_queued) {
986         if (rl->tokens >= 1000) {
987             /* We can transmit more packets as soon as we're called again. */
988             poll_immediate_wake();
989         } else {
990             /* We have to wait for the bucket to re-fill.  We could calculate
991              * the exact amount of time here for increased smoothness. */
992             poll_timer_wait(TIME_UPDATE_INTERVAL / 2);
993         }
994     }
995 }
996
997 static struct hook
998 rate_limit_hook_create(const struct settings *s, struct switch_status *ss,
999                        struct rconn *local, struct rconn *remote)
1000 {
1001     struct rate_limiter *rl;
1002     size_t i;
1003
1004     rl = xcalloc(1, sizeof *rl);
1005     rl->s = s;
1006     rl->remote_rconn = remote;
1007     for (i = 0; i < ARRAY_SIZE(rl->queues); i++) {
1008         queue_init(&rl->queues[i]);
1009     }
1010     rl->last_fill = time_msec();
1011     rl->tokens = s->rate_limit * 100;
1012     switch_status_register_category(ss, "rate-limit",
1013                                     rate_limit_status_cb, rl);
1014     return make_hook(rate_limit_packet_cb, rate_limit_periodic_cb,
1015                      rate_limit_wait_cb, rl);
1016 }
1017 \f
1018 /* OFPST_SWITCH statistics. */
1019
1020 struct switch_status_category {
1021     char *name;
1022     void (*cb)(struct status_reply *, void *aux);
1023     void *aux;
1024 };
1025
1026 struct switch_status {
1027     const struct settings *s;
1028     time_t booted;
1029     struct switch_status_category categories[8];
1030     int n_categories;
1031 };
1032
1033 struct status_reply {
1034     struct switch_status_category *category;
1035     struct ds request;
1036     struct ds output;
1037 };
1038
1039 static bool
1040 switch_status_packet_cb(struct relay *r, int half, void *ss_)
1041 {
1042     struct switch_status *ss = ss_;
1043     struct rconn *rc = r->halves[HALF_REMOTE].rconn;
1044     struct buffer *msg = r->halves[HALF_REMOTE].rxbuf;
1045     struct switch_status_category *c;
1046     struct ofp_stats_request *osr;
1047     struct ofp_stats_reply *reply;
1048     struct status_reply sr;
1049     struct ofp_header *oh;
1050     struct buffer *b;
1051     int retval;
1052
1053     if (half == HALF_LOCAL) {
1054         return false;
1055     }
1056
1057     oh = msg->data;
1058     if (oh->type != OFPT_STATS_REQUEST) {
1059         return false;
1060     }
1061     if (msg->size < sizeof(struct ofp_stats_request)) {
1062         VLOG_WARN_RL(&vrl, "packet too short (%zu bytes) for stats_request",
1063                      msg->size);
1064         return false;
1065     }
1066
1067     osr = msg->data;
1068     if (osr->type != htons(OFPST_SWITCH)) {
1069         return false;
1070     }
1071
1072     sr.request.string = (void *) (osr + 1);
1073     sr.request.length = msg->size - sizeof *osr;
1074     ds_init(&sr.output);
1075     for (c = ss->categories; c < &ss->categories[ss->n_categories]; c++) {
1076         if (!memcmp(c->name, sr.request.string,
1077                     MIN(strlen(c->name), sr.request.length))) {
1078             sr.category = c;
1079             c->cb(&sr, c->aux);
1080         }
1081     }
1082     reply = make_openflow_xid((offsetof(struct ofp_stats_reply, body)
1083                                + sr.output.length),
1084                               OFPT_STATS_REPLY, osr->header.xid, &b);
1085     reply->type = htons(OFPST_SWITCH);
1086     reply->flags = 0;
1087     memcpy(reply->body, sr.output.string, sr.output.length);
1088     retval = rconn_send(rc, b, NULL);
1089     if (retval && retval != EAGAIN) {
1090         VLOG_WARN("send failed (%s)", strerror(retval));
1091     }
1092     ds_destroy(&sr.output);
1093     return true;
1094 }
1095
1096 static void
1097 rconn_status_cb(struct status_reply *sr, void *rconn_)
1098 {
1099     struct rconn *rconn = rconn_;
1100     time_t now = time_now();
1101
1102     status_reply_put(sr, "name=%s", rconn_get_name(rconn));
1103     status_reply_put(sr, "state=%s", rconn_get_state(rconn));
1104     status_reply_put(sr, "backoff=%d", rconn_get_backoff(rconn));
1105     status_reply_put(sr, "is-connected=%s",
1106                      rconn_is_connected(rconn) ? "true" : "false");
1107     status_reply_put(sr, "sent-msgs=%u", rconn_packets_sent(rconn));
1108     status_reply_put(sr, "received-msgs=%u", rconn_packets_received(rconn));
1109     status_reply_put(sr, "attempted-connections=%u",
1110                      rconn_get_attempted_connections(rconn));
1111     status_reply_put(sr, "successful-connections=%u",
1112                      rconn_get_successful_connections(rconn));
1113     status_reply_put(sr, "last-connection=%ld",
1114                      (long int) (now - rconn_get_last_connection(rconn)));
1115     status_reply_put(sr, "time-connected=%lu",
1116                      rconn_get_total_time_connected(rconn));
1117     status_reply_put(sr, "state-elapsed=%u", rconn_get_state_elapsed(rconn));
1118 }
1119
1120 static void
1121 config_status_cb(struct status_reply *sr, void *s_)
1122 {
1123     const struct settings *s = s_;
1124     size_t i;
1125
1126     for (i = 0; i < s->n_listeners; i++) {
1127         status_reply_put(sr, "management%zu=%s", i, s->listener_names[i]);
1128     }
1129     if (s->probe_interval) {
1130         status_reply_put(sr, "probe-interval=%d", s->probe_interval);
1131     }
1132     if (s->max_backoff) {
1133         status_reply_put(sr, "max-backoff=%d", s->max_backoff);
1134     }
1135 }
1136
1137 static void
1138 switch_status_cb(struct status_reply *sr, void *ss_)
1139 {
1140     struct switch_status *ss = ss_;
1141     time_t now = time_now();
1142
1143     status_reply_put(sr, "now=%ld", (long int) now);
1144     status_reply_put(sr, "uptime=%ld", (long int) (now - ss->booted));
1145     status_reply_put(sr, "pid=%ld", (long int) getpid());
1146 }
1147
1148 static struct hook
1149 switch_status_hook_create(const struct settings *s, struct switch_status **ssp)
1150 {
1151     struct switch_status *ss = xcalloc(1, sizeof *ss);
1152     ss->s = s;
1153     ss->booted = time_now();
1154     switch_status_register_category(ss, "config",
1155                                     config_status_cb, (void *) s);
1156     switch_status_register_category(ss, "switch", switch_status_cb, ss);
1157     *ssp = ss;
1158     return make_hook(switch_status_packet_cb, NULL, NULL, ss);
1159 }
1160
1161 static void
1162 switch_status_register_category(struct switch_status *ss,
1163                                 const char *category,
1164                                 void (*cb)(struct status_reply *,
1165                                            void *aux),
1166                                 void *aux)
1167 {
1168     struct switch_status_category *c;
1169     assert(ss->n_categories < ARRAY_SIZE(ss->categories));
1170     c = &ss->categories[ss->n_categories++];
1171     c->cb = cb;
1172     c->aux = aux;
1173     c->name = xstrdup(category);
1174 }
1175
1176 static void
1177 status_reply_put(struct status_reply *sr, const char *content, ...)
1178 {
1179     size_t old_length = sr->output.length;
1180     size_t added;
1181     va_list args;
1182
1183     /* Append the status reply to the output. */
1184     ds_put_format(&sr->output, "%s.", sr->category->name);
1185     va_start(args, content);
1186     ds_put_format_valist(&sr->output, content, args);
1187     va_end(args);
1188     if (ds_last(&sr->output) != '\n') {
1189         ds_put_char(&sr->output, '\n');
1190     }
1191
1192     /* Drop what we just added if it doesn't match the request. */
1193     added = sr->output.length - old_length;
1194     if (added < sr->request.length
1195         || memcmp(&sr->output.string[old_length],
1196                   sr->request.string, sr->request.length)) {
1197         ds_truncate(&sr->output, old_length);
1198     }
1199 }
1200
1201 \f
1202 /* Controller discovery. */
1203
1204 struct discovery
1205 {
1206     const struct settings *s;
1207     struct dhclient *dhcp;
1208     int n_changes;
1209 };
1210
1211 static void
1212 discovery_status_cb(struct status_reply *sr, void *d_)
1213 {
1214     struct discovery *d = d_;
1215
1216     status_reply_put(sr, "accept-remote=%s", d->s->accept_controller_re);
1217     status_reply_put(sr, "n-changes=%d", d->n_changes);
1218     status_reply_put(sr, "state=%s", dhclient_get_state(d->dhcp));
1219     status_reply_put(sr, "state-elapsed=%u",
1220                      dhclient_get_state_elapsed(d->dhcp));
1221     if (dhclient_is_bound(d->dhcp)) {
1222         uint32_t ip = dhclient_get_ip(d->dhcp);
1223         uint32_t netmask = dhclient_get_netmask(d->dhcp);
1224         uint32_t router = dhclient_get_router(d->dhcp);
1225
1226         const struct dhcp_msg *cfg = dhclient_get_config(d->dhcp);
1227         uint32_t dns_server;
1228         char *domain_name;
1229         int i;
1230
1231         status_reply_put(sr, "ip="IP_FMT, IP_ARGS(&ip));
1232         status_reply_put(sr, "netmask="IP_FMT, IP_ARGS(&netmask));
1233         if (router) {
1234             status_reply_put(sr, "router="IP_FMT, IP_ARGS(&router));
1235         }
1236
1237         for (i = 0; dhcp_msg_get_ip(cfg, DHCP_CODE_DNS_SERVER, i, &dns_server);
1238              i++) {
1239             status_reply_put(sr, "dns%d="IP_FMT, i, IP_ARGS(&dns_server));
1240         }
1241
1242         domain_name = dhcp_msg_get_string(cfg, DHCP_CODE_DOMAIN_NAME);
1243         if (domain_name) {
1244             status_reply_put(sr, "domain=%s", domain_name);
1245             free(domain_name);
1246         }
1247
1248         status_reply_put(sr, "lease-remaining=%u",
1249                          dhclient_get_lease_remaining(d->dhcp));
1250     }
1251 }
1252
1253 static struct discovery *
1254 discovery_init(const struct settings *s, struct switch_status *ss)
1255 {
1256     struct netdev *netdev;
1257     struct discovery *d;
1258     struct dhclient *dhcp;
1259     int retval;
1260
1261     /* Bring ofX network device up. */
1262     retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
1263     if (retval) {
1264         fatal(retval, "Could not open %s device", s->of_name);
1265     }
1266     retval = netdev_turn_flags_on(netdev, NETDEV_UP, true);
1267     if (retval) {
1268         fatal(retval, "Could not bring %s device up", s->of_name);
1269     }
1270     netdev_close(netdev);
1271
1272     /* Initialize DHCP client. */
1273     retval = dhclient_create(s->of_name, modify_dhcp_request,
1274                              validate_dhcp_offer, (void *) s, &dhcp);
1275     if (retval) {
1276         fatal(retval, "Failed to initialize DHCP client");
1277     }
1278     dhclient_init(dhcp, 0);
1279
1280     d = xmalloc(sizeof *d);
1281     d->s = s;
1282     d->dhcp = dhcp;
1283     d->n_changes = 0;
1284
1285     switch_status_register_category(ss, "discovery", discovery_status_cb, d);
1286
1287     return d;
1288 }
1289
1290 static void
1291 discovery_question_connectivity(struct discovery *d)
1292 {
1293     dhclient_force_renew(d->dhcp, 15);
1294 }
1295
1296 static bool
1297 discovery_run(struct discovery *d, char **controller_name)
1298 {
1299     dhclient_run(d->dhcp);
1300     if (!dhclient_changed(d->dhcp)) {
1301         return false;
1302     }
1303
1304     dhclient_configure_netdev(d->dhcp);
1305     if (d->s->update_resolv_conf) {
1306         dhclient_update_resolv_conf(d->dhcp);
1307     }
1308
1309     if (dhclient_is_bound(d->dhcp)) {
1310         *controller_name = dhcp_msg_get_string(dhclient_get_config(d->dhcp),
1311                                                DHCP_CODE_OFP_CONTROLLER_VCONN);
1312         VLOG_WARN("%s: discovered controller", *controller_name);
1313         d->n_changes++;
1314     } else {
1315         *controller_name = NULL;
1316         if (d->n_changes) {
1317             VLOG_WARN("discovered controller no longer available");
1318             d->n_changes++;
1319         }
1320     }
1321     return true;
1322 }
1323
1324 static void
1325 discovery_wait(struct discovery *d)
1326 {
1327     dhclient_wait(d->dhcp);
1328 }
1329
1330 static void
1331 modify_dhcp_request(struct dhcp_msg *msg, void *aux)
1332 {
1333     dhcp_msg_put_string(msg, DHCP_CODE_VENDOR_CLASS, "OpenFlow");
1334 }
1335
1336 static bool
1337 validate_dhcp_offer(const struct dhcp_msg *msg, void *s_)
1338 {
1339     const struct settings *s = s_;
1340     char *vconn_name;
1341     bool accept;
1342
1343     vconn_name = dhcp_msg_get_string(msg, DHCP_CODE_OFP_CONTROLLER_VCONN);
1344     if (!vconn_name) {
1345         VLOG_WARN_RL(&vrl, "rejecting DHCP offer missing controller vconn");
1346         return false;
1347     }
1348     accept = !regexec(&s->accept_controller_regex, vconn_name, 0, NULL, 0);
1349     if (!accept) {
1350         VLOG_WARN_RL(&vrl, "rejecting controller vconn that fails to match %s",
1351                      s->accept_controller_re);
1352     }
1353     free(vconn_name);
1354     return accept;
1355 }
1356 \f
1357 /* User interface. */
1358
1359 static void
1360 parse_options(int argc, char *argv[], struct settings *s)
1361 {
1362     enum {
1363         OPT_ACCEPT_VCONN = UCHAR_MAX + 1,
1364         OPT_NO_RESOLV_CONF,
1365         OPT_INACTIVITY_PROBE,
1366         OPT_MAX_IDLE,
1367         OPT_MAX_BACKOFF,
1368         OPT_RATE_LIMIT,
1369         OPT_BURST_LIMIT
1370     };
1371     static struct option long_options[] = {
1372         {"accept-vconn", required_argument, 0, OPT_ACCEPT_VCONN},
1373         {"no-resolv-conf", no_argument, 0, OPT_NO_RESOLV_CONF},
1374         {"fail",        required_argument, 0, 'F'},
1375         {"inactivity-probe", required_argument, 0, OPT_INACTIVITY_PROBE},
1376         {"max-idle",    required_argument, 0, OPT_MAX_IDLE},
1377         {"max-backoff", required_argument, 0, OPT_MAX_BACKOFF},
1378         {"listen",      required_argument, 0, 'l'},
1379         {"rate-limit",  optional_argument, 0, OPT_RATE_LIMIT},
1380         {"burst-limit", required_argument, 0, OPT_BURST_LIMIT},
1381         {"detach",      no_argument, 0, 'D'},
1382         {"force",       no_argument, 0, 'f'},
1383         {"pidfile",     optional_argument, 0, 'P'},
1384         {"verbose",     optional_argument, 0, 'v'},
1385         {"help",        no_argument, 0, 'h'},
1386         {"version",     no_argument, 0, 'V'},
1387         VCONN_SSL_LONG_OPTIONS
1388         {0, 0, 0, 0},
1389     };
1390     char *short_options = long_options_to_short_options(long_options);
1391     char *accept_re = NULL;
1392     int retval;
1393
1394     /* Set defaults that we can figure out before parsing options. */
1395     s->n_listeners = 0;
1396     s->fail_mode = FAIL_OPEN;
1397     s->max_idle = 15;
1398     s->probe_interval = 15;
1399     s->max_backoff = 15;
1400     s->update_resolv_conf = true;
1401     s->rate_limit = 0;
1402     s->burst_limit = 0;
1403     for (;;) {
1404         int c;
1405
1406         c = getopt_long(argc, argv, short_options, long_options, NULL);
1407         if (c == -1) {
1408             break;
1409         }
1410
1411         switch (c) {
1412         case OPT_ACCEPT_VCONN:
1413             accept_re = optarg[0] == '^' ? optarg : xasprintf("^%s", optarg);
1414             break;
1415
1416         case OPT_NO_RESOLV_CONF:
1417             s->update_resolv_conf = false;
1418             break;
1419
1420         case 'F':
1421             if (!strcmp(optarg, "open")) {
1422                 s->fail_mode = FAIL_OPEN;
1423             } else if (!strcmp(optarg, "closed")) {
1424                 s->fail_mode = FAIL_CLOSED;
1425             } else {
1426                 fatal(0,
1427                       "-f or --fail argument must be \"open\" or \"closed\"");
1428             }
1429             break;
1430
1431         case OPT_INACTIVITY_PROBE:
1432             s->probe_interval = atoi(optarg);
1433             if (s->probe_interval < 5) {
1434                 fatal(0, "--inactivity-probe argument must be at least 5");
1435             }
1436             break;
1437
1438         case OPT_MAX_IDLE:
1439             if (!strcmp(optarg, "permanent")) {
1440                 s->max_idle = OFP_FLOW_PERMANENT;
1441             } else {
1442                 s->max_idle = atoi(optarg);
1443                 if (s->max_idle < 1 || s->max_idle > 65535) {
1444                     fatal(0, "--max-idle argument must be between 1 and "
1445                           "65535 or the word 'permanent'");
1446                 }
1447             }
1448             break;
1449
1450         case OPT_MAX_BACKOFF:
1451             s->max_backoff = atoi(optarg);
1452             if (s->max_backoff < 1) {
1453                 fatal(0, "--max-backoff argument must be at least 1");
1454             } else if (s->max_backoff > 3600) {
1455                 s->max_backoff = 3600;
1456             }
1457             break;
1458
1459         case OPT_RATE_LIMIT:
1460             if (optarg) {
1461                 s->rate_limit = atoi(optarg);
1462                 if (s->rate_limit < 1) {
1463                     fatal(0, "--rate-limit argument must be at least 1");
1464                 }
1465             } else {
1466                 s->rate_limit = 1000;
1467             }
1468             break;
1469
1470         case OPT_BURST_LIMIT:
1471             s->burst_limit = atoi(optarg);
1472             if (s->burst_limit < 1) {
1473                 fatal(0, "--burst-limit argument must be at least 1");
1474             }
1475             break;
1476
1477         case 'D':
1478             set_detach();
1479             break;
1480
1481         case 'P':
1482             set_pidfile(optarg);
1483             break;
1484
1485         case 'f':
1486             ignore_existing_pidfile();
1487             break;
1488
1489         case 'l':
1490             if (s->n_listeners >= MAX_MGMT) {
1491                 fatal(0, "-l or --listen may be specified at most %d times",
1492                       MAX_MGMT);
1493             }
1494             s->listener_names[s->n_listeners++] = optarg;
1495             break;
1496
1497         case 'h':
1498             usage();
1499
1500         case 'V':
1501             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
1502             exit(EXIT_SUCCESS);
1503
1504         case 'v':
1505             vlog_set_verbosity(optarg);
1506             break;
1507
1508         VCONN_SSL_OPTION_HANDLERS
1509
1510         case '?':
1511             exit(EXIT_FAILURE);
1512
1513         default:
1514             abort();
1515         }
1516     }
1517     free(short_options);
1518
1519     argc -= optind;
1520     argv += optind;
1521     if (argc < 1 || argc > 2) {
1522         fatal(0, "need one or two non-option arguments; use --help for usage");
1523     }
1524
1525     /* Local and remote vconns. */
1526     s->nl_name = argv[0];
1527     if (strncmp(s->nl_name, "nl:", 3)
1528         || strlen(s->nl_name) < 4
1529         || s->nl_name[strspn(s->nl_name + 3, "0123456789") + 3]) {
1530         fatal(0, "%s: argument is not of the form \"nl:DP_IDX\"", s->nl_name);
1531     }
1532     s->of_name = xasprintf("of%s", s->nl_name + 3);
1533     s->controller_name = argc > 1 ? xstrdup(argv[1]) : NULL;
1534
1535     /* Set accept_controller_regex. */
1536     if (!accept_re) {
1537         accept_re = vconn_ssl_is_configured() ? "^ssl:.*" : ".*";
1538     }
1539     retval = regcomp(&s->accept_controller_regex, accept_re,
1540                      REG_NOSUB | REG_EXTENDED);
1541     if (retval) {
1542         size_t length = regerror(retval, &s->accept_controller_regex, NULL, 0);
1543         char *buffer = xmalloc(length);
1544         regerror(retval, &s->accept_controller_regex, buffer, length);
1545         fatal(0, "%s: %s", accept_re, buffer);
1546     }
1547     s->accept_controller_re = accept_re;
1548
1549     /* Mode of operation. */
1550     s->discovery = s->controller_name == NULL;
1551     if (s->discovery) {
1552         s->in_band = true;
1553     } else {
1554         enum netdev_flags flags;
1555         struct netdev *netdev;
1556
1557         retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
1558         if (retval) {
1559             fatal(retval, "Could not open %s device", s->of_name);
1560         }
1561
1562         retval = netdev_get_flags(netdev, &flags);
1563         if (retval) {
1564             fatal(retval, "Could not get flags for %s device", s->of_name);
1565         }
1566
1567         s->in_band = (flags & NETDEV_UP) != 0;
1568         if (s->in_band && netdev_get_in6(netdev, NULL)) {
1569             VLOG_WARN("Ignoring IPv6 address on %s device: IPv6 not supported",
1570                       s->of_name);
1571         }
1572
1573         netdev_close(netdev);
1574     }
1575
1576     /* Rate limiting. */
1577     if (s->rate_limit) {
1578         if (s->rate_limit < 100) {
1579             VLOG_WARN("Rate limit set to unusually low value %d",
1580                       s->rate_limit);
1581         }
1582         if (!s->burst_limit) {
1583             s->burst_limit = s->rate_limit / 4;
1584         }
1585         s->burst_limit = MAX(s->burst_limit, 1);
1586         s->burst_limit = MIN(s->burst_limit, INT_MAX / 1000);
1587     }
1588 }
1589
1590 static void
1591 usage(void)
1592 {
1593     printf("%s: secure channel, a relay for OpenFlow messages.\n"
1594            "usage: %s [OPTIONS] nl:DP_IDX [CONTROLLER]\n"
1595            "where nl:DP_IDX is a datapath that has been added with dpctl.\n"
1596            "CONTROLLER is an active OpenFlow connection method; if it is\n"
1597            "omitted, then secchan performs controller discovery.\n",
1598            program_name, program_name);
1599     vconn_usage(true, true);
1600     printf("\nController discovery options:\n"
1601            "  --accept-vconn=REGEX    accept matching discovered controllers\n"
1602            "  --no-resolv-conf        do not update /etc/resolv.conf\n"
1603            "\nNetworking options:\n"
1604            "  -F, --fail=open|closed  when controller connection fails:\n"
1605            "                            closed: drop all packets\n"
1606            "                            open (default): act as learning switch\n"
1607            "  --inactivity-probe=SECS time between inactivity probes\n"
1608            "  --max-idle=SECS         max idle for flows set up by secchan\n"
1609            "  --max-backoff=SECS      max time between controller connection\n"
1610            "                          attempts (default: 15 seconds)\n"
1611            "  -l, --listen=METHOD     allow management connections on METHOD\n"
1612            "                          (a passive OpenFlow connection method)\n"
1613            "\nRate-limiting of \"packet-in\" messages to the controller:\n"
1614            "  --rate-limit[=PACKETS]  max rate, in packets/s (default: 1000)\n"
1615            "  --burst-limit=BURST     limit on packet credit for idle time\n"
1616            "\nOther options:\n"
1617            "  -D, --detach            run in background as daemon\n"
1618            "  -P, --pidfile[=FILE]    create pidfile (default: %s/secchan.pid)\n"
1619            "  -f, --force             with -P, start even if already running\n"
1620            "  -v, --verbose=MODULE[:FACILITY[:LEVEL]]  set logging levels\n"
1621            "  -v, --verbose           set maximum verbosity level\n"
1622            "  -h, --help              display this help message\n"
1623            "  -V, --version           display version information\n",
1624            RUNDIR);
1625     exit(EXIT_SUCCESS);
1626 }