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