Fix uninitialized data read in secchan.
[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 "stp.h"
66 #include "timeval.h"
67 #include "util.h"
68 #include "vconn-ssl.h"
69 #include "vconn.h"
70 #include "vlog-socket.h"
71
72 #include "vlog.h"
73 #define THIS_MODULE VLM_secchan
74
75 /* Behavior when the connection to the controller fails. */
76 enum fail_mode {
77     FAIL_OPEN,                  /* Act as learning switch. */
78     FAIL_CLOSED                 /* Drop all packets. */
79 };
80
81 /* Maximum number of management connection listeners. */
82 #define MAX_MGMT 8
83
84 /* Settings that may be configured by the user. */
85 struct settings {
86     /* Overall mode of operation. */
87     bool discovery;           /* Discover the controller automatically? */
88     bool in_band;             /* Connect to controller in-band? */
89
90     /* Related vconns and network devices. */
91     const char *nl_name;        /* Local datapath (must be "nl:" vconn). */
92     char *of_name;              /* ofX network device name. */
93     const char *controller_name; /* Controller (if not discovery mode). */
94     const char *listener_names[MAX_MGMT]; /* Listen for mgmt connections. */
95     size_t n_listeners;          /* Number of mgmt connection listeners. */
96     const char *monitor_name;   /* Listen for traffic monitor connections. */
97
98     /* Failure behavior. */
99     enum fail_mode fail_mode; /* Act as learning switch if no controller? */
100     int max_idle;             /* Idle time for flows in fail-open mode. */
101     int probe_interval;       /* # seconds idle before sending echo request. */
102     int max_backoff;          /* Max # seconds between connection attempts. */
103
104     /* Packet-in rate-limiting. */
105     int rate_limit;           /* Tokens added to bucket per second. */
106     int burst_limit;          /* Maximum number token bucket size. */
107
108     /* Discovery behavior. */
109     regex_t accept_controller_regex;  /* Controller vconns to accept. */
110     const char *accept_controller_re; /* String version of regex. */
111     bool update_resolv_conf;          /* Update /etc/resolv.conf? */
112 };
113
114 struct half {
115     struct rconn *rconn;
116     struct buffer *rxbuf;
117     int n_txq;                  /* No. of packets queued for tx on 'rconn'. */
118 };
119
120 struct relay {
121     struct list node;
122
123 #define HALF_LOCAL 0
124 #define HALF_REMOTE 1
125     struct half halves[2];
126
127     bool is_mgmt_conn;
128 };
129
130 struct hook {
131     bool (*packet_cb[2])(struct relay *, void *aux);
132     void (*periodic_cb)(void *aux);
133     void (*wait_cb)(void *aux);
134     void *aux;
135 };
136
137 static struct vlog_rate_limit vrl = VLOG_RATE_LIMIT_INIT(60, 60);
138
139 static void parse_options(int argc, char *argv[], struct settings *);
140 static void usage(void) NO_RETURN;
141
142 static struct vconn *open_passive_vconn(const char *name);
143 static struct vconn *accept_vconn(struct vconn *vconn);
144
145 static struct relay *relay_create(struct rconn *local, struct rconn *remote,
146                                   bool is_mgmt_conn);
147 static struct relay *relay_accept(const struct settings *, struct vconn *);
148 static void relay_run(struct relay *, const struct hook[], size_t n_hooks);
149 static void relay_wait(struct relay *);
150 static void relay_destroy(struct relay *);
151
152 static struct hook make_hook(bool (*local_packet_cb)(struct relay *, void *),
153                              bool (*remote_packet_cb)(struct relay *, void *),
154                              void (*periodic_cb)(void *),
155                              void (*wait_cb)(void *),
156                              void *aux);
157 static struct ofp_packet_in *get_ofp_packet_in(struct relay *);
158 static bool get_ofp_packet_eth_header(struct relay *, struct ofp_packet_in **,
159                                       struct eth_header **);
160 static void get_ofp_packet_payload(struct ofp_packet_in *, struct buffer *);
161
162 struct switch_status;
163 struct status_reply;
164 static struct hook switch_status_hook_create(const struct settings *,
165                                              struct switch_status **);
166 static void switch_status_register_category(struct switch_status *,
167                                             const char *category,
168                                             void (*cb)(struct status_reply *,
169                                                        void *aux),
170                                             void *aux);
171 static void status_reply_put(struct status_reply *, const char *, ...)
172     PRINTF_FORMAT(2, 3);
173
174 static void rconn_status_cb(struct status_reply *, void *rconn_);
175
176 static struct discovery *discovery_init(const struct settings *,
177                                         struct switch_status *);
178 static void discovery_question_connectivity(struct discovery *);
179 static bool discovery_run(struct discovery *, char **controller_name);
180 static void discovery_wait(struct discovery *);
181
182 static struct hook in_band_hook_create(const struct settings *,
183                                        struct switch_status *,
184                                        struct rconn *remote);
185
186 struct port_watcher;
187 static struct hook port_watcher_create(struct rconn *local,
188                                        struct rconn *remote,
189                                        struct port_watcher **);
190 static uint32_t port_watcher_get_flags(const struct port_watcher *,
191                                        int port_no);
192 static void port_watcher_set_flags(struct port_watcher *,
193                                    int port_no, uint32_t flags, uint32_t mask);
194
195 static struct hook stp_hook_create(const struct settings *,
196                                    struct port_watcher *,
197                                    struct rconn *local, struct rconn *remote);
198
199 static struct hook fail_open_hook_create(const struct settings *,
200                                          struct switch_status *,
201                                          struct rconn *local,
202                                          struct rconn *remote);
203 static struct hook rate_limit_hook_create(const struct settings *,
204                                           struct switch_status *,
205                                           struct rconn *local,
206                                           struct rconn *remote);
207
208
209 static void modify_dhcp_request(struct dhcp_msg *, void *aux);
210 static bool validate_dhcp_offer(const struct dhcp_msg *, void *aux);
211
212 int
213 main(int argc, char *argv[])
214 {
215     struct settings s;
216
217     struct list relays = LIST_INITIALIZER(&relays);
218
219     struct hook hooks[8];
220     size_t n_hooks = 0;
221
222     struct vconn *monitor;
223
224     struct vconn *listeners[MAX_MGMT];
225     size_t n_listeners;
226
227     struct rconn *local_rconn, *remote_rconn;
228     struct relay *controller_relay;
229     struct discovery *discovery;
230     struct switch_status *switch_status;
231     struct port_watcher *pw;
232     int i;
233     int retval;
234
235     set_program_name(argv[0]);
236     register_fault_handlers();
237     time_init();
238     vlog_init();
239     parse_options(argc, argv, &s);
240     signal(SIGPIPE, SIG_IGN);
241
242     /* Start listening for management and monitoring connections. */
243     n_listeners = 0;
244     for (i = 0; i < s.n_listeners; i++) {
245         listeners[n_listeners++] = open_passive_vconn(s.listener_names[i]);
246     }
247     monitor = s.monitor_name ? open_passive_vconn(s.monitor_name) : NULL;
248
249     /* Initialize switch status hook. */
250     hooks[n_hooks++] = switch_status_hook_create(&s, &switch_status);
251
252     /* Start controller discovery. */
253     discovery = s.discovery ? discovery_init(&s, switch_status) : NULL;
254
255     /* Start listening for vlogconf requests. */
256     retval = vlog_server_listen(NULL, NULL);
257     if (retval) {
258         fatal(retval, "Could not listen for vlog connections");
259     }
260
261     die_if_already_running();
262     daemonize();
263
264     VLOG_WARN("OpenFlow reference implementation version %s", VERSION);
265     VLOG_WARN("OpenFlow protocol version 0x%02x", OFP_VERSION);
266
267     /* Connect to datapath. */
268     local_rconn = rconn_create(0, s.max_backoff);
269     rconn_connect(local_rconn, s.nl_name);
270     switch_status_register_category(switch_status, "local",
271                                     rconn_status_cb, local_rconn);
272
273     /* Connect to controller. */
274     remote_rconn = rconn_create(s.probe_interval, s.max_backoff);
275     if (s.controller_name) {
276         retval = rconn_connect(remote_rconn, s.controller_name);
277         if (retval == EAFNOSUPPORT) {
278             fatal(0, "No support for %s vconn", s.controller_name);
279         }
280     }
281     switch_status_register_category(switch_status, "remote",
282                                     rconn_status_cb, remote_rconn);
283
284     /* Start relaying. */
285     controller_relay = relay_create(local_rconn, remote_rconn, false);
286     list_push_back(&relays, &controller_relay->node);
287
288     /* Set up hooks. */
289     hooks[n_hooks++] = port_watcher_create(local_rconn, remote_rconn, &pw);
290     hooks[n_hooks++] = stp_hook_create(&s, pw, local_rconn, remote_rconn);
291     if (s.in_band) {
292         hooks[n_hooks++] = in_band_hook_create(&s, switch_status,
293                                                remote_rconn);
294     }
295     if (s.fail_mode == FAIL_OPEN) {
296         hooks[n_hooks++] = fail_open_hook_create(&s, switch_status,
297                                                  local_rconn, remote_rconn);
298     }
299     if (s.rate_limit) {
300         hooks[n_hooks++] = rate_limit_hook_create(&s, switch_status,
301                                                   local_rconn, remote_rconn);
302     }
303     assert(n_hooks <= ARRAY_SIZE(hooks));
304
305     for (;;) {
306         struct relay *r, *n;
307         size_t i;
308
309         /* Do work. */
310         LIST_FOR_EACH_SAFE (r, n, struct relay, node, &relays) {
311             relay_run(r, hooks, n_hooks);
312         }
313         for (i = 0; i < n_listeners; i++) {
314             for (;;) {
315                 struct relay *r = relay_accept(&s, listeners[i]);
316                 if (!r) {
317                     break;
318                 }
319                 list_push_back(&relays, &r->node);
320             }
321         }
322         if (monitor) {
323             struct vconn *new = accept_vconn(monitor);
324             if (new) {
325                 rconn_add_monitor(local_rconn, new);
326             }
327         }
328         for (i = 0; i < n_hooks; i++) {
329             if (hooks[i].periodic_cb) {
330                 hooks[i].periodic_cb(hooks[i].aux);
331             }
332         }
333         if (s.discovery) {
334             char *controller_name;
335             if (rconn_is_connectivity_questionable(remote_rconn)) {
336                 discovery_question_connectivity(discovery);
337             }
338             if (discovery_run(discovery, &controller_name)) {
339                 if (controller_name) {
340                     rconn_connect(remote_rconn, controller_name);
341                 } else {
342                     rconn_disconnect(remote_rconn);
343                 }
344             }
345         }
346
347         /* Wait for something to happen. */
348         LIST_FOR_EACH (r, struct relay, node, &relays) {
349             relay_wait(r);
350         }
351         for (i = 0; i < n_listeners; i++) {
352             vconn_accept_wait(listeners[i]);
353         }
354         if (monitor) {
355             vconn_accept_wait(monitor);
356         }
357         for (i = 0; i < n_hooks; i++) {
358             if (hooks[i].wait_cb) {
359                 hooks[i].wait_cb(hooks[i].aux);
360             }
361         }
362         if (discovery) {
363             discovery_wait(discovery);
364         }
365         poll_block();
366     }
367
368     return 0;
369 }
370
371 static struct vconn *
372 open_passive_vconn(const char *name) 
373 {
374     struct vconn *vconn;
375     int retval;
376
377     retval = vconn_open(name, &vconn);
378     if (retval && retval != EAGAIN) {
379         fatal(retval, "opening %s", name);
380     }
381     if (!vconn_is_passive(vconn)) {
382         fatal(0, "%s is not a passive vconn", name);
383     }
384     return vconn;
385 }
386
387 static struct vconn *
388 accept_vconn(struct vconn *vconn) 
389 {
390     struct vconn *new;
391     int retval;
392
393     retval = vconn_accept(vconn, &new);
394     if (retval && retval != EAGAIN) {
395         VLOG_WARN_RL(&vrl, "accept failed (%s)", strerror(retval));
396     }
397     return new;
398 }
399
400 static struct hook
401 make_hook(bool (*local_packet_cb)(struct relay *, void *aux),
402           bool (*remote_packet_cb)(struct relay *, void *aux),
403           void (*periodic_cb)(void *aux),
404           void (*wait_cb)(void *aux),
405           void *aux)
406 {
407     struct hook h;
408     h.packet_cb[HALF_LOCAL] = local_packet_cb;
409     h.packet_cb[HALF_REMOTE] = remote_packet_cb;
410     h.periodic_cb = periodic_cb;
411     h.wait_cb = wait_cb;
412     h.aux = aux;
413     return h;
414 }
415
416 static struct ofp_packet_in *
417 get_ofp_packet_in(struct relay *r)
418 {
419     struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
420     struct ofp_header *oh = msg->data;
421     if (oh->type == OFPT_PACKET_IN) {
422         if (msg->size >= offsetof (struct ofp_packet_in, data)) {
423             return msg->data;
424         } else {
425             VLOG_WARN("packet too short (%zu bytes) for packet_in",
426                       msg->size);
427         }
428     }
429     return NULL;
430 }
431
432 static bool
433 get_ofp_packet_eth_header(struct relay *r, struct ofp_packet_in **opip,
434                           struct eth_header **ethp)
435 {
436     const int min_len = offsetof(struct ofp_packet_in, data) + ETH_HEADER_LEN;
437     struct ofp_packet_in *opi = get_ofp_packet_in(r);
438     if (opi && ntohs(opi->header.length) >= min_len) {
439         *opip = opi;
440         *ethp = (void *) opi->data;
441         return true;
442     }
443     return false;
444 }
445
446 \f
447 /* OpenFlow message relaying. */
448
449 static struct relay *
450 relay_accept(const struct settings *s, struct vconn *listen_vconn)
451 {
452     struct vconn *new_remote, *new_local;
453     char *nl_name_without_subscription;
454     struct rconn *r1, *r2;
455     int retval;
456
457     new_remote = accept_vconn(listen_vconn);
458     if (!new_remote) {
459         return NULL;
460     }
461
462     /* nl:123 or nl:123:1 opens a netlink connection to local datapath 123.  We
463      * only accept the former syntax in main().
464      *
465      * nl:123:0 opens a netlink connection to local datapath 123 without
466      * obtaining a subscription for ofp_packet_in or ofp_flow_expired
467      * messages.*/
468     nl_name_without_subscription = xasprintf("%s:0", s->nl_name);
469     retval = vconn_open(nl_name_without_subscription, &new_local);
470     if (retval) {
471         VLOG_ERR_RL(&vrl, "could not connect to %s (%s)",
472                     nl_name_without_subscription, strerror(retval));
473         vconn_close(new_remote);
474         free(nl_name_without_subscription);
475         return NULL;
476     }
477
478     /* Create and return relay. */
479     r1 = rconn_create(0, 0);
480     rconn_connect_unreliably(r1, nl_name_without_subscription, new_local);
481     free(nl_name_without_subscription);
482
483     r2 = rconn_create(0, 0);
484     rconn_connect_unreliably(r2, "passive", new_remote);
485
486     return relay_create(r1, r2, true);
487 }
488
489 static struct relay *
490 relay_create(struct rconn *local, struct rconn *remote, bool is_mgmt_conn)
491 {
492     struct relay *r = xcalloc(1, sizeof *r);
493     r->halves[HALF_LOCAL].rconn = local;
494     r->halves[HALF_REMOTE].rconn = remote;
495     r->is_mgmt_conn = is_mgmt_conn;
496     return r;
497 }
498
499 static void
500 relay_run(struct relay *r, const struct hook hooks[], size_t n_hooks)
501 {
502     int iteration;
503     int i;
504
505     for (i = 0; i < 2; i++) {
506         rconn_run(r->halves[i].rconn);
507     }
508
509     /* Limit the number of iterations to prevent other tasks from starving. */
510     for (iteration = 0; iteration < 50; iteration++) {
511         bool progress = false;
512         for (i = 0; i < 2; i++) {
513             struct half *this = &r->halves[i];
514             struct half *peer = &r->halves[!i];
515
516             if (!this->rxbuf) {
517                 this->rxbuf = rconn_recv(this->rconn);
518                 if (this->rxbuf && (i == HALF_REMOTE || !r->is_mgmt_conn)) {
519                     const struct hook *h;
520                     for (h = hooks; h < &hooks[n_hooks]; h++) {
521                         if (h->packet_cb[i] && h->packet_cb[i](r, h->aux)) {
522                             buffer_delete(this->rxbuf);
523                             this->rxbuf = NULL;
524                             progress = true;
525                             break;
526                         }
527                     }
528                 }
529             }
530
531             if (this->rxbuf && !this->n_txq) {
532                 int retval = rconn_send(peer->rconn, this->rxbuf,
533                                         &this->n_txq);
534                 if (retval != EAGAIN) {
535                     if (!retval) {
536                         progress = true;
537                     } else {
538                         buffer_delete(this->rxbuf);
539                     }
540                     this->rxbuf = NULL;
541                 }
542             }
543         }
544         if (!progress) {
545             break;
546         }
547     }
548
549     if (r->is_mgmt_conn) {
550         for (i = 0; i < 2; i++) {
551             struct half *this = &r->halves[i];
552             if (!rconn_is_alive(this->rconn)) {
553                 relay_destroy(r);
554                 return;
555             }
556         }
557     }
558 }
559
560 static void
561 relay_wait(struct relay *r)
562 {
563     int i;
564
565     for (i = 0; i < 2; i++) {
566         struct half *this = &r->halves[i];
567
568         rconn_run_wait(this->rconn);
569         if (!this->rxbuf) {
570             rconn_recv_wait(this->rconn);
571         }
572     }
573 }
574
575 static void
576 relay_destroy(struct relay *r)
577 {
578     int i;
579
580     list_remove(&r->node);
581     for (i = 0; i < 2; i++) {
582         struct half *this = &r->halves[i];
583         rconn_destroy(this->rconn);
584         buffer_delete(this->rxbuf);
585     }
586     free(r);
587 }
588 \f
589 /* Port status watcher. */
590
591 typedef void port_watcher_cb_func(uint16_t port_no,
592                                   const struct ofp_phy_port *old,
593                                   const struct ofp_phy_port *new,
594                                   void *aux);
595
596 struct port_watcher_cb {
597     port_watcher_cb_func *function;
598     void *aux;
599 };
600
601 struct port_watcher {
602     struct rconn *local_rconn;
603     struct rconn *remote_rconn;
604     struct ofp_phy_port ports[OFPP_MAX + 1];
605     time_t last_feature_request;
606     bool got_feature_reply;
607     int n_txq;
608     struct port_watcher_cb cbs[2];
609     int n_cbs;
610 };
611
612 /* Returns the number of fields that differ from 'a' to 'b'. */
613 static int
614 opp_differs(const struct ofp_phy_port *a, const struct ofp_phy_port *b)
615 {
616     BUILD_ASSERT_DECL(sizeof *a == 36); /* Trips when we add or remove fields. */
617     return ((a->port_no != b->port_no)
618             + (memcmp(a->hw_addr, b->hw_addr, sizeof a->hw_addr) != 0)
619             + (memcmp(a->name, b->name, sizeof a->name) != 0)
620             + (a->flags != b->flags)
621             + (a->speed != b->speed)
622             + (a->features != b->features));
623 }
624
625 static void
626 sanitize_opp(struct ofp_phy_port *opp)
627 {
628     size_t i;
629
630     for (i = 0; i < sizeof opp->name; i++) {
631         char c = opp->name[i];
632         if (c && (c < 0x20 || c > 0x7e)) {
633             opp->name[i] = '.';
634         }
635     }
636     opp->name[sizeof opp->name - 1] = '\0';
637 }
638
639 static int
640 port_no_to_pw_idx(int port_no)
641 {
642     return (port_no < OFPP_MAX ? port_no
643             : port_no == OFPP_LOCAL ? OFPP_MAX
644             : -1);
645 }
646
647 static void
648 call_pw_callbacks(struct port_watcher *pw, int port_no,
649                   const struct ofp_phy_port *old,
650                   const struct ofp_phy_port *new)
651 {
652     if (opp_differs(old, new)) {
653         int i;
654         for (i = 0; i < pw->n_cbs; i++) {
655             pw->cbs[i].function(port_no, old, new, pw->cbs[i].aux);
656         }
657     }
658 }
659
660 static void
661 update_phy_port(struct port_watcher *pw, struct ofp_phy_port *opp,
662                 uint8_t reason, bool seen[OFPP_MAX + 1])
663 {
664     struct ofp_phy_port *pw_opp;
665     struct ofp_phy_port old;
666     uint16_t port_no;
667     int idx;
668
669     port_no = ntohs(opp->port_no);
670     idx = port_no_to_pw_idx(port_no);
671     if (idx < 0) {
672         return;
673     }
674
675     if (seen) {
676         seen[idx] = true;
677     }
678
679     pw_opp = &pw->ports[idx];
680     old = *pw_opp;
681     if (reason == OFPPR_DELETE) {
682         memset(pw_opp, 0, sizeof *pw_opp);
683         pw_opp->port_no = htons(OFPP_NONE);
684     } else if (reason == OFPPR_MOD || reason == OFPPR_ADD) {
685         *pw_opp = *opp;
686         sanitize_opp(pw_opp);
687     }
688     call_pw_callbacks(pw, port_no, &old, pw_opp);
689 }
690
691 static bool
692 port_watcher_local_packet_cb(struct relay *r, void *pw_)
693 {
694     struct port_watcher *pw = pw_;
695     struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
696     struct ofp_header *oh = msg->data;
697
698     if (oh->type == OFPT_FEATURES_REPLY
699         && msg->size >= offsetof(struct ofp_switch_features, ports)) {
700         struct ofp_switch_features *osf = msg->data;
701         bool seen[ARRAY_SIZE(pw->ports)];
702         size_t n_ports;
703         size_t i;
704
705         pw->got_feature_reply = true;
706
707         /* Update each port included in the message. */
708         memset(seen, 0, sizeof seen);
709         n_ports = ((msg->size - offsetof(struct ofp_switch_features, ports))
710                    / sizeof *osf->ports);
711         for (i = 0; i < n_ports; i++) {
712             update_phy_port(pw, &osf->ports[i], OFPPR_MOD, seen);
713         }
714
715         /* Delete all the ports not included in the message. */
716         for (i = 0; i < ARRAY_SIZE(pw->ports); i++) {
717             if (!seen[i]) {
718                 update_phy_port(pw, &pw->ports[i], OFPPR_DELETE, NULL);
719             }
720         }
721     } else if (oh->type == OFPT_PORT_STATUS
722                && msg->size >= sizeof(struct ofp_port_status)) {
723         struct ofp_port_status *ops = msg->data;
724         update_phy_port(pw, &ops->desc, ops->reason, NULL);
725     }
726     return false;
727 }
728
729 static void
730 port_watcher_periodic_cb(void *pw_)
731 {
732     struct port_watcher *pw = pw_;
733
734     if (!pw->got_feature_reply && time_now() >= pw->last_feature_request + 5) {
735         struct buffer *b;
736         make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &b);
737         rconn_send_with_limit(pw->local_rconn, b, &pw->n_txq, 1);
738         pw->last_feature_request = time_now();
739     }
740 }
741
742 static void
743 put_duplexes(struct ds *ds, const char *name, uint32_t features,
744              uint32_t hd_bit, uint32_t fd_bit)
745 {
746     if (features & (hd_bit | fd_bit)) {
747         ds_put_format(ds, " %s", name);
748         if (features & hd_bit) {
749             ds_put_cstr(ds, "(HD)");
750         }
751         if (features & fd_bit) {
752             ds_put_cstr(ds, "(FD)");
753         }
754     }
755 }
756
757 static void
758 log_port_status(uint16_t port_no,
759                 const struct ofp_phy_port *old,
760                 const struct ofp_phy_port *new,
761                 void *aux)
762 {
763     if (VLOG_IS_DBG_ENABLED()) {
764         bool was_enabled = old->port_no != htons(OFPP_NONE);
765         bool now_enabled = new->port_no != htons(OFPP_NONE);
766         uint32_t features = ntohl(new->features);
767         struct ds ds;
768
769         if (old->flags != new->flags && opp_differs(old, new) == 1) {
770             /* Don't care if only flags changed. */
771             return;
772         }
773
774         ds_init(&ds);
775         ds_put_format(&ds, "\"%s\", "ETH_ADDR_FMT, new->name,
776                       ETH_ADDR_ARGS(new->hw_addr));
777         if (ntohl(new->speed)) {
778             ds_put_format(&ds, ", speed %"PRIu32, ntohl(new->speed));
779         }
780         if (features & (OFPPF_10MB_HD | OFPPF_10MB_FD
781                         | OFPPF_100MB_HD | OFPPF_100MB_FD
782                         | OFPPF_1GB_HD | OFPPF_1GB_FD | OFPPF_10GB_FD)) {
783             ds_put_cstr(&ds, ", supports");
784             put_duplexes(&ds, "10M", features, OFPPF_10MB_HD, OFPPF_10MB_FD);
785             put_duplexes(&ds, "100M", features,
786                          OFPPF_100MB_HD, OFPPF_100MB_FD);
787             put_duplexes(&ds, "1G", features, OFPPF_100MB_HD, OFPPF_100MB_FD);
788             if (features & OFPPF_10GB_FD) {
789                 ds_put_cstr(&ds, " 10G");
790             }
791         }
792         if (was_enabled != now_enabled) {
793             if (now_enabled) {
794                 VLOG_DBG("Port %d added: %s", port_no, ds_cstr(&ds));
795             } else {
796                 VLOG_DBG("Port %d deleted", port_no);
797             }
798         } else {
799             VLOG_DBG("Port %d changed: %s", port_no, ds_cstr(&ds));
800         }
801         ds_destroy(&ds);
802     }
803 }
804
805 static void
806 port_watcher_register_callback(struct port_watcher *pw,
807                                port_watcher_cb_func *function,
808                                void *aux)
809 {
810     assert(pw->n_cbs < ARRAY_SIZE(pw->cbs));
811     pw->cbs[pw->n_cbs].function = function;
812     pw->cbs[pw->n_cbs].aux = aux;
813     pw->n_cbs++;
814 }
815
816 static uint32_t
817 port_watcher_get_flags(const struct port_watcher *pw, int port_no)
818 {
819     int idx = port_no_to_pw_idx(port_no);
820     return idx >= 0 ? ntohl(pw->ports[idx].flags) : 0;
821 }
822
823 static void
824 port_watcher_set_flags(struct port_watcher *pw,
825                        int port_no, uint32_t flags, uint32_t mask)
826 {
827     struct ofp_phy_port old;
828     struct ofp_phy_port *p;
829     struct ofp_port_mod *opm;
830     struct ofp_port_status *ops;
831     struct buffer *b;
832     int idx;
833
834     idx = port_no_to_pw_idx(port_no);
835     if (idx < 0) {
836         return;
837     }
838
839     p = &pw->ports[idx];
840     if (!((ntohl(p->flags) ^ flags) & mask)) {
841         return;
842     }
843     old = *p;
844
845     /* Update our idea of the flags. */
846     p->flags = ntohl(flags);
847     call_pw_callbacks(pw, port_no, &old, p);
848
849     /* Change the flags in the datapath. */
850     opm = make_openflow(sizeof *opm, OFPT_PORT_MOD, &b);
851     opm->mask = htonl(mask);
852     opm->desc = *p;
853     rconn_send(pw->local_rconn, b, NULL);
854
855     /* Notify the controller that the flags changed. */
856     ops = make_openflow(sizeof *ops, OFPT_PORT_STATUS, &b);
857     ops->reason = OFPPR_MOD;
858     ops->desc = *p;
859     rconn_send(pw->remote_rconn, b, NULL);
860 }
861
862 static bool
863 port_watcher_is_ready(const struct port_watcher *pw)
864 {
865     return pw->got_feature_reply;
866 }
867
868 static struct hook
869 port_watcher_create(struct rconn *local_rconn, struct rconn *remote_rconn,
870                     struct port_watcher **pwp)
871 {
872     struct port_watcher *pw;
873     int i;
874
875     pw = *pwp = xcalloc(1, sizeof *pw);
876     pw->local_rconn = local_rconn;
877     pw->remote_rconn = remote_rconn;
878     pw->last_feature_request = TIME_MIN;
879     for (i = 0; i < OFPP_MAX; i++) {
880         pw->ports[i].port_no = htons(OFPP_NONE);
881     }
882     port_watcher_register_callback(pw, log_port_status, NULL);
883     return make_hook(port_watcher_local_packet_cb, NULL,
884                      port_watcher_periodic_cb, NULL, pw);
885 }
886 \f
887 /* Spanning tree protocol. */
888
889 /* Extra time, in seconds, at boot before going into fail-open, to give the
890  * spanning tree protocol time to figure out the network layout. */
891 #define STP_EXTRA_BOOT_TIME 30
892
893 struct stp_data {
894     struct stp *stp;
895     struct port_watcher *pw;
896     struct rconn *local_rconn;
897     struct rconn *remote_rconn;
898     uint8_t dpid[ETH_ADDR_LEN];
899     long long int last_tick_256ths;
900     int n_txq;
901 };
902
903 static bool
904 stp_local_packet_cb(struct relay *r, void *stp_)
905 {
906     struct stp_data *stp = stp_;
907     struct ofp_packet_in *opi;
908     struct eth_header *eth;
909     struct llc_header *llc;
910     struct buffer payload;
911     uint16_t port_no;
912     struct flow flow;
913
914     if (!get_ofp_packet_eth_header(r, &opi, &eth)
915         || !eth_addr_equals(eth->eth_dst, stp_eth_addr)) {
916         return false;
917     }
918
919     port_no = ntohs(opi->in_port);
920     if (port_no >= STP_MAX_PORTS) {
921         /* STP only supports 255 ports. */
922         return false;
923     }
924     if (port_watcher_get_flags(stp->pw, port_no) & OFPPFL_NO_STP) {
925         /* We're not doing STP on this port. */
926         return false;
927     }
928
929     if (opi->reason == OFPR_ACTION) {
930         /* The controller set up a flow for this, so we won't intercept it. */
931         return false;
932     }
933
934     get_ofp_packet_payload(opi, &payload);
935     flow_extract(&payload, port_no, &flow);
936     if (flow.dl_type != htons(OFP_DL_TYPE_NOT_ETH_TYPE)) {
937         VLOG_DBG("non-LLC frame received on STP multicast address");
938         return false;
939     }
940     llc = buffer_at_assert(&payload, sizeof *eth, sizeof *llc);
941     if (llc->llc_dsap != STP_LLC_DSAP) {
942         VLOG_DBG("bad DSAP 0x%02"PRIx8" received on STP multicast address",
943                  llc->llc_dsap);
944         return false;
945     }
946
947     /* Trim off padding on payload. */
948     if (payload.size > ntohs(eth->eth_type) + ETH_HEADER_LEN) {
949         payload.size = ntohs(eth->eth_type) + ETH_HEADER_LEN;
950     }
951     if (buffer_try_pull(&payload, ETH_HEADER_LEN + LLC_HEADER_LEN)) {
952         struct stp_port *p = stp_get_port(stp->stp, port_no);
953         stp_received_bpdu(p, payload.data, payload.size);
954     }
955
956     return true;
957 }
958
959 static long long int
960 time_256ths(void)
961 {
962     return time_msec() * 256 / 1000;
963 }
964
965 static void
966 stp_periodic_cb(void *stp_)
967 {
968     struct stp_data *stp = stp_;
969     long long int now_256ths = time_256ths();
970     long long int elapsed_256ths = now_256ths - stp->last_tick_256ths;
971     struct stp_port *p;
972
973     if (!port_watcher_is_ready(stp->pw)) {
974         /* Can't start STP until we know port flags, because port flags can
975          * disable STP. */
976         return;
977     }
978     if (elapsed_256ths <= 0) {
979         return;
980     }
981
982     stp_tick(stp->stp, MIN(INT_MAX, elapsed_256ths));
983     stp->last_tick_256ths = now_256ths;
984
985     while (stp_get_changed_port(stp->stp, &p)) {
986         int port_no = stp_port_no(p);
987         enum stp_state state = stp_port_get_state(p);
988
989         if (state != STP_DISABLED) {
990             VLOG_WARN("STP: Port %d entered %s state",
991                       port_no, stp_state_name(state));
992         }
993         if (!(port_watcher_get_flags(stp->pw, port_no) & OFPPFL_NO_STP)) {
994             uint32_t flags;
995             switch (state) {
996             case STP_LISTENING:
997                 flags = OFPPFL_STP_LISTEN;
998                 break;
999             case STP_LEARNING:
1000                 flags = OFPPFL_STP_LEARN;
1001                 break;
1002             case STP_DISABLED:
1003             case STP_FORWARDING:
1004                 flags = OFPPFL_STP_FORWARD;
1005                 break;
1006             case STP_BLOCKING:
1007                 flags = OFPPFL_STP_BLOCK;
1008                 break;
1009             default:
1010                 VLOG_DBG_RL(&vrl, "STP: Port %d has bad state %x",
1011                             port_no, state);
1012                 flags = OFPPFL_STP_FORWARD;
1013                 break;
1014             }
1015             if (!stp_forward_in_state(state)) {
1016                 flags |= OFPPFL_NO_FLOOD;
1017             }
1018             port_watcher_set_flags(stp->pw, port_no, flags,
1019                                    OFPPFL_STP_MASK | OFPPFL_NO_FLOOD);
1020         } else {
1021             /* We don't own those flags. */
1022         }
1023     }
1024 }
1025
1026 static void
1027 stp_wait_cb(void *stp_ UNUSED)
1028 {
1029     poll_timer_wait(1000);
1030 }
1031
1032 static void
1033 send_bpdu(const void *bpdu, size_t bpdu_size, int port_no, void *stp_)
1034 {
1035     struct stp_data *stp = stp_;
1036     struct eth_header *eth;
1037     struct llc_header *llc;
1038     struct buffer pkt, *opo;
1039
1040     /* Packet skeleton. */
1041     buffer_init(&pkt, ETH_HEADER_LEN + LLC_HEADER_LEN + bpdu_size);
1042     eth = buffer_put_uninit(&pkt, sizeof *eth);
1043     llc = buffer_put_uninit(&pkt, sizeof *llc);
1044     buffer_put(&pkt, bpdu, bpdu_size);
1045
1046     /* 802.2 header. */
1047     memcpy(eth->eth_dst, stp_eth_addr, ETH_ADDR_LEN);
1048     memcpy(eth->eth_src, stp->pw->ports[port_no].hw_addr, ETH_ADDR_LEN);
1049     eth->eth_type = htons(pkt.size - ETH_HEADER_LEN);
1050
1051     /* LLC header. */
1052     llc->llc_dsap = STP_LLC_DSAP;
1053     llc->llc_ssap = STP_LLC_SSAP;
1054     llc->llc_cntl = STP_LLC_CNTL;
1055
1056     opo = make_unbuffered_packet_out(&pkt, OFPP_NONE, port_no);
1057     buffer_uninit(&pkt);
1058     rconn_send_with_limit(stp->local_rconn, opo, &stp->n_txq, OFPP_MAX);
1059 }
1060
1061 static void
1062 stp_port_watcher_cb(uint16_t port_no,
1063                     const struct ofp_phy_port *old,
1064                     const struct ofp_phy_port *new,
1065                     void *stp_)
1066 {
1067     struct stp_data *stp = stp_;
1068     struct stp_port *p;
1069
1070     /* STP only supports a maximum of 255 ports, one less than OpenFlow.  We
1071      * don't support STP on OFPP_LOCAL, either.  */
1072     if (port_no >= STP_MAX_PORTS) {
1073         return;
1074     }
1075
1076     p = stp_get_port(stp->stp, port_no);
1077     if (new->port_no == htons(OFPP_NONE)
1078         || new->flags & htonl(OFPPFL_NO_STP)) {
1079         stp_port_disable(p);
1080     } else {
1081         stp_port_enable(p);
1082         stp_port_set_speed(p, new->speed);
1083     }
1084 }
1085
1086 static struct hook
1087 stp_hook_create(const struct settings *s, struct port_watcher *pw,
1088                 struct rconn *local, struct rconn *remote)
1089 {
1090     uint8_t dpid[ETH_ADDR_LEN];
1091     struct netdev *netdev;
1092     struct stp_data *stp;
1093     int retval;
1094
1095     retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
1096     if (retval) {
1097         fatal(retval, "Could not open %s device", s->of_name);
1098     }
1099     memcpy(dpid, netdev_get_etheraddr(netdev), ETH_ADDR_LEN);
1100     netdev_close(netdev);
1101
1102     stp = xcalloc(1, sizeof *stp);
1103     stp->stp = stp_create("stp", eth_addr_to_uint64(dpid), send_bpdu, stp);
1104     stp->pw = pw;
1105     memcpy(stp->dpid, dpid, ETH_ADDR_LEN);
1106     stp->local_rconn = local;
1107     stp->remote_rconn = remote;
1108     stp->last_tick_256ths = time_256ths();
1109
1110     port_watcher_register_callback(pw, stp_port_watcher_cb, stp);
1111     return make_hook(stp_local_packet_cb, NULL,
1112                      stp_periodic_cb, stp_wait_cb, stp);
1113 }
1114 \f
1115 /* In-band control. */
1116
1117 struct in_band_data {
1118     const struct settings *s;
1119     struct mac_learning *ml;
1120     struct netdev *of_device;
1121     struct rconn *controller;
1122     uint8_t mac[ETH_ADDR_LEN];
1123     int n_queued;
1124 };
1125
1126 static void
1127 queue_tx(struct rconn *rc, struct in_band_data *in_band, struct buffer *b)
1128 {
1129     rconn_send_with_limit(rc, b, &in_band->n_queued, 10);
1130 }
1131
1132 static const uint8_t *
1133 get_controller_mac(struct in_band_data *in_band)
1134 {
1135     static uint32_t ip, last_nonzero_ip;
1136     static uint8_t mac[ETH_ADDR_LEN], last_nonzero_mac[ETH_ADDR_LEN];
1137     static time_t next_refresh = 0;
1138
1139     uint32_t last_ip = ip;
1140
1141     time_t now = time_now();
1142
1143     ip = rconn_get_ip(in_band->controller);
1144     if (last_ip != ip || !next_refresh || now >= next_refresh) {
1145         bool have_mac;
1146
1147         /* Look up MAC address. */
1148         memset(mac, 0, sizeof mac);
1149         if (ip) {
1150             int retval = netdev_arp_lookup(in_band->of_device, ip, mac);
1151             if (retval) {
1152                 VLOG_DBG("cannot look up controller hw address ("IP_FMT"): %s",
1153                          IP_ARGS(&ip), strerror(retval));
1154             }
1155         }
1156         have_mac = !eth_addr_is_zero(mac);
1157
1158         /* Log changes in IP, MAC addresses. */
1159         if (ip && ip != last_nonzero_ip) {
1160             VLOG_DBG("controller IP address changed from "IP_FMT
1161                      " to "IP_FMT, IP_ARGS(&last_nonzero_ip), IP_ARGS(&ip));
1162             last_nonzero_ip = ip;
1163         }
1164         if (have_mac && memcmp(last_nonzero_mac, mac, ETH_ADDR_LEN)) {
1165             VLOG_DBG("controller MAC address changed from "ETH_ADDR_FMT" to "
1166                      ETH_ADDR_FMT,
1167                      ETH_ADDR_ARGS(last_nonzero_mac), ETH_ADDR_ARGS(mac));
1168             memcpy(last_nonzero_mac, mac, ETH_ADDR_LEN);
1169         }
1170
1171         /* Schedule next refresh.
1172          *
1173          * If we have an IP address but not a MAC address, then refresh
1174          * quickly, since we probably will get a MAC address soon (via ARP).
1175          * Otherwise, we can afford to wait a little while. */
1176         next_refresh = now + (!ip || have_mac ? 10 : 1);
1177     }
1178     return !eth_addr_is_zero(mac) ? mac : NULL;
1179 }
1180
1181 static bool
1182 is_controller_mac(const uint8_t dl_addr[ETH_ADDR_LEN],
1183                   struct in_band_data *in_band)
1184 {
1185     const uint8_t *mac = get_controller_mac(in_band);
1186     return mac && eth_addr_equals(mac, dl_addr);
1187 }
1188
1189 static void
1190 in_band_learn_mac(struct in_band_data *in_band,
1191                   uint16_t in_port, const uint8_t src_mac[ETH_ADDR_LEN])
1192 {
1193     if (mac_learning_learn(in_band->ml, src_mac, in_port)) {
1194         VLOG_DBG_RL(&vrl, "learned that "ETH_ADDR_FMT" is on port %"PRIu16,
1195                     ETH_ADDR_ARGS(src_mac), in_port);
1196     }
1197 }
1198
1199 static bool
1200 in_band_local_packet_cb(struct relay *r, void *in_band_)
1201 {
1202     struct in_band_data *in_band = in_band_;
1203     struct rconn *rc = r->halves[HALF_LOCAL].rconn;
1204     struct ofp_packet_in *opi;
1205     struct eth_header *eth;
1206     struct buffer payload;
1207     struct flow flow;
1208     uint16_t in_port;
1209     int out_port;
1210
1211     if (!get_ofp_packet_eth_header(r, &opi, &eth)) {
1212         return false;
1213     }
1214     in_port = ntohs(opi->in_port);
1215
1216     /* Deal with local stuff. */
1217     if (in_port == OFPP_LOCAL) {
1218         /* Sent by secure channel. */
1219         out_port = mac_learning_lookup(in_band->ml, eth->eth_dst);
1220     } else if (eth_addr_equals(eth->eth_dst, in_band->mac)) {
1221         /* Sent to secure channel. */
1222         out_port = OFPP_LOCAL;
1223         in_band_learn_mac(in_band, in_port, eth->eth_src);
1224     } else if (eth->eth_type == htons(ETH_TYPE_ARP)
1225                && eth_addr_is_broadcast(eth->eth_dst)
1226                && is_controller_mac(eth->eth_src, in_band)) {
1227         /* ARP sent by controller. */
1228         out_port = OFPP_FLOOD;
1229     } else if (is_controller_mac(eth->eth_dst, in_band)
1230                || is_controller_mac(eth->eth_src, in_band)) {
1231         /* Traffic to or from controller.  Switch it by hand. */
1232         in_band_learn_mac(in_band, in_port, eth->eth_src);
1233         out_port = mac_learning_lookup(in_band->ml, eth->eth_dst);
1234     } else {
1235         const uint8_t *controller_mac;
1236         controller_mac = get_controller_mac(in_band);
1237         if (eth->eth_type == htons(ETH_TYPE_ARP)
1238             && eth_addr_is_broadcast(eth->eth_dst)
1239             && is_controller_mac(eth->eth_src, in_band)) {
1240             /* ARP sent by controller. */
1241             out_port = OFPP_FLOOD;
1242         } else if (is_controller_mac(eth->eth_dst, in_band)
1243                    && in_port == mac_learning_lookup(in_band->ml,
1244                                                      controller_mac)) {
1245             /* Drop controller traffic that arrives on the controller port. */
1246             out_port = -1;
1247         } else {
1248             return false;
1249         }
1250     }
1251
1252     get_ofp_packet_payload(opi, &payload);
1253     flow_extract(&payload, in_port, &flow);
1254     if (in_port == out_port) {
1255         /* The input and output port match.  Set up a flow to drop packets. */
1256         queue_tx(rc, in_band, make_add_flow(&flow, ntohl(opi->buffer_id),
1257                                           in_band->s->max_idle, 0));
1258     } else if (out_port != OFPP_FLOOD) {
1259         /* The output port is known, so add a new flow. */
1260         queue_tx(rc, in_band,
1261                  make_add_simple_flow(&flow, ntohl(opi->buffer_id),
1262                                       out_port, in_band->s->max_idle));
1263
1264         /* If the switch didn't buffer the packet, we need to send a copy. */
1265         if (ntohl(opi->buffer_id) == UINT32_MAX) {
1266             queue_tx(rc, in_band,
1267                      make_unbuffered_packet_out(&payload, in_port, out_port));
1268         }
1269     } else {
1270         /* We don't know that MAC.  Send along the packet without setting up a
1271          * flow. */
1272         struct buffer *b;
1273         if (ntohl(opi->buffer_id) == UINT32_MAX) {
1274             b = make_unbuffered_packet_out(&payload, in_port, out_port);
1275         } else {
1276             b = make_buffered_packet_out(ntohl(opi->buffer_id),
1277                                          in_port, out_port);
1278         }
1279         queue_tx(rc, in_band, b);
1280     }
1281     return true;
1282 }
1283
1284 static void
1285 in_band_status_cb(struct status_reply *sr, void *in_band_)
1286 {
1287     struct in_band_data *in_band = in_band_;
1288     struct in_addr local_ip;
1289     uint32_t controller_ip;
1290     const uint8_t *controller_mac;
1291
1292     if (netdev_get_in4(in_band->of_device, &local_ip)) {
1293         status_reply_put(sr, "local-ip="IP_FMT, IP_ARGS(&local_ip.s_addr));
1294     }
1295     status_reply_put(sr, "local-mac="ETH_ADDR_FMT,
1296                      ETH_ADDR_ARGS(in_band->mac));
1297
1298     controller_ip = rconn_get_ip(in_band->controller);
1299     if (controller_ip) {
1300         status_reply_put(sr, "controller-ip="IP_FMT,
1301                       IP_ARGS(&controller_ip));
1302     }
1303     controller_mac = get_controller_mac(in_band);
1304     if (controller_mac) {
1305         status_reply_put(sr, "controller-mac="ETH_ADDR_FMT,
1306                       ETH_ADDR_ARGS(controller_mac));
1307     }
1308 }
1309
1310 static void
1311 get_ofp_packet_payload(struct ofp_packet_in *opi, struct buffer *payload)
1312 {
1313     payload->data = opi->data;
1314     payload->size = ntohs(opi->header.length) - offsetof(struct ofp_packet_in,
1315                                                          data);
1316 }
1317
1318 static struct hook
1319 in_band_hook_create(const struct settings *s, struct switch_status *ss,
1320                     struct rconn *remote)
1321 {
1322     struct in_band_data *in_band;
1323     int retval;
1324
1325     in_band = xcalloc(1, sizeof *in_band);
1326     in_band->s = s;
1327     in_band->ml = mac_learning_create();
1328     retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE,
1329                          &in_band->of_device);
1330     if (retval) {
1331         fatal(retval, "Could not open %s device", s->of_name);
1332     }
1333     memcpy(in_band->mac, netdev_get_etheraddr(in_band->of_device),
1334            ETH_ADDR_LEN);
1335     in_band->controller = remote;
1336     switch_status_register_category(ss, "in-band", in_band_status_cb, in_band);
1337     return make_hook(in_band_local_packet_cb, NULL, NULL, NULL, in_band);
1338 }
1339 \f
1340 /* Fail open support. */
1341
1342 struct fail_open_data {
1343     const struct settings *s;
1344     struct rconn *local_rconn;
1345     struct rconn *remote_rconn;
1346     struct lswitch *lswitch;
1347     int last_disconn_secs;
1348     time_t boot_deadline;
1349 };
1350
1351 /* Causes 'r' to enter or leave fail-open mode, if appropriate. */
1352 static void
1353 fail_open_periodic_cb(void *fail_open_)
1354 {
1355     struct fail_open_data *fail_open = fail_open_;
1356     int disconn_secs;
1357     bool open;
1358
1359     if (time_now() < fail_open->boot_deadline) {
1360         return;
1361     }
1362     disconn_secs = rconn_disconnected_duration(fail_open->remote_rconn);
1363     open = disconn_secs >= fail_open->s->probe_interval * 3;
1364     if (open != (fail_open->lswitch != NULL)) {
1365         if (!open) {
1366             VLOG_WARN("No longer in fail-open mode");
1367             lswitch_destroy(fail_open->lswitch);
1368             fail_open->lswitch = NULL;
1369         } else {
1370             VLOG_WARN("Could not connect to controller for %d seconds, "
1371                       "failing open", disconn_secs);
1372             fail_open->lswitch = lswitch_create(fail_open->local_rconn, true,
1373                                                 fail_open->s->max_idle);
1374             fail_open->last_disconn_secs = disconn_secs;
1375         }
1376     } else if (open && disconn_secs > fail_open->last_disconn_secs + 60) {
1377         VLOG_WARN("Still in fail-open mode after %d seconds disconnected "
1378                   "from controller", disconn_secs);
1379         fail_open->last_disconn_secs = disconn_secs;
1380     }
1381 }
1382
1383 static bool
1384 fail_open_local_packet_cb(struct relay *r, void *fail_open_)
1385 {
1386     struct fail_open_data *fail_open = fail_open_;
1387     if (!fail_open->lswitch) {
1388         return false;
1389     } else {
1390         lswitch_process_packet(fail_open->lswitch, fail_open->local_rconn,
1391                                r->halves[HALF_LOCAL].rxbuf);
1392         rconn_run(fail_open->local_rconn);
1393         return true;
1394     }
1395 }
1396
1397 static void
1398 fail_open_status_cb(struct status_reply *sr, void *fail_open_)
1399 {
1400     struct fail_open_data *fail_open = fail_open_;
1401     const struct settings *s = fail_open->s;
1402     int trigger_duration = s->probe_interval * 3;
1403     int cur_duration = rconn_disconnected_duration(fail_open->remote_rconn);
1404
1405     status_reply_put(sr, "trigger-duration=%d", trigger_duration);
1406     status_reply_put(sr, "current-duration=%d", cur_duration);
1407     status_reply_put(sr, "triggered=%s",
1408                      cur_duration >= trigger_duration ? "true" : "false");
1409     status_reply_put(sr, "max-idle=%d", s->max_idle);
1410 }
1411
1412 static struct hook
1413 fail_open_hook_create(const struct settings *s, struct switch_status *ss,
1414                       struct rconn *local_rconn, struct rconn *remote_rconn)
1415 {
1416     struct fail_open_data *fail_open = xmalloc(sizeof *fail_open);
1417     fail_open->s = s;
1418     fail_open->local_rconn = local_rconn;
1419     fail_open->remote_rconn = remote_rconn;
1420     fail_open->lswitch = NULL;
1421     fail_open->boot_deadline = time_now() + s->probe_interval * 3;
1422     fail_open->boot_deadline += STP_EXTRA_BOOT_TIME;
1423     switch_status_register_category(ss, "fail-open",
1424                                     fail_open_status_cb, fail_open);
1425     return make_hook(fail_open_local_packet_cb, NULL,
1426                      fail_open_periodic_cb, NULL, fail_open);
1427 }
1428 \f
1429 struct rate_limiter {
1430     const struct settings *s;
1431     struct rconn *remote_rconn;
1432
1433     /* One queue per physical port. */
1434     struct queue queues[OFPP_MAX];
1435     int n_queued;               /* Sum over queues[*].n. */
1436     int next_tx_port;           /* Next port to check in round-robin. */
1437
1438     /* Token bucket.
1439      *
1440      * It costs 1000 tokens to send a single packet_in message.  A single token
1441      * per message would be more straightforward, but this choice lets us avoid
1442      * round-off error in refill_bucket()'s calculation of how many tokens to
1443      * add to the bucket, since no division step is needed. */
1444     long long int last_fill;    /* Time at which we last added tokens. */
1445     int tokens;                 /* Current number of tokens. */
1446
1447     /* Transmission queue. */
1448     int n_txq;                  /* No. of packets waiting in rconn for tx. */
1449
1450     /* Statistics reporting. */
1451     unsigned long long n_normal;        /* # txed w/o rate limit queuing. */
1452     unsigned long long n_limited;       /* # queued for rate limiting. */
1453     unsigned long long n_queue_dropped; /* # dropped due to queue overflow. */
1454     unsigned long long n_tx_dropped;    /* # dropped due to tx overflow. */
1455 };
1456
1457 /* Drop a packet from the longest queue in 'rl'. */
1458 static void
1459 drop_packet(struct rate_limiter *rl)
1460 {
1461     struct queue *longest;      /* Queue currently selected as longest. */
1462     int n_longest;              /* # of queues of same length as 'longest'. */
1463     struct queue *q;
1464
1465     longest = &rl->queues[0];
1466     n_longest = 1;
1467     for (q = &rl->queues[0]; q < &rl->queues[OFPP_MAX]; q++) {
1468         if (longest->n < q->n) {
1469             longest = q;
1470             n_longest = 1;
1471         } else if (longest->n == q->n) {
1472             n_longest++;
1473
1474             /* Randomly select one of the longest queues, with a uniform
1475              * distribution (Knuth algorithm 3.4.2R). */
1476             if (!random_range(n_longest)) {
1477                 longest = q;
1478             }
1479         }
1480     }
1481
1482     /* FIXME: do we want to pop the tail instead? */
1483     buffer_delete(queue_pop_head(longest));
1484     rl->n_queued--;
1485 }
1486
1487 /* Remove and return the next packet to transmit (in round-robin order). */
1488 static struct buffer *
1489 dequeue_packet(struct rate_limiter *rl)
1490 {
1491     unsigned int i;
1492
1493     for (i = 0; i < OFPP_MAX; i++) {
1494         unsigned int port = (rl->next_tx_port + i) % OFPP_MAX;
1495         struct queue *q = &rl->queues[port];
1496         if (q->n) {
1497             rl->next_tx_port = (port + 1) % OFPP_MAX;
1498             rl->n_queued--;
1499             return queue_pop_head(q);
1500         }
1501     }
1502     NOT_REACHED();
1503 }
1504
1505 /* Add tokens to the bucket based on elapsed time. */
1506 static void
1507 refill_bucket(struct rate_limiter *rl)
1508 {
1509     const struct settings *s = rl->s;
1510     long long int now = time_msec();
1511     long long int tokens = (now - rl->last_fill) * s->rate_limit + rl->tokens;
1512     if (tokens >= 1000) {
1513         rl->last_fill = now;
1514         rl->tokens = MIN(tokens, s->burst_limit * 1000);
1515     }
1516 }
1517
1518 /* Attempts to remove enough tokens from 'rl' to transmit a packet.  Returns
1519  * true if successful, false otherwise.  (In the latter case no tokens are
1520  * removed.) */
1521 static bool
1522 get_token(struct rate_limiter *rl)
1523 {
1524     if (rl->tokens >= 1000) {
1525         rl->tokens -= 1000;
1526         return true;
1527     } else {
1528         return false;
1529     }
1530 }
1531
1532 static bool
1533 rate_limit_local_packet_cb(struct relay *r, void *rl_)
1534 {
1535     struct rate_limiter *rl = rl_;
1536     const struct settings *s = rl->s;
1537     struct ofp_packet_in *opi;
1538
1539     opi = get_ofp_packet_in(r);
1540     if (!opi) {
1541         return false;
1542     }
1543
1544     if (!rl->n_queued && get_token(rl)) {
1545         /* In the common case where we are not constrained by the rate limit,
1546          * let the packet take the normal path. */
1547         rl->n_normal++;
1548         return false;
1549     } else {
1550         /* Otherwise queue it up for the periodic callback to drain out. */
1551         struct buffer *msg = r->halves[HALF_LOCAL].rxbuf;
1552         int port = ntohs(opi->in_port) % OFPP_MAX;
1553         if (rl->n_queued >= s->burst_limit) {
1554             drop_packet(rl);
1555         }
1556         queue_push_tail(&rl->queues[port], buffer_clone(msg));
1557         rl->n_queued++;
1558         rl->n_limited++;
1559         return true;
1560     }
1561 }
1562
1563 static void
1564 rate_limit_status_cb(struct status_reply *sr, void *rl_)
1565 {
1566     struct rate_limiter *rl = rl_;
1567
1568     status_reply_put(sr, "normal=%llu", rl->n_normal);
1569     status_reply_put(sr, "limited=%llu", rl->n_limited);
1570     status_reply_put(sr, "queue-dropped=%llu", rl->n_queue_dropped);
1571     status_reply_put(sr, "tx-dropped=%llu", rl->n_tx_dropped);
1572 }
1573
1574 static void
1575 rate_limit_periodic_cb(void *rl_)
1576 {
1577     struct rate_limiter *rl = rl_;
1578     int i;
1579
1580     /* Drain some packets out of the bucket if possible, but limit the number
1581      * of iterations to allow other code to get work done too. */
1582     refill_bucket(rl);
1583     for (i = 0; rl->n_queued && get_token(rl) && i < 50; i++) {
1584         /* Use a small, arbitrary limit for the amount of queuing to do here,
1585          * because the TCP connection is responsible for buffering and there is
1586          * no point in trying to transmit faster than the TCP connection can
1587          * handle. */
1588         struct buffer *b = dequeue_packet(rl);
1589         if (rconn_send_with_limit(rl->remote_rconn, b, &rl->n_txq, 10)) {
1590             rl->n_tx_dropped++;
1591         }
1592     }
1593 }
1594
1595 static void
1596 rate_limit_wait_cb(void *rl_)
1597 {
1598     struct rate_limiter *rl = rl_;
1599     if (rl->n_queued) {
1600         if (rl->tokens >= 1000) {
1601             /* We can transmit more packets as soon as we're called again. */
1602             poll_immediate_wake();
1603         } else {
1604             /* We have to wait for the bucket to re-fill.  We could calculate
1605              * the exact amount of time here for increased smoothness. */
1606             poll_timer_wait(TIME_UPDATE_INTERVAL / 2);
1607         }
1608     }
1609 }
1610
1611 static struct hook
1612 rate_limit_hook_create(const struct settings *s, struct switch_status *ss,
1613                        struct rconn *local, struct rconn *remote)
1614 {
1615     struct rate_limiter *rl;
1616     size_t i;
1617
1618     rl = xcalloc(1, sizeof *rl);
1619     rl->s = s;
1620     rl->remote_rconn = remote;
1621     for (i = 0; i < ARRAY_SIZE(rl->queues); i++) {
1622         queue_init(&rl->queues[i]);
1623     }
1624     rl->last_fill = time_msec();
1625     rl->tokens = s->rate_limit * 100;
1626     switch_status_register_category(ss, "rate-limit",
1627                                     rate_limit_status_cb, rl);
1628     return make_hook(rate_limit_local_packet_cb, NULL, rate_limit_periodic_cb,
1629                      rate_limit_wait_cb, rl);
1630 }
1631 \f
1632 /* OFPST_SWITCH statistics. */
1633
1634 struct switch_status_category {
1635     char *name;
1636     void (*cb)(struct status_reply *, void *aux);
1637     void *aux;
1638 };
1639
1640 struct switch_status {
1641     const struct settings *s;
1642     time_t booted;
1643     struct switch_status_category categories[8];
1644     int n_categories;
1645 };
1646
1647 struct status_reply {
1648     struct switch_status_category *category;
1649     struct ds request;
1650     struct ds output;
1651 };
1652
1653 static bool
1654 switch_status_remote_packet_cb(struct relay *r, void *ss_)
1655 {
1656     struct switch_status *ss = ss_;
1657     struct rconn *rc = r->halves[HALF_REMOTE].rconn;
1658     struct buffer *msg = r->halves[HALF_REMOTE].rxbuf;
1659     struct switch_status_category *c;
1660     struct ofp_stats_request *osr;
1661     struct ofp_stats_reply *reply;
1662     struct status_reply sr;
1663     struct ofp_header *oh;
1664     struct buffer *b;
1665     int retval;
1666
1667     oh = msg->data;
1668     if (oh->type != OFPT_STATS_REQUEST) {
1669         return false;
1670     }
1671     if (msg->size < sizeof(struct ofp_stats_request)) {
1672         VLOG_WARN_RL(&vrl, "packet too short (%zu bytes) for stats_request",
1673                      msg->size);
1674         return false;
1675     }
1676
1677     osr = msg->data;
1678     if (osr->type != htons(OFPST_SWITCH)) {
1679         return false;
1680     }
1681
1682     sr.request.string = (void *) (osr + 1);
1683     sr.request.length = msg->size - sizeof *osr;
1684     ds_init(&sr.output);
1685     for (c = ss->categories; c < &ss->categories[ss->n_categories]; c++) {
1686         if (!memcmp(c->name, sr.request.string,
1687                     MIN(strlen(c->name), sr.request.length))) {
1688             sr.category = c;
1689             c->cb(&sr, c->aux);
1690         }
1691     }
1692     reply = make_openflow_xid((offsetof(struct ofp_stats_reply, body)
1693                                + sr.output.length),
1694                               OFPT_STATS_REPLY, osr->header.xid, &b);
1695     reply->type = htons(OFPST_SWITCH);
1696     reply->flags = 0;
1697     memcpy(reply->body, sr.output.string, sr.output.length);
1698     retval = rconn_send(rc, b, NULL);
1699     if (retval && retval != EAGAIN) {
1700         VLOG_WARN("send failed (%s)", strerror(retval));
1701     }
1702     ds_destroy(&sr.output);
1703     return true;
1704 }
1705
1706 static void
1707 rconn_status_cb(struct status_reply *sr, void *rconn_)
1708 {
1709     struct rconn *rconn = rconn_;
1710     time_t now = time_now();
1711
1712     status_reply_put(sr, "name=%s", rconn_get_name(rconn));
1713     status_reply_put(sr, "state=%s", rconn_get_state(rconn));
1714     status_reply_put(sr, "backoff=%d", rconn_get_backoff(rconn));
1715     status_reply_put(sr, "is-connected=%s",
1716                      rconn_is_connected(rconn) ? "true" : "false");
1717     status_reply_put(sr, "sent-msgs=%u", rconn_packets_sent(rconn));
1718     status_reply_put(sr, "received-msgs=%u", rconn_packets_received(rconn));
1719     status_reply_put(sr, "attempted-connections=%u",
1720                      rconn_get_attempted_connections(rconn));
1721     status_reply_put(sr, "successful-connections=%u",
1722                      rconn_get_successful_connections(rconn));
1723     status_reply_put(sr, "last-connection=%ld",
1724                      (long int) (now - rconn_get_last_connection(rconn)));
1725     status_reply_put(sr, "time-connected=%lu",
1726                      rconn_get_total_time_connected(rconn));
1727     status_reply_put(sr, "state-elapsed=%u", rconn_get_state_elapsed(rconn));
1728 }
1729
1730 static void
1731 config_status_cb(struct status_reply *sr, void *s_)
1732 {
1733     const struct settings *s = s_;
1734     size_t i;
1735
1736     for (i = 0; i < s->n_listeners; i++) {
1737         status_reply_put(sr, "management%zu=%s", i, s->listener_names[i]);
1738     }
1739     if (s->probe_interval) {
1740         status_reply_put(sr, "probe-interval=%d", s->probe_interval);
1741     }
1742     if (s->max_backoff) {
1743         status_reply_put(sr, "max-backoff=%d", s->max_backoff);
1744     }
1745 }
1746
1747 static void
1748 switch_status_cb(struct status_reply *sr, void *ss_)
1749 {
1750     struct switch_status *ss = ss_;
1751     time_t now = time_now();
1752
1753     status_reply_put(sr, "now=%ld", (long int) now);
1754     status_reply_put(sr, "uptime=%ld", (long int) (now - ss->booted));
1755     status_reply_put(sr, "pid=%ld", (long int) getpid());
1756 }
1757
1758 static struct hook
1759 switch_status_hook_create(const struct settings *s, struct switch_status **ssp)
1760 {
1761     struct switch_status *ss = xcalloc(1, sizeof *ss);
1762     ss->s = s;
1763     ss->booted = time_now();
1764     switch_status_register_category(ss, "config",
1765                                     config_status_cb, (void *) s);
1766     switch_status_register_category(ss, "switch", switch_status_cb, ss);
1767     *ssp = ss;
1768     return make_hook(NULL, switch_status_remote_packet_cb, NULL, NULL, ss);
1769 }
1770
1771 static void
1772 switch_status_register_category(struct switch_status *ss,
1773                                 const char *category,
1774                                 void (*cb)(struct status_reply *,
1775                                            void *aux),
1776                                 void *aux)
1777 {
1778     struct switch_status_category *c;
1779     assert(ss->n_categories < ARRAY_SIZE(ss->categories));
1780     c = &ss->categories[ss->n_categories++];
1781     c->cb = cb;
1782     c->aux = aux;
1783     c->name = xstrdup(category);
1784 }
1785
1786 static void
1787 status_reply_put(struct status_reply *sr, const char *content, ...)
1788 {
1789     size_t old_length = sr->output.length;
1790     size_t added;
1791     va_list args;
1792
1793     /* Append the status reply to the output. */
1794     ds_put_format(&sr->output, "%s.", sr->category->name);
1795     va_start(args, content);
1796     ds_put_format_valist(&sr->output, content, args);
1797     va_end(args);
1798     if (ds_last(&sr->output) != '\n') {
1799         ds_put_char(&sr->output, '\n');
1800     }
1801
1802     /* Drop what we just added if it doesn't match the request. */
1803     added = sr->output.length - old_length;
1804     if (added < sr->request.length
1805         || memcmp(&sr->output.string[old_length],
1806                   sr->request.string, sr->request.length)) {
1807         ds_truncate(&sr->output, old_length);
1808     }
1809 }
1810
1811 \f
1812 /* Controller discovery. */
1813
1814 struct discovery
1815 {
1816     const struct settings *s;
1817     struct dhclient *dhcp;
1818     int n_changes;
1819 };
1820
1821 static void
1822 discovery_status_cb(struct status_reply *sr, void *d_)
1823 {
1824     struct discovery *d = d_;
1825
1826     status_reply_put(sr, "accept-remote=%s", d->s->accept_controller_re);
1827     status_reply_put(sr, "n-changes=%d", d->n_changes);
1828     status_reply_put(sr, "state=%s", dhclient_get_state(d->dhcp));
1829     status_reply_put(sr, "state-elapsed=%u",
1830                      dhclient_get_state_elapsed(d->dhcp));
1831     if (dhclient_is_bound(d->dhcp)) {
1832         uint32_t ip = dhclient_get_ip(d->dhcp);
1833         uint32_t netmask = dhclient_get_netmask(d->dhcp);
1834         uint32_t router = dhclient_get_router(d->dhcp);
1835
1836         const struct dhcp_msg *cfg = dhclient_get_config(d->dhcp);
1837         uint32_t dns_server;
1838         char *domain_name;
1839         int i;
1840
1841         status_reply_put(sr, "ip="IP_FMT, IP_ARGS(&ip));
1842         status_reply_put(sr, "netmask="IP_FMT, IP_ARGS(&netmask));
1843         if (router) {
1844             status_reply_put(sr, "router="IP_FMT, IP_ARGS(&router));
1845         }
1846
1847         for (i = 0; dhcp_msg_get_ip(cfg, DHCP_CODE_DNS_SERVER, i, &dns_server);
1848              i++) {
1849             status_reply_put(sr, "dns%d="IP_FMT, i, IP_ARGS(&dns_server));
1850         }
1851
1852         domain_name = dhcp_msg_get_string(cfg, DHCP_CODE_DOMAIN_NAME);
1853         if (domain_name) {
1854             status_reply_put(sr, "domain=%s", domain_name);
1855             free(domain_name);
1856         }
1857
1858         status_reply_put(sr, "lease-remaining=%u",
1859                          dhclient_get_lease_remaining(d->dhcp));
1860     }
1861 }
1862
1863 static struct discovery *
1864 discovery_init(const struct settings *s, struct switch_status *ss)
1865 {
1866     struct netdev *netdev;
1867     struct discovery *d;
1868     struct dhclient *dhcp;
1869     int retval;
1870
1871     /* Bring ofX network device up. */
1872     retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
1873     if (retval) {
1874         fatal(retval, "Could not open %s device", s->of_name);
1875     }
1876     retval = netdev_turn_flags_on(netdev, NETDEV_UP, true);
1877     if (retval) {
1878         fatal(retval, "Could not bring %s device up", s->of_name);
1879     }
1880     netdev_close(netdev);
1881
1882     /* Initialize DHCP client. */
1883     retval = dhclient_create(s->of_name, modify_dhcp_request,
1884                              validate_dhcp_offer, (void *) s, &dhcp);
1885     if (retval) {
1886         fatal(retval, "Failed to initialize DHCP client");
1887     }
1888     dhclient_init(dhcp, 0);
1889
1890     d = xmalloc(sizeof *d);
1891     d->s = s;
1892     d->dhcp = dhcp;
1893     d->n_changes = 0;
1894
1895     switch_status_register_category(ss, "discovery", discovery_status_cb, d);
1896
1897     return d;
1898 }
1899
1900 static void
1901 discovery_question_connectivity(struct discovery *d)
1902 {
1903     dhclient_force_renew(d->dhcp, 15);
1904 }
1905
1906 static bool
1907 discovery_run(struct discovery *d, char **controller_name)
1908 {
1909     dhclient_run(d->dhcp);
1910     if (!dhclient_changed(d->dhcp)) {
1911         return false;
1912     }
1913
1914     dhclient_configure_netdev(d->dhcp);
1915     if (d->s->update_resolv_conf) {
1916         dhclient_update_resolv_conf(d->dhcp);
1917     }
1918
1919     if (dhclient_is_bound(d->dhcp)) {
1920         *controller_name = dhcp_msg_get_string(dhclient_get_config(d->dhcp),
1921                                                DHCP_CODE_OFP_CONTROLLER_VCONN);
1922         VLOG_WARN("%s: discovered controller", *controller_name);
1923         d->n_changes++;
1924     } else {
1925         *controller_name = NULL;
1926         if (d->n_changes) {
1927             VLOG_WARN("discovered controller no longer available");
1928             d->n_changes++;
1929         }
1930     }
1931     return true;
1932 }
1933
1934 static void
1935 discovery_wait(struct discovery *d)
1936 {
1937     dhclient_wait(d->dhcp);
1938 }
1939
1940 static void
1941 modify_dhcp_request(struct dhcp_msg *msg, void *aux)
1942 {
1943     dhcp_msg_put_string(msg, DHCP_CODE_VENDOR_CLASS, "OpenFlow");
1944 }
1945
1946 static bool
1947 validate_dhcp_offer(const struct dhcp_msg *msg, void *s_)
1948 {
1949     const struct settings *s = s_;
1950     char *vconn_name;
1951     bool accept;
1952
1953     vconn_name = dhcp_msg_get_string(msg, DHCP_CODE_OFP_CONTROLLER_VCONN);
1954     if (!vconn_name) {
1955         VLOG_WARN_RL(&vrl, "rejecting DHCP offer missing controller vconn");
1956         return false;
1957     }
1958     accept = !regexec(&s->accept_controller_regex, vconn_name, 0, NULL, 0);
1959     if (!accept) {
1960         VLOG_WARN_RL(&vrl, "rejecting controller vconn that fails to match %s",
1961                      s->accept_controller_re);
1962     }
1963     free(vconn_name);
1964     return accept;
1965 }
1966 \f
1967 /* User interface. */
1968
1969 static void
1970 parse_options(int argc, char *argv[], struct settings *s)
1971 {
1972     enum {
1973         OPT_ACCEPT_VCONN = UCHAR_MAX + 1,
1974         OPT_NO_RESOLV_CONF,
1975         OPT_INACTIVITY_PROBE,
1976         OPT_MAX_IDLE,
1977         OPT_MAX_BACKOFF,
1978         OPT_RATE_LIMIT,
1979         OPT_BURST_LIMIT
1980     };
1981     static struct option long_options[] = {
1982         {"accept-vconn", required_argument, 0, OPT_ACCEPT_VCONN},
1983         {"no-resolv-conf", no_argument, 0, OPT_NO_RESOLV_CONF},
1984         {"fail",        required_argument, 0, 'F'},
1985         {"inactivity-probe", required_argument, 0, OPT_INACTIVITY_PROBE},
1986         {"max-idle",    required_argument, 0, OPT_MAX_IDLE},
1987         {"max-backoff", required_argument, 0, OPT_MAX_BACKOFF},
1988         {"listen",      required_argument, 0, 'l'},
1989         {"monitor",     required_argument, 0, 'm'},
1990         {"rate-limit",  optional_argument, 0, OPT_RATE_LIMIT},
1991         {"burst-limit", required_argument, 0, OPT_BURST_LIMIT},
1992         {"detach",      no_argument, 0, 'D'},
1993         {"force",       no_argument, 0, 'f'},
1994         {"pidfile",     optional_argument, 0, 'P'},
1995         {"verbose",     optional_argument, 0, 'v'},
1996         {"help",        no_argument, 0, 'h'},
1997         {"version",     no_argument, 0, 'V'},
1998         VCONN_SSL_LONG_OPTIONS
1999         {0, 0, 0, 0},
2000     };
2001     char *short_options = long_options_to_short_options(long_options);
2002     char *accept_re = NULL;
2003     int retval;
2004
2005     /* Set defaults that we can figure out before parsing options. */
2006     s->n_listeners = 0;
2007     s->monitor_name = NULL;
2008     s->fail_mode = FAIL_OPEN;
2009     s->max_idle = 15;
2010     s->probe_interval = 15;
2011     s->max_backoff = 15;
2012     s->update_resolv_conf = true;
2013     s->rate_limit = 0;
2014     s->burst_limit = 0;
2015     for (;;) {
2016         int c;
2017
2018         c = getopt_long(argc, argv, short_options, long_options, NULL);
2019         if (c == -1) {
2020             break;
2021         }
2022
2023         switch (c) {
2024         case OPT_ACCEPT_VCONN:
2025             accept_re = optarg[0] == '^' ? optarg : xasprintf("^%s", optarg);
2026             break;
2027
2028         case OPT_NO_RESOLV_CONF:
2029             s->update_resolv_conf = false;
2030             break;
2031
2032         case 'F':
2033             if (!strcmp(optarg, "open")) {
2034                 s->fail_mode = FAIL_OPEN;
2035             } else if (!strcmp(optarg, "closed")) {
2036                 s->fail_mode = FAIL_CLOSED;
2037             } else {
2038                 fatal(0,
2039                       "-f or --fail argument must be \"open\" or \"closed\"");
2040             }
2041             break;
2042
2043         case OPT_INACTIVITY_PROBE:
2044             s->probe_interval = atoi(optarg);
2045             if (s->probe_interval < 5) {
2046                 fatal(0, "--inactivity-probe argument must be at least 5");
2047             }
2048             break;
2049
2050         case OPT_MAX_IDLE:
2051             if (!strcmp(optarg, "permanent")) {
2052                 s->max_idle = OFP_FLOW_PERMANENT;
2053             } else {
2054                 s->max_idle = atoi(optarg);
2055                 if (s->max_idle < 1 || s->max_idle > 65535) {
2056                     fatal(0, "--max-idle argument must be between 1 and "
2057                           "65535 or the word 'permanent'");
2058                 }
2059             }
2060             break;
2061
2062         case OPT_MAX_BACKOFF:
2063             s->max_backoff = atoi(optarg);
2064             if (s->max_backoff < 1) {
2065                 fatal(0, "--max-backoff argument must be at least 1");
2066             } else if (s->max_backoff > 3600) {
2067                 s->max_backoff = 3600;
2068             }
2069             break;
2070
2071         case OPT_RATE_LIMIT:
2072             if (optarg) {
2073                 s->rate_limit = atoi(optarg);
2074                 if (s->rate_limit < 1) {
2075                     fatal(0, "--rate-limit argument must be at least 1");
2076                 }
2077             } else {
2078                 s->rate_limit = 1000;
2079             }
2080             break;
2081
2082         case OPT_BURST_LIMIT:
2083             s->burst_limit = atoi(optarg);
2084             if (s->burst_limit < 1) {
2085                 fatal(0, "--burst-limit argument must be at least 1");
2086             }
2087             break;
2088
2089         case 'D':
2090             set_detach();
2091             break;
2092
2093         case 'P':
2094             set_pidfile(optarg);
2095             break;
2096
2097         case 'f':
2098             ignore_existing_pidfile();
2099             break;
2100
2101         case 'l':
2102             if (s->n_listeners >= MAX_MGMT) {
2103                 fatal(0, "-l or --listen may be specified at most %d times",
2104                       MAX_MGMT);
2105             }
2106             s->listener_names[s->n_listeners++] = optarg;
2107             break;
2108
2109         case 'm':
2110             if (s->monitor_name) {
2111                 fatal(0, "-m or --monitor may only be specified once");
2112             }
2113             s->monitor_name = optarg;
2114             break;
2115
2116         case 'h':
2117             usage();
2118
2119         case 'V':
2120             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
2121             exit(EXIT_SUCCESS);
2122
2123         case 'v':
2124             vlog_set_verbosity(optarg);
2125             break;
2126
2127         VCONN_SSL_OPTION_HANDLERS
2128
2129         case '?':
2130             exit(EXIT_FAILURE);
2131
2132         default:
2133             abort();
2134         }
2135     }
2136     free(short_options);
2137
2138     argc -= optind;
2139     argv += optind;
2140     if (argc < 1 || argc > 2) {
2141         fatal(0, "need one or two non-option arguments; use --help for usage");
2142     }
2143
2144     /* Local and remote vconns. */
2145     s->nl_name = argv[0];
2146     if (strncmp(s->nl_name, "nl:", 3)
2147         || strlen(s->nl_name) < 4
2148         || s->nl_name[strspn(s->nl_name + 3, "0123456789") + 3]) {
2149         fatal(0, "%s: argument is not of the form \"nl:DP_IDX\"", s->nl_name);
2150     }
2151     s->of_name = xasprintf("of%s", s->nl_name + 3);
2152     s->controller_name = argc > 1 ? xstrdup(argv[1]) : NULL;
2153
2154     /* Set accept_controller_regex. */
2155     if (!accept_re) {
2156         accept_re = vconn_ssl_is_configured() ? "^ssl:.*" : ".*";
2157     }
2158     retval = regcomp(&s->accept_controller_regex, accept_re,
2159                      REG_NOSUB | REG_EXTENDED);
2160     if (retval) {
2161         size_t length = regerror(retval, &s->accept_controller_regex, NULL, 0);
2162         char *buffer = xmalloc(length);
2163         regerror(retval, &s->accept_controller_regex, buffer, length);
2164         fatal(0, "%s: %s", accept_re, buffer);
2165     }
2166     s->accept_controller_re = accept_re;
2167
2168     /* Mode of operation. */
2169     s->discovery = s->controller_name == NULL;
2170     if (s->discovery) {
2171         s->in_band = true;
2172     } else {
2173         enum netdev_flags flags;
2174         struct netdev *netdev;
2175
2176         retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
2177         if (retval) {
2178             fatal(retval, "Could not open %s device", s->of_name);
2179         }
2180
2181         retval = netdev_get_flags(netdev, &flags);
2182         if (retval) {
2183             fatal(retval, "Could not get flags for %s device", s->of_name);
2184         }
2185
2186         s->in_band = (flags & NETDEV_UP) != 0;
2187         if (s->in_band && netdev_get_in6(netdev, NULL)) {
2188             VLOG_WARN("Ignoring IPv6 address on %s device: IPv6 not supported",
2189                       s->of_name);
2190         }
2191
2192         netdev_close(netdev);
2193     }
2194
2195     /* Rate limiting. */
2196     if (s->rate_limit) {
2197         if (s->rate_limit < 100) {
2198             VLOG_WARN("Rate limit set to unusually low value %d",
2199                       s->rate_limit);
2200         }
2201         if (!s->burst_limit) {
2202             s->burst_limit = s->rate_limit / 4;
2203         }
2204         s->burst_limit = MAX(s->burst_limit, 1);
2205         s->burst_limit = MIN(s->burst_limit, INT_MAX / 1000);
2206     }
2207 }
2208
2209 static void
2210 usage(void)
2211 {
2212     printf("%s: secure channel, a relay for OpenFlow messages.\n"
2213            "usage: %s [OPTIONS] nl:DP_IDX [CONTROLLER]\n"
2214            "where nl:DP_IDX is a datapath that has been added with dpctl.\n"
2215            "CONTROLLER is an active OpenFlow connection method; if it is\n"
2216            "omitted, then secchan performs controller discovery.\n",
2217            program_name, program_name);
2218     vconn_usage(true, true);
2219     printf("\nController discovery options:\n"
2220            "  --accept-vconn=REGEX    accept matching discovered controllers\n"
2221            "  --no-resolv-conf        do not update /etc/resolv.conf\n"
2222            "\nNetworking options:\n"
2223            "  -F, --fail=open|closed  when controller connection fails:\n"
2224            "                            closed: drop all packets\n"
2225            "                            open (default): act as learning switch\n"
2226            "  --inactivity-probe=SECS time between inactivity probes\n"
2227            "  --max-idle=SECS         max idle for flows set up by secchan\n"
2228            "  --max-backoff=SECS      max time between controller connection\n"
2229            "                          attempts (default: 15 seconds)\n"
2230            "  -l, --listen=METHOD     allow management connections on METHOD\n"
2231            "                          (a passive OpenFlow connection method)\n"
2232            "  -m, --monitor=METHOD    copy traffic to/from kernel to METHOD\n"
2233            "                          (a passive OpenFlow connection method)\n"
2234            "\nRate-limiting of \"packet-in\" messages to the controller:\n"
2235            "  --rate-limit[=PACKETS]  max rate, in packets/s (default: 1000)\n"
2236            "  --burst-limit=BURST     limit on packet credit for idle time\n"
2237            "\nOther options:\n"
2238            "  -D, --detach            run in background as daemon\n"
2239            "  -P, --pidfile[=FILE]    create pidfile (default: %s/secchan.pid)\n"
2240            "  -f, --force             with -P, start even if already running\n"
2241            "  -v, --verbose=MODULE[:FACILITY[:LEVEL]]  set logging levels\n"
2242            "  -v, --verbose           set maximum verbosity level\n"
2243            "  -h, --help              display this help message\n"
2244            "  -V, --version           display version information\n",
2245            RUNDIR);
2246     exit(EXIT_SUCCESS);
2247 }