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