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