dhcp: Break out netdev configuration from DHCP binding.
[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 static void parse_options(int argc, char *argv[]);
137 static void usage(void) NO_RETURN;
138
139 static void new_management_connection(const char *nl_name, struct vconn *new_remote);
140 static struct relay *relay_create(struct rconn *local, struct rconn *remote,
141                                   bool is_mgmt_conn);
142 static void relay_run(struct relay *);
143 static void relay_wait(struct relay *);
144 static void relay_destroy(struct relay *);
145
146 static bool local_hook(struct relay *r);
147 static bool failing_open(struct relay *r);
148 static bool fail_open_hook(struct relay *r);
149
150 static void modify_dhcp_request(struct dhcp_msg *, void *aux);
151 static bool validate_dhcp_offer(const struct dhcp_msg *, void *aux);
152
153 int
154 main(int argc, char *argv[])
155 {
156     struct rconn *local_rconn, *remote_rconn;
157     struct vconn *listen_vconn;
158     struct relay *controller_relay;
159     const char *nl_name;
160     char of_name[16];
161     int retval;
162
163     set_program_name(argv[0]);
164     register_fault_handlers();
165     vlog_init();
166     parse_options(argc, argv);
167
168     argc -= optind;
169     argv += optind;
170     if (argc < 1 || argc > 2) {
171         fatal(0, "need one or two non-option arguments; use --help for usage");
172     }
173     nl_name = argv[0];
174     if (strncmp(nl_name, "nl:", 3)
175         || strlen(nl_name) < 4
176         || nl_name[strspn(nl_name + 3, "0123456789") + 3]) {
177         fatal(0, "%s: argument is not of the form \"nl:DP_IDX\"", nl_name);
178     }
179     controller_name = argc > 1 ? xstrdup(argv[1]) : NULL;
180     autodiscovery = controller_name == NULL;
181
182     if (!accept_controller_re) {
183         accept_controller_re = vconn_ssl_is_configured() ? "^ssl:.*" : ".*";
184     }
185     retval = regcomp(&accept_controller_regex, accept_controller_re,
186                      REG_NOSUB | REG_EXTENDED);
187     if (retval) {
188         size_t length = regerror(retval, &accept_controller_regex, NULL, 0);
189         char *buffer = xmalloc(length);
190         regerror(retval, &accept_controller_regex, buffer, length);
191         fatal(0, "%s: %s", accept_controller_re, buffer);
192     }
193
194     if (listen_vconn_name) {
195         retval = vconn_open(listen_vconn_name, &listen_vconn);
196         if (retval && retval != EAGAIN) {
197             fatal(retval, "opening %s", listen_vconn_name);
198         }
199         if (!vconn_is_passive(listen_vconn)) {
200             fatal(0, "%s is not a passive vconn", listen_vconn_name);
201         }
202     } else {
203         listen_vconn = NULL;
204     }
205
206     snprintf(of_name, sizeof of_name, "of%s", nl_name + 3);
207     retval = netdev_open(of_name, NETDEV_ETH_TYPE_NONE, &of_device);
208     if (!retval) {
209         enum netdev_flags flags;
210
211         if (autodiscovery) {
212             retval = netdev_turn_flags_on(of_device, NETDEV_UP, true);
213             if (retval) {
214                 fatal(retval, "Could not bring %s device up", of_name);
215             }
216         }
217
218         retval = netdev_get_flags(of_device, &flags);
219         if (!retval) {
220             if (flags & NETDEV_UP) {
221                 struct in6_addr in6;
222
223                 in_band = true;
224                 memcpy(local_mac, netdev_get_etheraddr(of_device),
225                        ETH_ADDR_LEN);
226                 if (netdev_get_in6(of_device, &in6)) {
227                     VLOG_WARN("Ignoring IPv6 address on %s device: "
228                               "IPv6 not supported", of_name);
229                 }
230                 local_ml = mac_learning_create();
231             } 
232         } else {
233             error(retval, "Could not get flags for %s device", of_name);
234         }
235     } else {
236         error(retval, "Could not open %s device", of_name);
237     }
238     if (autodiscovery && !in_band) {
239         fatal(retval, "In autodiscovery mode but failed to configure "
240               "in-band control");
241     }
242
243     if (autodiscovery) {
244         retval = dhclient_create(of_name, modify_dhcp_request,
245                                  validate_dhcp_offer, NULL, &dhcp);
246         if (retval) {
247             fatal(retval, "Failed to initialize DHCP client");
248         }
249         dhclient_init(dhcp, 0);
250     }
251
252     retval = vlog_server_listen(NULL, NULL);
253     if (retval) {
254         fatal(retval, "Could not listen for vlog connections");
255     }
256
257     daemonize();
258
259     local_rconn = rconn_create(1, 0, max_backoff);
260     rconn_connect(local_rconn, nl_name);
261
262     remote_rconn = rconn_create(1, probe_interval, max_backoff);
263     if (controller_name) {
264         retval = rconn_connect(remote_rconn, controller_name);
265         if (retval == EAFNOSUPPORT) {
266             fatal(0, "No support for %s vconn", controller_name);
267         }
268     }
269     controller_relay = relay_create(local_rconn, remote_rconn, false);
270     for (;;) {
271         struct relay *r, *n;
272
273         /* Do work. */
274         LIST_FOR_EACH_SAFE (r, n, struct relay, node, &relays) {
275             relay_run(r);
276         }
277         if (listen_vconn) {
278             for (;;) {
279                 struct vconn *new_remote;
280                 retval = vconn_accept(listen_vconn, &new_remote);
281                 if (retval) {
282                     if (retval != EAGAIN) {
283                         VLOG_WARN("accept failed (%s)", strerror(retval));
284                     }
285                     break;
286                 }
287                 new_management_connection(nl_name, new_remote);
288             }
289         }
290         if (controller_relay) {
291             /* FIXME: should also fail open when controller_relay is NULL. */
292             failing_open(controller_relay); 
293         }
294         if (dhcp) {
295             if (rconn_is_connectivity_questionable(remote_rconn)) {
296                 dhclient_force_renew(dhcp, 15);
297             }
298             dhclient_run(dhcp);
299             if (dhclient_changed(dhcp)) {
300                 dhclient_configure_netdev(dhcp);
301                 free(controller_name);
302                 if (dhclient_is_bound(dhcp)) {
303                     controller_name = dhcp_msg_get_string(
304                         dhclient_get_config(dhcp),
305                         DHCP_CODE_OFP_CONTROLLER_VCONN);
306                     VLOG_WARN("%s: discovered controller",
307                               controller_name);
308                     rconn_connect(remote_rconn, controller_name);
309                 } else if (controller_name) {
310                     VLOG_WARN("%s: discover controller no longer available",
311                               controller_name);
312                     controller_name = NULL;
313                     rconn_disconnect(remote_rconn);
314                 }
315             }
316         }
317
318         /* Wait for something to happen. */
319         LIST_FOR_EACH (r, struct relay, node, &relays) {
320             relay_wait(r);
321         }
322         if (listen_vconn) {
323             vconn_accept_wait(listen_vconn);
324         }
325         if (dhcp) {
326             dhclient_wait(dhcp);
327         }
328         poll_block();
329     }
330
331     return 0;
332 }
333
334 static void
335 new_management_connection(const char *nl_name, struct vconn *new_remote)
336 {
337     char *nl_name_without_subscription;
338     struct vconn *new_local;
339     struct rconn *r1, *r2;
340     int retval;
341
342     /* nl:123 or nl:123:1 opens a netlink connection to local datapath 123.  We
343      * only accept the former syntax in main().
344      *
345      * nl:123:0 opens a netlink connection to local datapath 123 without
346      * obtaining a subscription for ofp_packet_in or ofp_flow_expired
347      * messages.*/
348     nl_name_without_subscription = xasprintf("%s:0", nl_name);
349     retval = vconn_open(nl_name_without_subscription, &new_local);
350     if (retval) {
351         VLOG_ERR("could not connect to %s (%s)",
352                  nl_name_without_subscription, strerror(retval));
353         vconn_close(new_remote);
354         free(nl_name_without_subscription);
355         return;
356     }
357
358     /* Add it to the relay list. */
359     r1 = rconn_create(1, 0, 0);
360     rconn_connect_unreliably(r1, nl_name_without_subscription, new_local);
361     r2 = rconn_create(1, 0, 0);
362     rconn_connect_unreliably(r2, "passive", new_remote);
363     relay_create(r1, r2, true);
364
365     free(nl_name_without_subscription);
366 }
367
368 static struct relay *
369 relay_create(struct rconn *local, struct rconn *remote, bool is_mgmt_conn)
370 {
371     struct relay *r;
372     int i;
373
374     r = xmalloc(sizeof *r);
375     r->halves[HALF_LOCAL].rconn = local;
376     r->halves[HALF_REMOTE].rconn = remote;
377     for (i = 0; i < 2; i++) {
378         r->halves[i].rxbuf = NULL;
379     }
380     r->is_mgmt_conn = is_mgmt_conn;
381     r->lswitch = NULL;
382     list_push_back(&relays, &r->node);
383     return r;
384 }
385
386 static void
387 relay_run(struct relay *r)
388 {
389     int iteration;
390     int i;
391
392     for (i = 0; i < 2; i++) {
393         rconn_run(r->halves[i].rconn);
394     }
395
396     /* Limit the number of iterations to prevent other tasks from starving. */
397     for (iteration = 0; iteration < 50; iteration++) {
398         bool progress = false;
399         for (i = 0; i < 2; i++) {
400             struct half *this = &r->halves[i];
401             struct half *peer = &r->halves[!i];
402
403             if (!this->rxbuf) {
404                 this->rxbuf = rconn_recv(this->rconn);
405                 if (this->rxbuf && !r->is_mgmt_conn && i == HALF_LOCAL
406                     && (local_hook(r) || fail_open_hook(r))) {
407                     buffer_delete(this->rxbuf);
408                     this->rxbuf = NULL;
409                 }
410             }
411
412             if (this->rxbuf) {
413                 int retval = rconn_send(peer->rconn, this->rxbuf);
414                 if (retval != EAGAIN) {
415                     if (!retval) {
416                         progress = true;
417                     } else {
418                         buffer_delete(this->rxbuf);
419                     }
420                     this->rxbuf = NULL;
421                 }
422             }
423         }
424         if (!progress) {
425             break;
426         }
427     }
428
429     if (r->is_mgmt_conn) {
430         for (i = 0; i < 2; i++) {
431             struct half *this = &r->halves[i];
432             if (!rconn_is_alive(this->rconn)) {
433                 relay_destroy(r);
434                 return;
435             }
436         }
437     }
438 }
439
440 static void
441 relay_wait(struct relay *r)
442 {
443     int i;
444
445     for (i = 0; i < 2; i++) {
446         struct half *this = &r->halves[i];
447
448         rconn_run_wait(this->rconn);
449         if (!this->rxbuf) {
450             rconn_recv_wait(this->rconn);
451         }
452     }
453 }
454
455 static void
456 relay_destroy(struct relay *r)
457 {
458     int i;
459
460     list_remove(&r->node);
461     for (i = 0; i < 2; i++) {
462         struct half *this = &r->halves[i];
463         rconn_destroy(this->rconn);
464         buffer_delete(this->rxbuf);
465     }
466     free(r);
467 }
468
469 static void
470 queue_tx(struct rconn *rc, struct buffer *b)
471 {
472     if (rconn_force_send(rc, b)) {
473         buffer_delete(b);
474     }
475 }
476
477 static bool
478 is_controller_mac(const uint8_t dl_addr[ETH_ADDR_LEN],
479                   struct rconn *controller) 
480 {
481     static uint32_t ip, last_nonzero_ip;
482     static uint8_t mac[ETH_ADDR_LEN], last_nonzero_mac[ETH_ADDR_LEN];
483     static time_t next_refresh = 0;
484
485     uint32_t last_ip = ip;
486
487     time_t now = time(0);
488
489     ip = rconn_get_ip(controller);
490     if (last_ip != ip || !next_refresh || now >= next_refresh) {
491         bool have_mac;
492
493         /* Look up MAC address. */
494         memset(mac, 0, sizeof mac);
495         if (ip) {
496             int retval = netdev_arp_lookup(of_device, ip, mac);
497             if (retval) {
498                 VLOG_DBG("cannot look up controller hw address ("IP_FMT"): %s",
499                          IP_ARGS(&ip), strerror(retval));
500             }
501         }
502         have_mac = !eth_addr_is_zero(mac);
503
504         /* Log changes in IP, MAC addresses. */
505         if (ip && ip != last_nonzero_ip) {
506             VLOG_DBG("controller IP address changed from "IP_FMT
507                      " to "IP_FMT, IP_ARGS(&last_nonzero_ip), IP_ARGS(&ip));
508             last_nonzero_ip = ip;
509         }
510         if (have_mac && memcmp(last_nonzero_mac, mac, ETH_ADDR_LEN)) {
511             VLOG_DBG("controller MAC address changed from "ETH_ADDR_FMT" to "
512                      ETH_ADDR_FMT,
513                      ETH_ADDR_ARGS(last_nonzero_mac), ETH_ADDR_ARGS(mac));
514             memcpy(last_nonzero_mac, mac, ETH_ADDR_LEN);
515         }
516
517         /* Schedule next refresh.
518          *
519          * If we have an IP address but not a MAC address, then refresh
520          * quickly, since we probably will get a MAC address soon (via ARP).
521          * Otherwise, we can afford to wait a little while. */
522         next_refresh = now + (!ip || have_mac ? 10 : 1);
523     }
524     return !eth_addr_is_zero(mac) && eth_addr_equals(mac, dl_addr);
525 }
526
527 static bool
528 local_hook(struct relay *r)
529 {
530     struct rconn *rc = r->halves[HALF_LOCAL].rconn;
531     struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
532     struct ofp_packet_in *opi;
533     struct ofp_header *oh;
534     size_t pkt_ofs, pkt_len;
535     struct buffer pkt;
536     struct flow flow;
537     uint16_t in_port, out_port;
538
539     if (!in_band) {
540         return false;
541     }
542
543     oh = msg->data;
544     if (oh->type != OFPT_PACKET_IN) {
545         return false;
546     }
547     if (msg->size < offsetof (struct ofp_packet_in, data)) {
548         VLOG_WARN("packet too short (%zu bytes) for packet_in", msg->size);
549         return false;
550     }
551
552     /* Extract flow data from 'opi' into 'flow'. */
553     opi = msg->data;
554     in_port = ntohs(opi->in_port);
555     pkt_ofs = offsetof(struct ofp_packet_in, data);
556     pkt_len = ntohs(opi->header.length) - pkt_ofs;
557     pkt.data = opi->data;
558     pkt.size = pkt_len;
559     flow_extract(&pkt, in_port, &flow);
560
561     /* Deal with local stuff. */
562     if (in_port == OFPP_LOCAL) {
563         out_port = mac_learning_lookup(local_ml, flow.dl_dst);
564     } else if (eth_addr_equals(flow.dl_dst, local_mac)) {
565         out_port = OFPP_LOCAL;
566         if (mac_learning_learn(local_ml, flow.dl_src, in_port)) {
567             VLOG_DBG("learned that "ETH_ADDR_FMT" is on port %"PRIu16,
568                      ETH_ADDR_ARGS(flow.dl_src), in_port);
569         }
570     } else if (flow.dl_type == htons(ETH_TYPE_ARP)
571                && eth_addr_is_broadcast(flow.dl_dst)
572                && is_controller_mac(flow.dl_src,
573                                     r->halves[HALF_REMOTE].rconn)) {
574         out_port = OFPP_FLOOD;
575     } else {
576         return false;
577     }
578
579     if (out_port != OFPP_FLOOD) {
580         /* The output port is known, so add a new flow. */
581         queue_tx(rc, make_add_simple_flow(&flow, ntohl(opi->buffer_id),
582                                           out_port, max_idle));
583
584         /* If the switch didn't buffer the packet, we need to send a copy. */
585         if (ntohl(opi->buffer_id) == UINT32_MAX) {
586             queue_tx(rc, make_unbuffered_packet_out(&pkt, in_port, out_port));
587         }
588     } else {
589         /* We don't know that MAC.  Send along the packet without setting up a
590          * flow. */
591         struct buffer *b;
592         if (ntohl(opi->buffer_id) == UINT32_MAX) {
593             b = make_unbuffered_packet_out(&pkt, in_port, out_port);
594         } else {
595             b = make_buffered_packet_out(ntohl(opi->buffer_id),
596                                          in_port, out_port);
597         }
598         queue_tx(rc, b);
599     }
600     return true;
601 }
602
603 /* Causess 'r' to enter or leave fail-open mode, if appropriate.  Returns true
604  * if 'r' is in fail-open fail, false otherwise. */
605 static bool
606 failing_open(struct relay *r)
607 {
608     struct rconn *local = r->halves[HALF_LOCAL].rconn;
609     struct rconn *remote = r->halves[HALF_REMOTE].rconn;
610     int disconnected_duration;
611
612     if (fail_mode == FAIL_CLOSED) {
613         /* We fail closed, so there's never anything to do. */
614         return false;
615     }
616
617     disconnected_duration = rconn_disconnected_duration(remote);
618     if (disconnected_duration < probe_interval * 3) {
619         /* It's not time to fail open yet. */
620         if (r->lswitch && rconn_is_connected(remote)) {
621             /* We're connected, so drop the learning switch. */
622             VLOG_WARN("No longer in fail-open mode");
623             lswitch_destroy(r->lswitch);
624             r->lswitch = NULL;
625         }
626         return false;
627     }
628
629     if (!r->lswitch) {
630         VLOG_WARN("Could not connect to controller for %d seconds, "
631                   "failing open", disconnected_duration);
632         r->lswitch = lswitch_create(local, true, max_idle);
633     }
634     return true;
635 }
636
637 static bool
638 fail_open_hook(struct relay *r)
639 {
640     if (!failing_open(r)) {
641         return false;
642     } else {
643         struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
644         struct rconn *local = r->halves[HALF_LOCAL].rconn;
645         lswitch_process_packet(r->lswitch, local, msg);
646         rconn_run(local);
647         return true;
648     }
649 }
650
651 static void
652 modify_dhcp_request(struct dhcp_msg *msg, void *aux)
653 {
654     dhcp_msg_put_string(msg, DHCP_CODE_VENDOR_CLASS, "OpenFlow");
655 }
656
657 static bool
658 validate_dhcp_offer(const struct dhcp_msg *msg, void *aux)
659 {
660     char *vconn_name;
661     bool accept;
662
663     vconn_name = dhcp_msg_get_string(msg, DHCP_CODE_OFP_CONTROLLER_VCONN);
664     if (!vconn_name) {
665         VLOG_WARN("rejecting DHCP offer missing controller vconn");
666         return false;
667     }
668     accept = !regexec(&accept_controller_regex, vconn_name, 0, NULL, 0);
669     free(vconn_name);
670     return accept;
671 }
672
673 static void
674 parse_options(int argc, char *argv[]) 
675 {
676     enum {
677         OPT_ACCEPT_VCONN = UCHAR_MAX + 1,
678         OPT_INACTIVITY_PROBE,
679         OPT_MAX_IDLE,
680         OPT_MAX_BACKOFF
681     };
682     static struct option long_options[] = {
683         {"accept-vconn", required_argument, 0, OPT_ACCEPT_VCONN},
684         {"fail",        required_argument, 0, 'f'},
685         {"inactivity-probe", required_argument, 0, OPT_INACTIVITY_PROBE},
686         {"max-idle",    required_argument, 0, OPT_MAX_IDLE},
687         {"max-backoff", required_argument, 0, OPT_MAX_BACKOFF},
688         {"listen",      required_argument, 0, 'l'},
689         {"detach",      no_argument, 0, 'D'},
690         {"pidfile",     optional_argument, 0, 'P'},
691         {"verbose",     optional_argument, 0, 'v'},
692         {"help",        no_argument, 0, 'h'},
693         {"version",     no_argument, 0, 'V'},
694         VCONN_SSL_LONG_OPTIONS
695         {0, 0, 0, 0},
696     };
697     char *short_options = long_options_to_short_options(long_options);
698     
699     for (;;) {
700         int c;
701
702         c = getopt_long(argc, argv, short_options, long_options, NULL);
703         if (c == -1) {
704             break;
705         }
706
707         switch (c) {
708         case OPT_ACCEPT_VCONN:
709             accept_controller_re = (optarg[0] == '^'
710                                     ? optarg
711                                     : xasprintf("^%s", optarg));
712             break;
713
714         case 'f':
715             if (!strcmp(optarg, "open")) {
716                 fail_mode = FAIL_OPEN;
717             } else if (!strcmp(optarg, "closed")) {
718                 fail_mode = FAIL_CLOSED;
719             } else {
720                 fatal(0,
721                       "-f or --fail argument must be \"open\" or \"closed\"");
722             }
723             break;
724
725         case OPT_INACTIVITY_PROBE:
726             probe_interval = atoi(optarg);
727             if (probe_interval < 5) {
728                 fatal(0, "--inactivity-probe argument must be at least 5");
729             }
730             break;
731
732         case OPT_MAX_IDLE:
733             if (!strcmp(optarg, "permanent")) {
734                 max_idle = OFP_FLOW_PERMANENT;
735             } else {
736                 max_idle = atoi(optarg);
737                 if (max_idle < 1 || max_idle > 65535) {
738                     fatal(0, "--max-idle argument must be between 1 and "
739                           "65535 or the word 'permanent'");
740                 }
741             }
742             break;
743
744         case OPT_MAX_BACKOFF:
745             max_backoff = atoi(optarg);
746             if (max_backoff < 1) {
747                 fatal(0, "--max-backoff argument must be at least 1");
748             } else if (max_backoff > 3600) {
749                 max_backoff = 3600;
750             }
751             break;
752
753         case 'D':
754             set_detach();
755             break;
756
757         case 'P':
758             set_pidfile(optarg);
759             break;
760
761         case 'l':
762             if (listen_vconn_name) {
763                 fatal(0, "-l or --listen may be only specified once");
764             }
765             listen_vconn_name = optarg;
766             break;
767
768         case 'h':
769             usage();
770
771         case 'V':
772             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
773             exit(EXIT_SUCCESS);
774
775         case 'v':
776             vlog_set_verbosity(optarg);
777             break;
778
779         VCONN_SSL_OPTION_HANDLERS
780
781         case '?':
782             exit(EXIT_FAILURE);
783
784         default:
785             abort();
786         }
787     }
788     free(short_options);
789 }
790
791 static void
792 usage(void)
793 {
794     printf("%s: secure channel, a relay for OpenFlow messages.\n"
795            "usage: %s [OPTIONS] nl:DP_IDX [CONTROLLER]\n"
796            "where nl:DP_IDX is a datapath that has been added with dpctl.\n"
797            "CONTROLLER is an active OpenFlow connection method; if it is\n"
798            "omitted, then secchan performs controller autodiscovery.\n",
799            program_name, program_name);
800     vconn_usage(true, true);
801     printf("\nNetworking options:\n"
802            "  --accept-vconn=REGEX    accept matching discovered controllers\n"
803            "  -f, --fail=open|closed  when controller connection fails:\n"
804            "                            closed: drop all packets\n"
805            "                            open (default): act as learning switch\n"
806            "  --inactivity-probe=SECS time between inactivity probes\n"
807            "  --max-idle=SECS         max idle for flows set up by secchan\n"
808            "  --max-backoff=SECS      max time between controller connection\n"
809            "                          attempts (default: 15 seconds)\n"
810            "  -l, --listen=METHOD     allow management connections on METHOD\n"
811            "                          (a passive OpenFlow connection method)\n"
812            "\nOther options:\n"
813            "  -D, --detach            run in background as daemon\n"
814            "  -P, --pidfile[=FILE]    create pidfile (default: %s/secchan.pid)\n"
815            "  -v, --verbose=MODULE[:FACILITY[:LEVEL]]  set logging levels\n"
816            "  -v, --verbose           set maximum verbosity level\n"
817            "  -h, --help              display this help message\n"
818            "  -V, --version           display version information\n",
819            RUNDIR);
820     exit(EXIT_SUCCESS);
821 }