Enable secchan, ofp-discover to update /etc/resolv.conf.
[sliver-openvswitch.git] / secchan / secchan.c
1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  * 
4  * We are making the OpenFlow specification and associated documentation
5  * (Software) available for public use and benefit with the expectation
6  * that others will use, modify and enhance the Software and contribute
7  * those enhancements back to the community. However, since we would
8  * like to make the Software available for broadest use, with as few
9  * restrictions as possible permission is hereby granted, free of
10  * charge, to any person obtaining a copy of this Software to deal in
11  * the Software under the copyrights without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  * 
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  * 
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27  * SOFTWARE.
28  * 
29  * The name and trademarks of copyright holder(s) may NOT be used in
30  * advertising or publicity pertaining to the Software or any
31  * derivatives without specific, written prior permission.
32  */
33
34 #include <config.h>
35 #include <errno.h>
36 #include <getopt.h>
37 #include <inttypes.h>
38 #include <netinet/in.h>
39 #include <poll.h>
40 #include <regex.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <time.h>
44 #include <unistd.h>
45
46 #include "buffer.h"
47 #include "command-line.h"
48 #include "compiler.h"
49 #include "daemon.h"
50 #include "dhcp.h"
51 #include "dhcp-client.h"
52 #include "fault.h"
53 #include "flow.h"
54 #include "learning-switch.h"
55 #include "list.h"
56 #include "mac-learning.h"
57 #include "netdev.h"
58 #include "openflow.h"
59 #include "packets.h"
60 #include "poll-loop.h"
61 #include "rconn.h"
62 #include "util.h"
63 #include "vconn-ssl.h"
64 #include "vconn.h"
65 #include "vlog-socket.h"
66
67 #include "vlog.h"
68 #define THIS_MODULE VLM_secchan
69
70 static const char *listen_vconn_name;
71
72 struct half {
73     struct rconn *rconn;
74     struct buffer *rxbuf;
75 };
76
77 /* Behavior when the connection to the controller fails. */
78 enum fail_mode {
79     FAIL_OPEN,                  /* Act as learning switch. */
80     FAIL_CLOSED                 /* Drop all packets. */
81 };
82
83 struct relay {
84     struct list node;
85
86 #define HALF_LOCAL 0
87 #define HALF_REMOTE 1
88     struct half halves[2];
89
90     bool is_mgmt_conn;
91     struct lswitch *lswitch;
92 };
93
94 static struct list relays = LIST_INITIALIZER(&relays);
95
96 /* Mode of operation.  Note that autodiscovery implies in-band
97  * communication. */
98 static bool autodiscovery;      /* Discover the controller automatically? */
99 static bool in_band;            /* Connect to controller in-band? */
100
101 /* MAC address of local port. */
102 static uint8_t local_mac[ETH_ADDR_LEN];
103
104 /* MAC learning table for local port. */
105 static struct mac_learning *local_ml;
106
107 /* Controller vconn name, or null to perform controller autodiscovery. */
108 static char *controller_name = NULL;
109
110 /* -f, --fail: Behavior when the connection to the controller fails. */
111 static enum fail_mode fail_mode = FAIL_OPEN;
112
113 /* The OpenFlow virtual network device ofX. */
114 static struct netdev *of_device;
115
116 /* --inactivity-probe: Number of seconds without receiving a message from the
117    controller before sending an inactivity probe. */
118 static int probe_interval = 15;
119
120 /* --max-idle: Idle time to assign to flows created by learning switch when in
121  * fail-open mode. */
122 static int max_idle = 15;
123
124 /* --max-backoff: Maximum interval between controller connection attempts, in
125  * seconds. */
126 static int max_backoff = 15;
127
128 /* DHCP client, for controller autodiscovery. */
129 static struct dhclient *dhcp;
130
131 /* --accept-vconn: Regular expression specifying the class of controller vconns
132  * that we will accept during autodiscovery. */
133 static const char *accept_controller_re;
134 static regex_t accept_controller_regex;
135
136 /* --no-resolv-conf: Update resolv.conf upon successful controller
137  * discovery? */
138 static bool update_resolv_conf = true;
139
140 static void parse_options(int argc, char *argv[]);
141 static void usage(void) NO_RETURN;
142
143 static void new_management_connection(const char *nl_name, struct vconn *new_remote);
144 static struct relay *relay_create(struct rconn *local, struct rconn *remote,
145                                   bool is_mgmt_conn);
146 static void relay_run(struct relay *);
147 static void relay_wait(struct relay *);
148 static void relay_destroy(struct relay *);
149
150 static bool local_hook(struct relay *r);
151 static bool failing_open(struct relay *r);
152 static bool fail_open_hook(struct relay *r);
153
154 static void modify_dhcp_request(struct dhcp_msg *, void *aux);
155 static bool validate_dhcp_offer(const struct dhcp_msg *, void *aux);
156
157 int
158 main(int argc, char *argv[])
159 {
160     struct rconn *local_rconn, *remote_rconn;
161     struct vconn *listen_vconn;
162     struct relay *controller_relay;
163     const char *nl_name;
164     char of_name[16];
165     int retval;
166
167     set_program_name(argv[0]);
168     register_fault_handlers();
169     vlog_init();
170     parse_options(argc, argv);
171
172     argc -= optind;
173     argv += optind;
174     if (argc < 1 || argc > 2) {
175         fatal(0, "need one or two non-option arguments; use --help for usage");
176     }
177     nl_name = argv[0];
178     if (strncmp(nl_name, "nl:", 3)
179         || strlen(nl_name) < 4
180         || nl_name[strspn(nl_name + 3, "0123456789") + 3]) {
181         fatal(0, "%s: argument is not of the form \"nl:DP_IDX\"", nl_name);
182     }
183     controller_name = argc > 1 ? xstrdup(argv[1]) : NULL;
184     autodiscovery = controller_name == NULL;
185
186     if (!accept_controller_re) {
187         accept_controller_re = vconn_ssl_is_configured() ? "^ssl:.*" : ".*";
188     }
189     retval = regcomp(&accept_controller_regex, accept_controller_re,
190                      REG_NOSUB | REG_EXTENDED);
191     if (retval) {
192         size_t length = regerror(retval, &accept_controller_regex, NULL, 0);
193         char *buffer = xmalloc(length);
194         regerror(retval, &accept_controller_regex, buffer, length);
195         fatal(0, "%s: %s", accept_controller_re, buffer);
196     }
197
198     if (listen_vconn_name) {
199         retval = vconn_open(listen_vconn_name, &listen_vconn);
200         if (retval && retval != EAGAIN) {
201             fatal(retval, "opening %s", listen_vconn_name);
202         }
203         if (!vconn_is_passive(listen_vconn)) {
204             fatal(0, "%s is not a passive vconn", listen_vconn_name);
205         }
206     } else {
207         listen_vconn = NULL;
208     }
209
210     snprintf(of_name, sizeof of_name, "of%s", nl_name + 3);
211     retval = netdev_open(of_name, NETDEV_ETH_TYPE_NONE, &of_device);
212     if (!retval) {
213         enum netdev_flags flags;
214
215         if (autodiscovery) {
216             retval = netdev_turn_flags_on(of_device, NETDEV_UP, true);
217             if (retval) {
218                 fatal(retval, "Could not bring %s device up", of_name);
219             }
220         }
221
222         retval = netdev_get_flags(of_device, &flags);
223         if (!retval) {
224             if (flags & NETDEV_UP) {
225                 struct in6_addr in6;
226
227                 in_band = true;
228                 memcpy(local_mac, netdev_get_etheraddr(of_device),
229                        ETH_ADDR_LEN);
230                 if (netdev_get_in6(of_device, &in6)) {
231                     VLOG_WARN("Ignoring IPv6 address on %s device: "
232                               "IPv6 not supported", of_name);
233                 }
234                 local_ml = mac_learning_create();
235             } 
236         } else {
237             error(retval, "Could not get flags for %s device", of_name);
238         }
239     } else {
240         error(retval, "Could not open %s device", of_name);
241     }
242     if (autodiscovery && !in_band) {
243         fatal(retval, "In autodiscovery mode but failed to configure "
244               "in-band control");
245     }
246
247     if (autodiscovery) {
248         retval = dhclient_create(of_name, modify_dhcp_request,
249                                  validate_dhcp_offer, NULL, &dhcp);
250         if (retval) {
251             fatal(retval, "Failed to initialize DHCP client");
252         }
253         dhclient_init(dhcp, 0);
254     }
255
256     retval = vlog_server_listen(NULL, NULL);
257     if (retval) {
258         fatal(retval, "Could not listen for vlog connections");
259     }
260
261     daemonize();
262
263     local_rconn = rconn_create(1, 0, max_backoff);
264     rconn_connect(local_rconn, nl_name);
265
266     remote_rconn = rconn_create(1, probe_interval, max_backoff);
267     if (controller_name) {
268         retval = rconn_connect(remote_rconn, controller_name);
269         if (retval == EAFNOSUPPORT) {
270             fatal(0, "No support for %s vconn", controller_name);
271         }
272     }
273     controller_relay = relay_create(local_rconn, remote_rconn, false);
274     for (;;) {
275         struct relay *r, *n;
276
277         /* Do work. */
278         LIST_FOR_EACH_SAFE (r, n, struct relay, node, &relays) {
279             relay_run(r);
280         }
281         if (listen_vconn) {
282             for (;;) {
283                 struct vconn *new_remote;
284                 retval = vconn_accept(listen_vconn, &new_remote);
285                 if (retval) {
286                     if (retval != EAGAIN) {
287                         VLOG_WARN("accept failed (%s)", strerror(retval));
288                     }
289                     break;
290                 }
291                 new_management_connection(nl_name, new_remote);
292             }
293         }
294         if (controller_relay) {
295             /* FIXME: should also fail open when controller_relay is NULL. */
296             failing_open(controller_relay); 
297         }
298         if (dhcp) {
299             if (rconn_is_connectivity_questionable(remote_rconn)) {
300                 dhclient_force_renew(dhcp, 15);
301             }
302             dhclient_run(dhcp);
303             if (dhclient_changed(dhcp)) {
304                 dhclient_configure_netdev(dhcp);
305                 if (update_resolv_conf) {
306                     dhclient_update_resolv_conf(dhcp);
307                 }
308
309                 if (dhclient_is_bound(dhcp)) {
310                     free(controller_name);
311                     controller_name = dhcp_msg_get_string(
312                         dhclient_get_config(dhcp),
313                         DHCP_CODE_OFP_CONTROLLER_VCONN);
314                     VLOG_WARN("%s: discovered controller",
315                               controller_name);
316                     rconn_connect(remote_rconn, controller_name);
317                 } else if (controller_name) {
318                     VLOG_WARN("%s: discover controller no longer available",
319                               controller_name);
320                     free(controller_name);
321                     controller_name = NULL;
322                     rconn_disconnect(remote_rconn);
323                 }
324             }
325         }
326
327         /* Wait for something to happen. */
328         LIST_FOR_EACH (r, struct relay, node, &relays) {
329             relay_wait(r);
330         }
331         if (listen_vconn) {
332             vconn_accept_wait(listen_vconn);
333         }
334         if (dhcp) {
335             dhclient_wait(dhcp);
336         }
337         poll_block();
338     }
339
340     return 0;
341 }
342
343 static void
344 new_management_connection(const char *nl_name, struct vconn *new_remote)
345 {
346     char *nl_name_without_subscription;
347     struct vconn *new_local;
348     struct rconn *r1, *r2;
349     int retval;
350
351     /* nl:123 or nl:123:1 opens a netlink connection to local datapath 123.  We
352      * only accept the former syntax in main().
353      *
354      * nl:123:0 opens a netlink connection to local datapath 123 without
355      * obtaining a subscription for ofp_packet_in or ofp_flow_expired
356      * messages.*/
357     nl_name_without_subscription = xasprintf("%s:0", nl_name);
358     retval = vconn_open(nl_name_without_subscription, &new_local);
359     if (retval) {
360         VLOG_ERR("could not connect to %s (%s)",
361                  nl_name_without_subscription, strerror(retval));
362         vconn_close(new_remote);
363         free(nl_name_without_subscription);
364         return;
365     }
366
367     /* Add it to the relay list. */
368     r1 = rconn_create(1, 0, 0);
369     rconn_connect_unreliably(r1, nl_name_without_subscription, new_local);
370     r2 = rconn_create(1, 0, 0);
371     rconn_connect_unreliably(r2, "passive", new_remote);
372     relay_create(r1, r2, true);
373
374     free(nl_name_without_subscription);
375 }
376
377 static struct relay *
378 relay_create(struct rconn *local, struct rconn *remote, bool is_mgmt_conn)
379 {
380     struct relay *r;
381     int i;
382
383     r = xmalloc(sizeof *r);
384     r->halves[HALF_LOCAL].rconn = local;
385     r->halves[HALF_REMOTE].rconn = remote;
386     for (i = 0; i < 2; i++) {
387         r->halves[i].rxbuf = NULL;
388     }
389     r->is_mgmt_conn = is_mgmt_conn;
390     r->lswitch = NULL;
391     list_push_back(&relays, &r->node);
392     return r;
393 }
394
395 static void
396 relay_run(struct relay *r)
397 {
398     int iteration;
399     int i;
400
401     for (i = 0; i < 2; i++) {
402         rconn_run(r->halves[i].rconn);
403     }
404
405     /* Limit the number of iterations to prevent other tasks from starving. */
406     for (iteration = 0; iteration < 50; iteration++) {
407         bool progress = false;
408         for (i = 0; i < 2; i++) {
409             struct half *this = &r->halves[i];
410             struct half *peer = &r->halves[!i];
411
412             if (!this->rxbuf) {
413                 this->rxbuf = rconn_recv(this->rconn);
414                 if (this->rxbuf && !r->is_mgmt_conn && i == HALF_LOCAL
415                     && (local_hook(r) || fail_open_hook(r))) {
416                     buffer_delete(this->rxbuf);
417                     this->rxbuf = NULL;
418                 }
419             }
420
421             if (this->rxbuf) {
422                 int retval = rconn_send(peer->rconn, this->rxbuf);
423                 if (retval != EAGAIN) {
424                     if (!retval) {
425                         progress = true;
426                     } else {
427                         buffer_delete(this->rxbuf);
428                     }
429                     this->rxbuf = NULL;
430                 }
431             }
432         }
433         if (!progress) {
434             break;
435         }
436     }
437
438     if (r->is_mgmt_conn) {
439         for (i = 0; i < 2; i++) {
440             struct half *this = &r->halves[i];
441             if (!rconn_is_alive(this->rconn)) {
442                 relay_destroy(r);
443                 return;
444             }
445         }
446     }
447 }
448
449 static void
450 relay_wait(struct relay *r)
451 {
452     int i;
453
454     for (i = 0; i < 2; i++) {
455         struct half *this = &r->halves[i];
456
457         rconn_run_wait(this->rconn);
458         if (!this->rxbuf) {
459             rconn_recv_wait(this->rconn);
460         }
461     }
462 }
463
464 static void
465 relay_destroy(struct relay *r)
466 {
467     int i;
468
469     list_remove(&r->node);
470     for (i = 0; i < 2; i++) {
471         struct half *this = &r->halves[i];
472         rconn_destroy(this->rconn);
473         buffer_delete(this->rxbuf);
474     }
475     free(r);
476 }
477
478 static void
479 queue_tx(struct rconn *rc, struct buffer *b)
480 {
481     if (rconn_force_send(rc, b)) {
482         buffer_delete(b);
483     }
484 }
485
486 static bool
487 is_controller_mac(const uint8_t dl_addr[ETH_ADDR_LEN],
488                   struct rconn *controller) 
489 {
490     static uint32_t ip, last_nonzero_ip;
491     static uint8_t mac[ETH_ADDR_LEN], last_nonzero_mac[ETH_ADDR_LEN];
492     static time_t next_refresh = 0;
493
494     uint32_t last_ip = ip;
495
496     time_t now = time(0);
497
498     ip = rconn_get_ip(controller);
499     if (last_ip != ip || !next_refresh || now >= next_refresh) {
500         bool have_mac;
501
502         /* Look up MAC address. */
503         memset(mac, 0, sizeof mac);
504         if (ip) {
505             int retval = netdev_arp_lookup(of_device, ip, mac);
506             if (retval) {
507                 VLOG_DBG("cannot look up controller hw address ("IP_FMT"): %s",
508                          IP_ARGS(&ip), strerror(retval));
509             }
510         }
511         have_mac = !eth_addr_is_zero(mac);
512
513         /* Log changes in IP, MAC addresses. */
514         if (ip && ip != last_nonzero_ip) {
515             VLOG_DBG("controller IP address changed from "IP_FMT
516                      " to "IP_FMT, IP_ARGS(&last_nonzero_ip), IP_ARGS(&ip));
517             last_nonzero_ip = ip;
518         }
519         if (have_mac && memcmp(last_nonzero_mac, mac, ETH_ADDR_LEN)) {
520             VLOG_DBG("controller MAC address changed from "ETH_ADDR_FMT" to "
521                      ETH_ADDR_FMT,
522                      ETH_ADDR_ARGS(last_nonzero_mac), ETH_ADDR_ARGS(mac));
523             memcpy(last_nonzero_mac, mac, ETH_ADDR_LEN);
524         }
525
526         /* Schedule next refresh.
527          *
528          * If we have an IP address but not a MAC address, then refresh
529          * quickly, since we probably will get a MAC address soon (via ARP).
530          * Otherwise, we can afford to wait a little while. */
531         next_refresh = now + (!ip || have_mac ? 10 : 1);
532     }
533     return !eth_addr_is_zero(mac) && eth_addr_equals(mac, dl_addr);
534 }
535
536 static bool
537 local_hook(struct relay *r)
538 {
539     struct rconn *rc = r->halves[HALF_LOCAL].rconn;
540     struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
541     struct ofp_packet_in *opi;
542     struct ofp_header *oh;
543     size_t pkt_ofs, pkt_len;
544     struct buffer pkt;
545     struct flow flow;
546     uint16_t in_port, out_port;
547
548     if (!in_band) {
549         return false;
550     }
551
552     oh = msg->data;
553     if (oh->type != OFPT_PACKET_IN) {
554         return false;
555     }
556     if (msg->size < offsetof (struct ofp_packet_in, data)) {
557         VLOG_WARN("packet too short (%zu bytes) for packet_in", msg->size);
558         return false;
559     }
560
561     /* Extract flow data from 'opi' into 'flow'. */
562     opi = msg->data;
563     in_port = ntohs(opi->in_port);
564     pkt_ofs = offsetof(struct ofp_packet_in, data);
565     pkt_len = ntohs(opi->header.length) - pkt_ofs;
566     pkt.data = opi->data;
567     pkt.size = pkt_len;
568     flow_extract(&pkt, in_port, &flow);
569
570     /* Deal with local stuff. */
571     if (in_port == OFPP_LOCAL) {
572         out_port = mac_learning_lookup(local_ml, flow.dl_dst);
573     } else if (eth_addr_equals(flow.dl_dst, local_mac)) {
574         out_port = OFPP_LOCAL;
575         if (mac_learning_learn(local_ml, flow.dl_src, in_port)) {
576             VLOG_DBG("learned that "ETH_ADDR_FMT" is on port %"PRIu16,
577                      ETH_ADDR_ARGS(flow.dl_src), in_port);
578         }
579     } else if (flow.dl_type == htons(ETH_TYPE_ARP)
580                && eth_addr_is_broadcast(flow.dl_dst)
581                && is_controller_mac(flow.dl_src,
582                                     r->halves[HALF_REMOTE].rconn)) {
583         out_port = OFPP_FLOOD;
584     } else {
585         return false;
586     }
587
588     if (out_port != OFPP_FLOOD) {
589         /* The output port is known, so add a new flow. */
590         queue_tx(rc, make_add_simple_flow(&flow, ntohl(opi->buffer_id),
591                                           out_port, max_idle));
592
593         /* If the switch didn't buffer the packet, we need to send a copy. */
594         if (ntohl(opi->buffer_id) == UINT32_MAX) {
595             queue_tx(rc, make_unbuffered_packet_out(&pkt, in_port, out_port));
596         }
597     } else {
598         /* We don't know that MAC.  Send along the packet without setting up a
599          * flow. */
600         struct buffer *b;
601         if (ntohl(opi->buffer_id) == UINT32_MAX) {
602             b = make_unbuffered_packet_out(&pkt, in_port, out_port);
603         } else {
604             b = make_buffered_packet_out(ntohl(opi->buffer_id),
605                                          in_port, out_port);
606         }
607         queue_tx(rc, b);
608     }
609     return true;
610 }
611
612 /* Causess 'r' to enter or leave fail-open mode, if appropriate.  Returns true
613  * if 'r' is in fail-open fail, false otherwise. */
614 static bool
615 failing_open(struct relay *r)
616 {
617     struct rconn *local = r->halves[HALF_LOCAL].rconn;
618     struct rconn *remote = r->halves[HALF_REMOTE].rconn;
619     int disconnected_duration;
620
621     if (fail_mode == FAIL_CLOSED) {
622         /* We fail closed, so there's never anything to do. */
623         return false;
624     }
625
626     disconnected_duration = rconn_disconnected_duration(remote);
627     if (disconnected_duration < probe_interval * 3) {
628         /* It's not time to fail open yet. */
629         if (r->lswitch && rconn_is_connected(remote)) {
630             /* We're connected, so drop the learning switch. */
631             VLOG_WARN("No longer in fail-open mode");
632             lswitch_destroy(r->lswitch);
633             r->lswitch = NULL;
634         }
635         return false;
636     }
637
638     if (!r->lswitch) {
639         VLOG_WARN("Could not connect to controller for %d seconds, "
640                   "failing open", disconnected_duration);
641         r->lswitch = lswitch_create(local, true, max_idle);
642     }
643     return true;
644 }
645
646 static bool
647 fail_open_hook(struct relay *r)
648 {
649     if (!failing_open(r)) {
650         return false;
651     } else {
652         struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
653         struct rconn *local = r->halves[HALF_LOCAL].rconn;
654         lswitch_process_packet(r->lswitch, local, msg);
655         rconn_run(local);
656         return true;
657     }
658 }
659
660 static void
661 modify_dhcp_request(struct dhcp_msg *msg, void *aux)
662 {
663     dhcp_msg_put_string(msg, DHCP_CODE_VENDOR_CLASS, "OpenFlow");
664 }
665
666 static bool
667 validate_dhcp_offer(const struct dhcp_msg *msg, void *aux)
668 {
669     char *vconn_name;
670     bool accept;
671
672     vconn_name = dhcp_msg_get_string(msg, DHCP_CODE_OFP_CONTROLLER_VCONN);
673     if (!vconn_name) {
674         VLOG_WARN("rejecting DHCP offer missing controller vconn");
675         return false;
676     }
677     accept = !regexec(&accept_controller_regex, vconn_name, 0, NULL, 0);
678     if (!accept) {
679         VLOG_WARN("rejecting controller vconn that fails to match %s",
680                   accept_controller_re);
681     }
682     free(vconn_name);
683     return accept;
684 }
685
686 static void
687 parse_options(int argc, char *argv[]) 
688 {
689     enum {
690         OPT_ACCEPT_VCONN = UCHAR_MAX + 1,
691         OPT_NO_RESOLV_CONF,
692         OPT_INACTIVITY_PROBE,
693         OPT_MAX_IDLE,
694         OPT_MAX_BACKOFF
695     };
696     static struct option long_options[] = {
697         {"accept-vconn", required_argument, 0, OPT_ACCEPT_VCONN},
698         {"no-resolv-conf", no_argument, 0, OPT_NO_RESOLV_CONF},
699         {"fail",        required_argument, 0, 'f'},
700         {"inactivity-probe", required_argument, 0, OPT_INACTIVITY_PROBE},
701         {"max-idle",    required_argument, 0, OPT_MAX_IDLE},
702         {"max-backoff", required_argument, 0, OPT_MAX_BACKOFF},
703         {"listen",      required_argument, 0, 'l'},
704         {"detach",      no_argument, 0, 'D'},
705         {"pidfile",     optional_argument, 0, 'P'},
706         {"verbose",     optional_argument, 0, 'v'},
707         {"help",        no_argument, 0, 'h'},
708         {"version",     no_argument, 0, 'V'},
709         VCONN_SSL_LONG_OPTIONS
710         {0, 0, 0, 0},
711     };
712     char *short_options = long_options_to_short_options(long_options);
713     
714     for (;;) {
715         int c;
716
717         c = getopt_long(argc, argv, short_options, long_options, NULL);
718         if (c == -1) {
719             break;
720         }
721
722         switch (c) {
723         case OPT_ACCEPT_VCONN:
724             accept_controller_re = (optarg[0] == '^'
725                                     ? optarg
726                                     : xasprintf("^%s", optarg));
727             break;
728
729         case OPT_NO_RESOLV_CONF:
730             update_resolv_conf = false;
731             break;
732
733         case 'f':
734             if (!strcmp(optarg, "open")) {
735                 fail_mode = FAIL_OPEN;
736             } else if (!strcmp(optarg, "closed")) {
737                 fail_mode = FAIL_CLOSED;
738             } else {
739                 fatal(0,
740                       "-f or --fail argument must be \"open\" or \"closed\"");
741             }
742             break;
743
744         case OPT_INACTIVITY_PROBE:
745             probe_interval = atoi(optarg);
746             if (probe_interval < 5) {
747                 fatal(0, "--inactivity-probe argument must be at least 5");
748             }
749             break;
750
751         case OPT_MAX_IDLE:
752             if (!strcmp(optarg, "permanent")) {
753                 max_idle = OFP_FLOW_PERMANENT;
754             } else {
755                 max_idle = atoi(optarg);
756                 if (max_idle < 1 || max_idle > 65535) {
757                     fatal(0, "--max-idle argument must be between 1 and "
758                           "65535 or the word 'permanent'");
759                 }
760             }
761             break;
762
763         case OPT_MAX_BACKOFF:
764             max_backoff = atoi(optarg);
765             if (max_backoff < 1) {
766                 fatal(0, "--max-backoff argument must be at least 1");
767             } else if (max_backoff > 3600) {
768                 max_backoff = 3600;
769             }
770             break;
771
772         case 'D':
773             set_detach();
774             break;
775
776         case 'P':
777             set_pidfile(optarg);
778             break;
779
780         case 'l':
781             if (listen_vconn_name) {
782                 fatal(0, "-l or --listen may be only specified once");
783             }
784             listen_vconn_name = optarg;
785             break;
786
787         case 'h':
788             usage();
789
790         case 'V':
791             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
792             exit(EXIT_SUCCESS);
793
794         case 'v':
795             vlog_set_verbosity(optarg);
796             break;
797
798         VCONN_SSL_OPTION_HANDLERS
799
800         case '?':
801             exit(EXIT_FAILURE);
802
803         default:
804             abort();
805         }
806     }
807     free(short_options);
808 }
809
810 static void
811 usage(void)
812 {
813     printf("%s: secure channel, a relay for OpenFlow messages.\n"
814            "usage: %s [OPTIONS] nl:DP_IDX [CONTROLLER]\n"
815            "where nl:DP_IDX is a datapath that has been added with dpctl.\n"
816            "CONTROLLER is an active OpenFlow connection method; if it is\n"
817            "omitted, then secchan performs controller autodiscovery.\n",
818            program_name, program_name);
819     vconn_usage(true, true);
820     printf("\nController discovery options:\n"
821            "  --accept-vconn=REGEX    accept matching discovered controllers\n"
822            "  --no-resolv-conf        do not update /etc/resolv.conf\n"
823            "\nNetworking options:\n"
824            "  -f, --fail=open|closed  when controller connection fails:\n"
825            "                            closed: drop all packets\n"
826            "                            open (default): act as learning switch\n"
827            "  --inactivity-probe=SECS time between inactivity probes\n"
828            "  --max-idle=SECS         max idle for flows set up by secchan\n"
829            "  --max-backoff=SECS      max time between controller connection\n"
830            "                          attempts (default: 15 seconds)\n"
831            "  -l, --listen=METHOD     allow management connections on METHOD\n"
832            "                          (a passive OpenFlow connection method)\n"
833            "\nOther options:\n"
834            "  -D, --detach            run in background as daemon\n"
835            "  -P, --pidfile[=FILE]    create pidfile (default: %s/secchan.pid)\n"
836            "  -v, --verbose=MODULE[:FACILITY[:LEVEL]]  set logging levels\n"
837            "  -v, --verbose           set maximum verbosity level\n"
838            "  -h, --help              display this help message\n"
839            "  -V, --version           display version information\n",
840            RUNDIR);
841     exit(EXIT_SUCCESS);
842 }