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