Make pkidir, rundir, logdir modifiable from "configure" command line.
[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 "command-line.h"
49 #include "compiler.h"
50 #include "daemon.h"
51 #include "dhcp-client.h"
52 #include "dhcp.h"
53 #include "dynamic-string.h"
54 #include "fault.h"
55 #include "flow.h"
56 #include "learning-switch.h"
57 #include "list.h"
58 #include "mac-learning.h"
59 #include "netdev.h"
60 #include "nicira-ext.h"
61 #include "ofpbuf.h"
62 #include "openflow.h"
63 #include "packets.h"
64 #include "poll-loop.h"
65 #include "port-array.h"
66 #include "rconn.h"
67 #include "stp.h"
68 #include "timeval.h"
69 #include "util.h"
70 #include "vconn-ssl.h"
71 #include "vconn.h"
72 #include "vlog-socket.h"
73 #include "xtoxll.h"
74
75 #include "vlog.h"
76 #define THIS_MODULE VLM_secchan
77
78 /* Behavior when the connection to the controller fails. */
79 enum fail_mode {
80     FAIL_OPEN,                  /* Act as learning switch. */
81     FAIL_CLOSED                 /* Drop all packets. */
82 };
83
84 /* Maximum number of management connection listeners. */
85 #define MAX_MGMT 8
86
87 /* Settings that may be configured by the user. */
88 struct settings {
89     /* Overall mode of operation. */
90     bool discovery;           /* Discover the controller automatically? */
91     bool in_band;             /* Connect to controller in-band? */
92
93     /* Related vconns and network devices. */
94     const char *dp_name;        /* Local datapath. */
95     const char *controller_name; /* Controller (if not discovery mode). */
96     const char *listener_names[MAX_MGMT]; /* Listen for mgmt connections. */
97     size_t n_listeners;          /* Number of mgmt connection listeners. */
98     const char *monitor_name;   /* Listen for traffic monitor connections. */
99
100     /* Failure behavior. */
101     enum fail_mode fail_mode; /* Act as learning switch if no controller? */
102     int max_idle;             /* Idle time for flows in fail-open mode. */
103     int probe_interval;       /* # seconds idle before sending echo request. */
104     int max_backoff;          /* Max # seconds between connection attempts. */
105
106     /* Packet-in rate-limiting. */
107     int rate_limit;           /* Tokens added to bucket per second. */
108     int burst_limit;          /* Maximum number token bucket size. */
109
110     /* Discovery behavior. */
111     regex_t accept_controller_regex;  /* Controller vconns to accept. */
112     const char *accept_controller_re; /* String version of regex. */
113     bool update_resolv_conf;          /* Update /etc/resolv.conf? */
114
115     /* Spanning tree protocol. */
116     bool enable_stp;
117 };
118
119 struct half {
120     struct rconn *rconn;
121     struct ofpbuf *rxbuf;
122     int n_txq;                  /* No. of packets queued for tx on 'rconn'. */
123 };
124
125 struct relay {
126     struct list node;
127
128 #define HALF_LOCAL 0
129 #define HALF_REMOTE 1
130     struct half halves[2];
131
132     bool is_mgmt_conn;
133 };
134
135 struct hook {
136     bool (*packet_cb[2])(struct relay *, void *aux);
137     void (*periodic_cb)(void *aux);
138     void (*wait_cb)(void *aux);
139     void *aux;
140 };
141
142 static struct vlog_rate_limit vrl = VLOG_RATE_LIMIT_INIT(60, 60);
143
144 static void parse_options(int argc, char *argv[], struct settings *);
145 static void usage(void) NO_RETURN;
146
147 static struct pvconn *open_passive_vconn(const char *name);
148 static struct vconn *accept_vconn(struct pvconn *pvconn);
149
150 static struct relay *relay_create(struct rconn *local, struct rconn *remote,
151                                   bool is_mgmt_conn);
152 static struct relay *relay_accept(const struct settings *, struct pvconn *);
153 static void relay_run(struct relay *, const struct hook[], size_t n_hooks);
154 static void relay_wait(struct relay *);
155 static void relay_destroy(struct relay *);
156
157 static struct hook make_hook(bool (*local_packet_cb)(struct relay *, void *),
158                              bool (*remote_packet_cb)(struct relay *, void *),
159                              void (*periodic_cb)(void *),
160                              void (*wait_cb)(void *),
161                              void *aux);
162 static struct ofp_packet_in *get_ofp_packet_in(struct relay *);
163 static bool get_ofp_packet_eth_header(struct relay *, struct ofp_packet_in **,
164                                       struct eth_header **);
165 static void get_ofp_packet_payload(struct ofp_packet_in *, struct ofpbuf *);
166
167 struct switch_status;
168 struct status_reply;
169 static struct hook switch_status_hook_create(const struct settings *,
170                                              struct switch_status **);
171 static void switch_status_register_category(struct switch_status *,
172                                             const char *category,
173                                             void (*cb)(struct status_reply *,
174                                                        void *aux),
175                                             void *aux);
176 static void status_reply_put(struct status_reply *, const char *, ...)
177     PRINTF_FORMAT(2, 3);
178
179 static void rconn_status_cb(struct status_reply *, void *rconn_);
180
181 struct port_watcher;
182 static struct discovery *discovery_init(const struct settings *,
183                                         struct port_watcher *,
184                                         struct switch_status *);
185 static void discovery_question_connectivity(struct discovery *);
186 static bool discovery_run(struct discovery *, char **controller_name);
187 static void discovery_wait(struct discovery *);
188
189 static struct hook in_band_hook_create(const struct settings *,
190                                        struct switch_status *,
191                                        struct port_watcher *,
192                                        struct rconn *remote);
193
194 static struct hook port_watcher_create(struct rconn *local,
195                                        struct rconn *remote,
196                                        struct port_watcher **);
197 static uint32_t port_watcher_get_config(const struct port_watcher *,
198                                         uint16_t port_no);
199 static const char *port_watcher_get_name(const struct port_watcher *,
200                                          uint16_t port_no) UNUSED;
201 static const uint8_t *port_watcher_get_hwaddr(const struct port_watcher *,
202                                               uint16_t port_no);
203 static void port_watcher_set_flags(struct port_watcher *, uint16_t port_no, 
204                                    uint32_t config, uint32_t c_mask,
205                                    uint32_t state, uint32_t s_mask);
206
207 #ifdef SUPPORT_SNAT
208 static struct hook snat_hook_create(struct port_watcher *pw);
209 #endif
210
211 static struct hook stp_hook_create(const struct settings *,
212                                    struct port_watcher *,
213                                    struct rconn *local, struct rconn *remote);
214
215 static struct hook fail_open_hook_create(const struct settings *,
216                                          struct switch_status *,
217                                          struct rconn *local,
218                                          struct rconn *remote);
219 static struct hook rate_limit_hook_create(const struct settings *,
220                                           struct switch_status *,
221                                           struct rconn *local,
222                                           struct rconn *remote);
223
224
225 static void modify_dhcp_request(struct dhcp_msg *, void *aux);
226 static bool validate_dhcp_offer(const struct dhcp_msg *, void *aux);
227
228 int
229 main(int argc, char *argv[])
230 {
231     struct settings s;
232
233     struct list relays = LIST_INITIALIZER(&relays);
234
235     struct hook hooks[8];
236     size_t n_hooks = 0;
237
238     struct pvconn *monitor;
239
240     struct pvconn *listeners[MAX_MGMT];
241     size_t n_listeners;
242
243     struct rconn *local_rconn, *remote_rconn;
244     struct relay *controller_relay;
245     struct discovery *discovery;
246     struct switch_status *switch_status;
247     struct port_watcher *pw;
248     int i;
249     int retval;
250
251     set_program_name(argv[0]);
252     register_fault_handlers();
253     time_init();
254     vlog_init();
255     parse_options(argc, argv, &s);
256     signal(SIGPIPE, SIG_IGN);
257
258     /* Start listening for management and monitoring connections. */
259     n_listeners = 0;
260     for (i = 0; i < s.n_listeners; i++) {
261         listeners[n_listeners++] = open_passive_vconn(s.listener_names[i]);
262     }
263     monitor = s.monitor_name ? open_passive_vconn(s.monitor_name) : NULL;
264
265     /* Initialize switch status hook. */
266     hooks[n_hooks++] = switch_status_hook_create(&s, &switch_status);
267
268     /* Start listening for vlogconf requests. */
269     retval = vlog_server_listen(NULL, NULL);
270     if (retval) {
271         ofp_fatal(retval, "Could not listen for vlog connections");
272     }
273
274     die_if_already_running();
275     daemonize();
276
277     VLOG_WARN("OpenFlow reference implementation version %s", VERSION);
278     VLOG_WARN("OpenFlow protocol version 0x%02x", OFP_VERSION);
279
280     /* Connect to datapath. */
281     local_rconn = rconn_create(0, s.max_backoff);
282     rconn_connect(local_rconn, s.dp_name);
283     switch_status_register_category(switch_status, "local",
284                                     rconn_status_cb, local_rconn);
285
286     /* Connect to controller. */
287     remote_rconn = rconn_create(s.probe_interval, s.max_backoff);
288     if (s.controller_name) {
289         retval = rconn_connect(remote_rconn, s.controller_name);
290         if (retval == EAFNOSUPPORT) {
291             ofp_fatal(0, "No support for %s vconn", s.controller_name);
292         }
293     }
294     switch_status_register_category(switch_status, "remote",
295                                     rconn_status_cb, remote_rconn);
296
297     /* Start relaying. */
298     controller_relay = relay_create(local_rconn, remote_rconn, false);
299     list_push_back(&relays, &controller_relay->node);
300
301     /* Set up hooks. */
302     hooks[n_hooks++] = port_watcher_create(local_rconn, remote_rconn, &pw);
303     discovery = s.discovery ? discovery_init(&s, pw, switch_status) : NULL;
304 #ifdef SUPPORT_SNAT
305     hooks[n_hooks++] = snat_hook_create(pw);
306 #endif
307     if (s.enable_stp) {
308         hooks[n_hooks++] = stp_hook_create(&s, pw, local_rconn, remote_rconn);
309     }
310     if (s.in_band) {
311         hooks[n_hooks++] = in_band_hook_create(&s, switch_status, pw,
312                                                remote_rconn);
313     }
314     if (s.fail_mode == FAIL_OPEN) {
315         hooks[n_hooks++] = fail_open_hook_create(&s, switch_status,
316                                                  local_rconn, remote_rconn);
317     }
318     if (s.rate_limit) {
319         hooks[n_hooks++] = rate_limit_hook_create(&s, switch_status,
320                                                   local_rconn, remote_rconn);
321     }
322     assert(n_hooks <= ARRAY_SIZE(hooks));
323
324     for (;;) {
325         struct relay *r, *n;
326         size_t i;
327
328         /* Do work. */
329         LIST_FOR_EACH_SAFE (r, n, struct relay, node, &relays) {
330             relay_run(r, hooks, n_hooks);
331         }
332         for (i = 0; i < n_listeners; i++) {
333             for (;;) {
334                 struct relay *r = relay_accept(&s, listeners[i]);
335                 if (!r) {
336                     break;
337                 }
338                 list_push_back(&relays, &r->node);
339             }
340         }
341         if (monitor) {
342             struct vconn *new = accept_vconn(monitor);
343             if (new) {
344                 rconn_add_monitor(local_rconn, new);
345             }
346         }
347         for (i = 0; i < n_hooks; i++) {
348             if (hooks[i].periodic_cb) {
349                 hooks[i].periodic_cb(hooks[i].aux);
350             }
351         }
352         if (s.discovery) {
353             char *controller_name;
354             if (rconn_is_connectivity_questionable(remote_rconn)) {
355                 discovery_question_connectivity(discovery);
356             }
357             if (discovery_run(discovery, &controller_name)) {
358                 if (controller_name) {
359                     rconn_connect(remote_rconn, controller_name);
360                 } else {
361                     rconn_disconnect(remote_rconn);
362                 }
363             }
364         }
365
366         /* Wait for something to happen. */
367         LIST_FOR_EACH (r, struct relay, node, &relays) {
368             relay_wait(r);
369         }
370         for (i = 0; i < n_listeners; i++) {
371             pvconn_wait(listeners[i]);
372         }
373         if (monitor) {
374             pvconn_wait(monitor);
375         }
376         for (i = 0; i < n_hooks; i++) {
377             if (hooks[i].wait_cb) {
378                 hooks[i].wait_cb(hooks[i].aux);
379             }
380         }
381         if (discovery) {
382             discovery_wait(discovery);
383         }
384         poll_block();
385     }
386
387     return 0;
388 }
389
390 static struct pvconn *
391 open_passive_vconn(const char *name)
392 {
393     struct pvconn *pvconn;
394     int retval;
395
396     retval = pvconn_open(name, &pvconn);
397     if (retval && retval != EAGAIN) {
398         ofp_fatal(retval, "opening %s", name);
399     }
400     return pvconn;
401 }
402
403 static struct vconn *
404 accept_vconn(struct pvconn *pvconn)
405 {
406     struct vconn *new;
407     int retval;
408
409     retval = pvconn_accept(pvconn, OFP_VERSION, &new);
410     if (retval && retval != EAGAIN) {
411         VLOG_WARN_RL(&vrl, "accept failed (%s)", strerror(retval));
412     }
413     return new;
414 }
415
416 static struct hook
417 make_hook(bool (*local_packet_cb)(struct relay *, void *aux),
418           bool (*remote_packet_cb)(struct relay *, void *aux),
419           void (*periodic_cb)(void *aux),
420           void (*wait_cb)(void *aux),
421           void *aux)
422 {
423     struct hook h;
424     h.packet_cb[HALF_LOCAL] = local_packet_cb;
425     h.packet_cb[HALF_REMOTE] = remote_packet_cb;
426     h.periodic_cb = periodic_cb;
427     h.wait_cb = wait_cb;
428     h.aux = aux;
429     return h;
430 }
431
432 static struct ofp_packet_in *
433 get_ofp_packet_in(struct relay *r)
434 {
435     struct ofpbuf *msg = r->halves[HALF_LOCAL].rxbuf;
436     struct ofp_header *oh = msg->data;
437     if (oh->type == OFPT_PACKET_IN) {
438         if (msg->size >= offsetof (struct ofp_packet_in, data)) {
439             return msg->data;
440         } else {
441             VLOG_WARN("packet too short (%zu bytes) for packet_in",
442                       msg->size);
443         }
444     }
445     return NULL;
446 }
447
448 static bool
449 get_ofp_packet_eth_header(struct relay *r, struct ofp_packet_in **opip,
450                           struct eth_header **ethp)
451 {
452     const int min_len = offsetof(struct ofp_packet_in, data) + ETH_HEADER_LEN;
453     struct ofp_packet_in *opi = get_ofp_packet_in(r);
454     if (opi && ntohs(opi->header.length) >= min_len) {
455         *opip = opi;
456         *ethp = (void *) opi->data;
457         return true;
458     }
459     return false;
460 }
461
462 \f
463 /* OpenFlow message relaying. */
464
465 static struct relay *
466 relay_accept(const struct settings *s, struct pvconn *pvconn)
467 {
468     struct vconn *new_remote, *new_local;
469     struct rconn *r1, *r2;
470     char *vconn_name;
471     int nl_index;
472     int retval;
473
474     new_remote = accept_vconn(pvconn);
475     if (!new_remote) {
476         return NULL;
477     }
478
479     if (sscanf(s->dp_name, "nl:%d", &nl_index) == 1) {
480         /* nl:123 or nl:123:1 opens a netlink connection to local datapath 123.
481          * nl:123:0 opens a netlink connection to local datapath 123 without
482          * obtaining a subscription for ofp_packet_in or ofp_flow_expired
483          * messages.  That's what we want here; management connections should
484          * not receive those messages, at least by default. */
485         vconn_name = xasprintf("nl:%d:0", nl_index);
486     } else {
487         /* We don't have a way to specify not to subscribe to those messages
488          * for other transports.  (That's a defect: really this should be in
489          * the OpenFlow protocol, not the Netlink transport). */
490         VLOG_WARN_RL(&vrl, "new management connection will receive "
491                      "asynchronous messages");
492         vconn_name = xstrdup(s->dp_name);
493     }
494
495     retval = vconn_open(vconn_name, OFP_VERSION, &new_local);
496     if (retval) {
497         VLOG_ERR_RL(&vrl, "could not connect to %s (%s)",
498                     vconn_name, strerror(retval));
499         vconn_close(new_remote);
500         free(vconn_name);
501         return NULL;
502     }
503
504     /* Create and return relay. */
505     r1 = rconn_create(0, 0);
506     rconn_connect_unreliably(r1, vconn_name, new_local);
507     free(vconn_name);
508
509     r2 = rconn_create(0, 0);
510     rconn_connect_unreliably(r2, "passive", new_remote);
511
512     return relay_create(r1, r2, true);
513 }
514
515 static struct relay *
516 relay_create(struct rconn *local, struct rconn *remote, bool is_mgmt_conn)
517 {
518     struct relay *r = xcalloc(1, sizeof *r);
519     r->halves[HALF_LOCAL].rconn = local;
520     r->halves[HALF_REMOTE].rconn = remote;
521     r->is_mgmt_conn = is_mgmt_conn;
522     return r;
523 }
524
525 static void
526 relay_run(struct relay *r, const struct hook hooks[], size_t n_hooks)
527 {
528     int iteration;
529     int i;
530
531     for (i = 0; i < 2; i++) {
532         rconn_run(r->halves[i].rconn);
533     }
534
535     /* Limit the number of iterations to prevent other tasks from starving. */
536     for (iteration = 0; iteration < 50; iteration++) {
537         bool progress = false;
538         for (i = 0; i < 2; i++) {
539             struct half *this = &r->halves[i];
540             struct half *peer = &r->halves[!i];
541
542             if (!this->rxbuf) {
543                 this->rxbuf = rconn_recv(this->rconn);
544                 if (this->rxbuf && (i == HALF_REMOTE || !r->is_mgmt_conn)) {
545                     const struct hook *h;
546                     for (h = hooks; h < &hooks[n_hooks]; h++) {
547                         if (h->packet_cb[i] && h->packet_cb[i](r, h->aux)) {
548                             ofpbuf_delete(this->rxbuf);
549                             this->rxbuf = NULL;
550                             progress = true;
551                             break;
552                         }
553                     }
554                 }
555             }
556
557             if (this->rxbuf && !this->n_txq) {
558                 int retval = rconn_send(peer->rconn, this->rxbuf,
559                                         &this->n_txq);
560                 if (retval != EAGAIN) {
561                     if (!retval) {
562                         progress = true;
563                     } else {
564                         ofpbuf_delete(this->rxbuf);
565                     }
566                     this->rxbuf = NULL;
567                 }
568             }
569         }
570         if (!progress) {
571             break;
572         }
573     }
574
575     if (r->is_mgmt_conn) {
576         for (i = 0; i < 2; i++) {
577             struct half *this = &r->halves[i];
578             if (!rconn_is_alive(this->rconn)) {
579                 relay_destroy(r);
580                 return;
581             }
582         }
583     }
584 }
585
586 static void
587 relay_wait(struct relay *r)
588 {
589     int i;
590
591     for (i = 0; i < 2; i++) {
592         struct half *this = &r->halves[i];
593
594         rconn_run_wait(this->rconn);
595         if (!this->rxbuf) {
596             rconn_recv_wait(this->rconn);
597         }
598     }
599 }
600
601 static void
602 relay_destroy(struct relay *r)
603 {
604     int i;
605
606     list_remove(&r->node);
607     for (i = 0; i < 2; i++) {
608         struct half *this = &r->halves[i];
609         rconn_destroy(this->rconn);
610         ofpbuf_delete(this->rxbuf);
611     }
612     free(r);
613 }
614 \f
615 /* Port status watcher. */
616
617 typedef void port_changed_cb_func(uint16_t port_no,
618                                   const struct ofp_phy_port *old,
619                                   const struct ofp_phy_port *new,
620                                   void *aux);
621
622 struct port_watcher_cb {
623     port_changed_cb_func *port_changed;
624     void *aux;
625 };
626
627 typedef void local_port_changed_cb_func(const struct ofp_phy_port *new,
628                                         void *aux);
629
630 struct port_watcher_local_cb {
631     local_port_changed_cb_func *local_port_changed;
632     void *aux;
633 };
634
635 struct port_watcher {
636     struct rconn *local_rconn;
637     struct rconn *remote_rconn;
638     struct port_array ports;
639     time_t last_feature_request;
640     bool got_feature_reply;
641     uint64_t datapath_id;
642     int n_txq;
643     struct port_watcher_cb cbs[2];
644     int n_cbs;
645     struct port_watcher_local_cb local_cbs[4];
646     int n_local_cbs;
647     char local_port_name[OFP_MAX_PORT_NAME_LEN + 1];
648 };
649
650 /* Returns the number of fields that differ from 'a' to 'b'. */
651 static int
652 opp_differs(const struct ofp_phy_port *a, const struct ofp_phy_port *b)
653 {
654     BUILD_ASSERT_DECL(sizeof *a == 48); /* Trips when we add or remove fields. */
655     return ((a->port_no != b->port_no)
656             + (memcmp(a->hw_addr, b->hw_addr, sizeof a->hw_addr) != 0)
657             + (memcmp(a->name, b->name, sizeof a->name) != 0)
658             + (a->config != b->config)
659             + (a->state != b->state)
660             + (a->curr != b->curr)
661             + (a->advertised != b->advertised)
662             + (a->supported != b->supported)
663             + (a->peer != b->peer));
664 }
665
666 static void
667 sanitize_opp(struct ofp_phy_port *opp)
668 {
669     size_t i;
670
671     for (i = 0; i < sizeof opp->name; i++) {
672         char c = opp->name[i];
673         if (c && (c < 0x20 || c > 0x7e)) {
674             opp->name[i] = '.';
675         }
676     }
677     opp->name[sizeof opp->name - 1] = '\0';
678 }
679
680 static void
681 call_port_changed_callbacks(struct port_watcher *pw, int port_no,
682                             const struct ofp_phy_port *old,
683                             const struct ofp_phy_port *new)
684 {
685     int i;
686     for (i = 0; i < pw->n_cbs; i++) {
687         port_changed_cb_func *port_changed = pw->cbs[i].port_changed;
688         (port_changed)(port_no, old, new, pw->cbs[i].aux);
689     }
690 }
691
692 static void
693 get_port_name(const struct ofp_phy_port *port, char *name, size_t name_size)
694 {
695     char *p;
696
697     memcpy(name, port->name, MIN(name_size, sizeof port->name));
698     name[name_size - 1] = '\0';
699     for (p = name; *p != '\0'; p++) {
700         if (*p < 32 || *p > 126) {
701             *p = '.';
702         }
703     }
704 }
705
706 static struct ofp_phy_port *
707 lookup_port(const struct port_watcher *pw, uint16_t port_no)
708 {
709     return port_array_get(&pw->ports, port_no);
710 }
711
712 static void
713 call_local_port_changed_callbacks(struct port_watcher *pw)
714 {
715     char name[OFP_MAX_PORT_NAME_LEN + 1];
716     const struct ofp_phy_port *port;
717     int i;
718
719     /* Pass the local port to the callbacks, if it exists.
720        Pass a null pointer if there is no local port. */
721     port = lookup_port(pw, OFPP_LOCAL);
722
723     /* Log the name of the local port. */
724     if (port) {
725         get_port_name(port, name, sizeof name);
726     } else {
727         name[0] = '\0';
728     }
729     if (strcmp(pw->local_port_name, name)) {
730         if (name[0]) {
731             VLOG_WARN("Identified data path local port as \"%s\".", name);
732         } else {
733             VLOG_WARN("Data path has no local port.");
734         }
735         strcpy(pw->local_port_name, name);
736     }
737
738     /* Invoke callbacks. */
739     for (i = 0; i < pw->n_local_cbs; i++) {
740         local_port_changed_cb_func *cb = pw->local_cbs[i].local_port_changed;
741         (cb)(port, pw->local_cbs[i].aux);
742     }
743 }
744
745 static void
746 update_phy_port(struct port_watcher *pw, struct ofp_phy_port *opp,
747                 uint8_t reason)
748 {
749     struct ofp_phy_port *old;
750     uint16_t port_no;
751
752     port_no = ntohs(opp->port_no);
753     old = lookup_port(pw, port_no);
754
755     if (reason == OFPPR_DELETE && old) {
756         call_port_changed_callbacks(pw, port_no, old, NULL);
757         free(old);
758         port_array_set(&pw->ports, port_no, NULL);
759     } else if (reason == OFPPR_MODIFY || reason == OFPPR_ADD) {
760         if (old) {
761             uint32_t s_mask = htonl(OFPPS_STP_MASK);
762             opp->state = (opp->state & ~s_mask) | (old->state & s_mask);
763         }
764         if (!old || opp_differs(opp, old)) {
765             struct ofp_phy_port new = *opp;
766             sanitize_opp(&new);
767             call_port_changed_callbacks(pw, port_no, old, &new);
768             if (old) {
769                 *old = new;
770             } else {
771                 port_array_set(&pw->ports, port_no, xmemdup(&new, sizeof new));
772             }
773         }
774     }
775 }
776
777 static bool
778 port_watcher_local_packet_cb(struct relay *r, void *pw_)
779 {
780     struct port_watcher *pw = pw_;
781     struct ofpbuf *msg = r->halves[HALF_LOCAL].rxbuf;
782     struct ofp_header *oh = msg->data;
783
784     if (oh->type == OFPT_FEATURES_REPLY
785         && msg->size >= offsetof(struct ofp_switch_features, ports)) {
786         struct ofp_switch_features *osf = msg->data;
787         bool seen[PORT_ARRAY_SIZE];
788         struct ofp_phy_port *p;
789         unsigned int port_no;
790         size_t n_ports;
791         size_t i;
792
793         pw->got_feature_reply = true;
794         if (pw->datapath_id != osf->datapath_id) {
795             pw->datapath_id = osf->datapath_id;
796             VLOG_WARN("Datapath id is %012"PRIx64, ntohll(pw->datapath_id));
797         }
798
799         /* Update each port included in the message. */
800         memset(seen, false, sizeof seen);
801         n_ports = ((msg->size - offsetof(struct ofp_switch_features, ports))
802                    / sizeof *osf->ports);
803         for (i = 0; i < n_ports; i++) {
804             struct ofp_phy_port *opp = &osf->ports[i];
805             update_phy_port(pw, opp, OFPPR_MODIFY);
806             seen[ntohs(opp->port_no)] = true;
807         }
808
809         /* Delete all the ports not included in the message. */
810         for (p = port_array_first(&pw->ports, &port_no); p;
811              p = port_array_next(&pw->ports, &port_no)) {
812             if (!seen[port_no]) {
813                 update_phy_port(pw, p, OFPPR_DELETE);
814             }
815         }
816
817         call_local_port_changed_callbacks(pw);
818     } else if (oh->type == OFPT_PORT_STATUS
819                && msg->size >= sizeof(struct ofp_port_status)) {
820         struct ofp_port_status *ops = msg->data;
821         update_phy_port(pw, &ops->desc, ops->reason);
822         if (ops->desc.port_no == htons(OFPP_LOCAL)) {
823             call_local_port_changed_callbacks(pw);
824         }
825     }
826     return false;
827 }
828
829 static bool
830 port_watcher_remote_packet_cb(struct relay *r, void *pw_)
831 {
832     struct port_watcher *pw = pw_;
833     struct ofpbuf *msg = r->halves[HALF_REMOTE].rxbuf;
834     struct ofp_header *oh = msg->data;
835
836     if (oh->type == OFPT_PORT_MOD
837         && msg->size >= sizeof(struct ofp_port_mod)) {
838         struct ofp_port_mod *opm = msg->data;
839         uint16_t port_no = ntohs(opm->port_no);
840         struct ofp_phy_port *pw_opp = lookup_port(pw, port_no);
841         if (pw_opp->port_no != htons(OFPP_NONE)) {
842             struct ofp_phy_port old = *pw_opp;
843             pw_opp->config = ((pw_opp->config & ~opm->mask)
844                               | (opm->config & opm->mask));
845             call_port_changed_callbacks(pw, port_no, &old, pw_opp);
846             if (pw_opp->port_no == htons(OFPP_LOCAL)) {
847                 call_local_port_changed_callbacks(pw);
848             }
849         }
850     }
851     return false;
852 }
853
854 static void
855 port_watcher_periodic_cb(void *pw_)
856 {
857     struct port_watcher *pw = pw_;
858
859     if (!pw->got_feature_reply
860         && time_now() >= pw->last_feature_request + 5
861         && rconn_is_connected(pw->local_rconn)) {
862         struct ofpbuf *b;
863         make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &b);
864         rconn_send_with_limit(pw->local_rconn, b, &pw->n_txq, 1);
865         pw->last_feature_request = time_now();
866     }
867 }
868
869 static void
870 port_watcher_wait_cb(void *pw_)
871 {
872     struct port_watcher *pw = pw_;
873     if (!pw->got_feature_reply && rconn_is_connected(pw->local_rconn)) {
874         if (pw->last_feature_request != TIME_MIN) {
875             poll_timer_wait(pw->last_feature_request + 5 - time_now());
876         } else {
877             poll_immediate_wake();
878         }
879     }
880 }
881
882 static void
883 put_duplexes(struct ds *ds, const char *name, uint32_t features,
884              uint32_t hd_bit, uint32_t fd_bit)
885 {
886     if (features & (hd_bit | fd_bit)) {
887         ds_put_format(ds, " %s", name);
888         if (features & hd_bit) {
889             ds_put_cstr(ds, "(HD)");
890         }
891         if (features & fd_bit) {
892             ds_put_cstr(ds, "(FD)");
893         }
894     }
895 }
896
897 static void
898 put_features(struct ds *ds, const char *name, uint32_t features)
899 {
900     if (features & (OFPPF_10MB_HD | OFPPF_10MB_FD
901                     | OFPPF_100MB_HD | OFPPF_100MB_FD
902                     | OFPPF_1GB_HD | OFPPF_1GB_FD | OFPPF_10GB_FD)) {
903         ds_put_cstr(ds, name);
904         put_duplexes(ds, "10M", features, OFPPF_10MB_HD, OFPPF_10MB_FD);
905         put_duplexes(ds, "100M", features,
906                      OFPPF_100MB_HD, OFPPF_100MB_FD);
907         put_duplexes(ds, "1G", features, OFPPF_100MB_HD, OFPPF_100MB_FD);
908         if (features & OFPPF_10GB_FD) {
909             ds_put_cstr(ds, " 10G");
910         }
911         if (features & OFPPF_AUTONEG) {
912             ds_put_cstr(ds, " AUTO_NEG");
913         }
914         if (features & OFPPF_PAUSE) {
915             ds_put_cstr(ds, " PAUSE");
916         }
917         if (features & OFPPF_PAUSE_ASYM) {
918             ds_put_cstr(ds, " PAUSE_ASYM");
919         }
920     }
921 }
922
923 static void
924 log_port_status(uint16_t port_no,
925                 const struct ofp_phy_port *old,
926                 const struct ofp_phy_port *new,
927                 void *aux)
928 {
929     if (VLOG_IS_DBG_ENABLED()) {
930         if (old && new && (opp_differs(old, new)
931                            == ((old->config != new->config)
932                                + (old->state != new->state))))
933         {
934             /* Don't care if only state or config changed. */
935         } else if (!new) {
936             if (old) {
937                 VLOG_DBG("Port %d deleted", port_no);
938             }
939         } else {
940             struct ds ds = DS_EMPTY_INITIALIZER;
941             uint32_t curr = ntohl(new->curr);
942             uint32_t supported = ntohl(new->supported);
943             ds_put_format(&ds, "\"%s\", "ETH_ADDR_FMT, new->name,
944                           ETH_ADDR_ARGS(new->hw_addr));
945             if (curr) {
946                 put_features(&ds, ", current", curr);
947             }
948             if (supported) {
949                 put_features(&ds, ", supports", supported);
950             }
951             VLOG_DBG("Port %d %s: %s",
952                      port_no, old ? "changed" : "added", ds_cstr(&ds));
953             ds_destroy(&ds);
954         }
955     }
956 }
957
958 static void
959 port_watcher_register_callback(struct port_watcher *pw,
960                                port_changed_cb_func *port_changed,
961                                void *aux)
962 {
963     assert(pw->n_cbs < ARRAY_SIZE(pw->cbs));
964     pw->cbs[pw->n_cbs].port_changed = port_changed;
965     pw->cbs[pw->n_cbs].aux = aux;
966     pw->n_cbs++;
967 }
968
969 static void
970 port_watcher_register_local_port_callback(struct port_watcher *pw,
971                                           local_port_changed_cb_func *cb,
972                                           void *aux)
973 {
974     assert(pw->n_local_cbs < ARRAY_SIZE(pw->local_cbs));
975     pw->local_cbs[pw->n_local_cbs].local_port_changed = cb;
976     pw->local_cbs[pw->n_local_cbs].aux = aux;
977     pw->n_local_cbs++;
978 }
979
980 static uint32_t
981 port_watcher_get_config(const struct port_watcher *pw, uint16_t port_no)
982 {
983     struct ofp_phy_port *p = lookup_port(pw, port_no);
984     return p ? ntohl(p->config) : 0;
985 }
986
987 static const char *
988 port_watcher_get_name(const struct port_watcher *pw, uint16_t port_no)
989 {
990     struct ofp_phy_port *p = lookup_port(pw, port_no);
991     return p ? (const char *) p->name : NULL;
992 }
993
994 static const uint8_t *
995 port_watcher_get_hwaddr(const struct port_watcher *pw, uint16_t port_no) 
996 {
997     struct ofp_phy_port *p = lookup_port(pw, port_no);
998     return p ? p->hw_addr : NULL;
999 }
1000
1001 static void
1002 port_watcher_set_flags(struct port_watcher *pw, uint16_t port_no, 
1003                        uint32_t config, uint32_t c_mask,
1004                        uint32_t state, uint32_t s_mask)
1005 {
1006     struct ofp_phy_port old;
1007     struct ofp_phy_port *p;
1008     struct ofp_port_mod *opm;
1009     struct ofp_port_status *ops;
1010     struct ofpbuf *b;
1011
1012     p = lookup_port(pw, port_no);
1013     if (!p) {
1014         return;
1015     }
1016
1017     if (!((ntohl(p->state) ^ state) & s_mask) 
1018             && (!((ntohl(p->config) ^ config) & c_mask))) {
1019         return;
1020     }
1021     old = *p;
1022
1023     /* Update our idea of the flags. */
1024     p->config = htonl((ntohl(p->config) & ~c_mask) | (config & c_mask));
1025     p->state = htonl((ntohl(p->state) & ~s_mask) | (state & s_mask));
1026     call_port_changed_callbacks(pw, port_no, &old, p);
1027
1028     /* Change the flags in the datapath. */
1029     opm = make_openflow(sizeof *opm, OFPT_PORT_MOD, &b);
1030     opm->port_no = p->port_no;
1031     memcpy(opm->hw_addr, p->hw_addr, OFP_ETH_ALEN);
1032     opm->config = p->config;
1033     opm->mask = htonl(c_mask);
1034     opm->advertise = htonl(0);
1035     rconn_send(pw->local_rconn, b, NULL);
1036
1037     /* Notify the controller that the flags changed. */
1038     ops = make_openflow(sizeof *ops, OFPT_PORT_STATUS, &b);
1039     ops->reason = OFPPR_MODIFY;
1040     ops->desc = *p;
1041     rconn_send(pw->remote_rconn, b, NULL);
1042 }
1043
1044 static bool
1045 port_watcher_is_ready(const struct port_watcher *pw)
1046 {
1047     return pw->got_feature_reply;
1048 }
1049
1050 static struct hook
1051 port_watcher_create(struct rconn *local_rconn, struct rconn *remote_rconn,
1052                     struct port_watcher **pwp)
1053 {
1054     struct port_watcher *pw;
1055
1056     pw = *pwp = xcalloc(1, sizeof *pw);
1057     pw->local_rconn = local_rconn;
1058     pw->remote_rconn = remote_rconn;
1059     pw->last_feature_request = TIME_MIN;
1060     port_array_init(&pw->ports);
1061     pw->local_port_name[0] = '\0';
1062     port_watcher_register_callback(pw, log_port_status, NULL);
1063     return make_hook(port_watcher_local_packet_cb,
1064                      port_watcher_remote_packet_cb,
1065                      port_watcher_periodic_cb,
1066                      port_watcher_wait_cb, pw);
1067 }
1068 \f
1069 #ifdef SUPPORT_SNAT
1070 struct snat_port_conf {
1071     struct list node;
1072     struct nx_snat_config config;
1073 };
1074
1075 struct snat_data {
1076     struct port_watcher *pw;
1077     struct list port_list;
1078 };
1079
1080
1081 /* Source-NAT configuration monitor. */
1082 #define SNAT_CMD_LEN 1024
1083
1084 /* Commands to configure iptables.  There is no programmatic interface
1085  * to iptables from the kernel, so we're stuck making command-line calls
1086  * in user-space. */
1087 #define SNAT_FLUSH_ALL_CMD "/sbin/iptables -t nat -F"
1088 #define SNAT_FLUSH_CHAIN_CMD "/sbin/iptables -t nat -F of-snat-%s"
1089
1090 #define SNAT_ADD_CHAIN_CMD "/sbin/iptables -t nat -N of-snat-%s"
1091 #define SNAT_CONF_CHAIN_CMD "/sbin/iptables -t nat -A POSTROUTING -o %s -j of-snat-%s"
1092
1093 #define SNAT_ADD_IP_CMD "/sbin/iptables -t nat -A of-snat-%s -j SNAT --to %s-%s"
1094 #define SNAT_ADD_TCP_CMD "/sbin/iptables -t nat -A of-snat-%s -j SNAT -p TCP --to %s-%s:%d-%d"
1095 #define SNAT_ADD_UDP_CMD "/sbin/iptables -t nat -A of-snat-%s -j SNAT -p UDP --to %s-%s:%d-%d"
1096
1097 #define SNAT_UNSET_CHAIN_CMD "/sbin/iptables -t nat -D POSTROUTING -o %s -j of-snat-%s"
1098 #define SNAT_DEL_CHAIN_CMD "/sbin/iptables -t nat -X of-snat-%s"
1099
1100 static void 
1101 snat_add_rules(const struct nx_snat_config *sc, const uint8_t *dev_name)
1102 {
1103     char command[SNAT_CMD_LEN];
1104     char ip_str_start[16];
1105     char ip_str_end[16];
1106
1107
1108     snprintf(ip_str_start, sizeof ip_str_start, IP_FMT, 
1109             IP_ARGS(&sc->ip_addr_start));
1110     snprintf(ip_str_end, sizeof ip_str_end, IP_FMT, 
1111             IP_ARGS(&sc->ip_addr_end));
1112
1113     /* We always attempt to remove existing entries, so that we know
1114      * there's a pristine state for SNAT on the interface.  We just ignore 
1115      * the results of these calls, since iptables will complain about 
1116      * any non-existent entries. */
1117
1118     /* Flush the chain that does the SNAT. */
1119     snprintf(command, sizeof(command), SNAT_FLUSH_CHAIN_CMD, dev_name);
1120     system(command);
1121
1122     /* We always try to create the a new chain. */
1123     snprintf(command, sizeof(command), SNAT_ADD_CHAIN_CMD, dev_name);
1124     system(command);
1125
1126     /* Disassociate any old SNAT chain from the POSTROUTING chain. */
1127     snprintf(command, sizeof(command), SNAT_UNSET_CHAIN_CMD, dev_name, 
1128             dev_name);
1129     system(command);
1130
1131     /* Associate the new chain with the POSTROUTING hook. */
1132     snprintf(command, sizeof(command), SNAT_CONF_CHAIN_CMD, dev_name, 
1133             dev_name);
1134     if (system(command) != 0) {
1135         VLOG_ERR("SNAT: problem flushing chain for add");
1136         return;
1137     }
1138
1139     /* If configured, restrict TCP source port ranges. */
1140     if ((sc->tcp_start != 0) && (sc->tcp_end != 0)) {
1141         snprintf(command, sizeof(command), SNAT_ADD_TCP_CMD, 
1142                 dev_name, ip_str_start, ip_str_end,
1143                 ntohs(sc->tcp_start), ntohs(sc->tcp_end));
1144         if (system(command) != 0) {
1145             VLOG_ERR("SNAT: problem adding TCP rule");
1146             return;
1147         }
1148     }
1149
1150     /* If configured, restrict UDP source port ranges. */
1151     if ((sc->udp_start != 0) && (sc->udp_end != 0)) {
1152         snprintf(command, sizeof(command), SNAT_ADD_UDP_CMD, 
1153                 dev_name, ip_str_start, ip_str_end,
1154                 ntohs(sc->udp_start), ntohs(sc->udp_end));
1155         if (system(command) != 0) {
1156             VLOG_ERR("SNAT: problem adding UDP rule");
1157             return;
1158         }
1159     }
1160
1161     /* Add a rule that covers all IP traffic that would not be covered
1162      * by the prior TCP or UDP ranges. */
1163     snprintf(command, sizeof(command), SNAT_ADD_IP_CMD, 
1164             dev_name, ip_str_start, ip_str_end);
1165     if (system(command) != 0) {
1166         VLOG_ERR("SNAT: problem adding base rule");
1167         return;
1168     }
1169 }
1170
1171 static void 
1172 snat_del_rules(const uint8_t *dev_name)
1173 {
1174     char command[SNAT_CMD_LEN];
1175
1176     /* Flush the chain that does the SNAT. */
1177     snprintf(command, sizeof(command), SNAT_FLUSH_CHAIN_CMD, dev_name);
1178     if (system(command) != 0) {
1179         VLOG_ERR("SNAT: problem flushing chain for deletion");
1180         return;
1181     }
1182
1183     /* Disassociate the SNAT chain from the POSTROUTING chain. */
1184     snprintf(command, sizeof(command), SNAT_UNSET_CHAIN_CMD, dev_name, 
1185             dev_name);
1186     if (system(command) != 0) {
1187         VLOG_ERR("SNAT: problem unsetting chain");
1188         return;
1189     }
1190
1191     /* Now we can finally delete our SNAT chain. */
1192     snprintf(command, sizeof(command), SNAT_DEL_CHAIN_CMD, dev_name);
1193     if (system(command) != 0) {
1194         VLOG_ERR("SNAT: problem deleting chain");
1195         return;
1196     }
1197 }
1198
1199 static void 
1200 snat_config(const struct nx_snat_config *sc, struct snat_data *snat)
1201 {
1202     struct snat_port_conf *c, *spc=NULL;
1203     const uint8_t *netdev_name;
1204
1205     netdev_name = (const uint8_t *) port_watcher_get_name(snat->pw,
1206                                                           ntohs(sc->port));
1207     if (!netdev_name) {
1208         return;
1209     }
1210
1211     LIST_FOR_EACH(c, struct snat_port_conf, node, &snat->port_list) {
1212         if (c->config.port == sc->port) {
1213             spc = c;
1214             break;
1215         }
1216     }
1217
1218     if (sc->command == NXSC_ADD) {
1219         if (!spc) {
1220             spc = xmalloc(sizeof(*c));
1221             if (!spc) {
1222                 VLOG_ERR("SNAT: no memory for new entry");
1223                 return;
1224             }
1225             list_push_back(&snat->port_list, &spc->node);
1226         }
1227         memcpy(&spc->config, sc, sizeof(spc->config));
1228         snat_add_rules(sc, netdev_name);
1229     } else if (spc) {
1230         snat_del_rules(netdev_name);
1231         list_remove(&spc->node);
1232     }
1233 }
1234
1235 static bool
1236 snat_remote_packet_cb(struct relay *r, void *snat_)
1237 {
1238     struct snat_data *snat = snat_;
1239     struct ofpbuf *msg = r->halves[HALF_REMOTE].rxbuf;
1240     struct nicira_header *request = msg->data;
1241     struct nx_act_config *nac = msg->data;
1242     int n_configs, i;
1243
1244
1245     if (msg->size < sizeof(struct nx_act_config)) {
1246         return false;
1247     }
1248     request = msg->data;
1249     if (request->header.type != OFPT_VENDOR
1250         || request->vendor != htonl(NX_VENDOR_ID)
1251         || request->subtype != htonl(NXT_ACT_SET_CONFIG)) {
1252         return false;
1253     }
1254
1255     /* We're only interested in attempts to configure SNAT */
1256     if (nac->type != htons(NXAST_SNAT)) {
1257         return false;
1258     }
1259
1260     n_configs = (msg->size - sizeof *nac) / sizeof *nac->snat;
1261     for (i=0; i<n_configs; i++) {
1262         snat_config(&nac->snat[i], snat);
1263     }
1264
1265     return false;
1266 }
1267
1268 static void
1269 snat_port_changed_cb(uint16_t port_no,
1270                     const struct ofp_phy_port *old,
1271                     const struct ofp_phy_port *new,
1272                     void *snat_)
1273 {
1274     struct snat_data *snat = snat_;
1275     struct snat_port_conf *c;
1276
1277     /* We're only interested in ports that went away */
1278     if (old && !new) {
1279         return;
1280     }
1281
1282     LIST_FOR_EACH(c, struct snat_port_conf, node, &snat->port_list) {
1283         if (c->config.port == old->port_no) {
1284             snat_del_rules(old->name);
1285             list_remove(&c->node);
1286             return;
1287         }
1288     }
1289 }
1290
1291 static struct hook
1292 snat_hook_create(struct port_watcher *pw)
1293 {
1294     int ret;
1295     struct snat_data *snat;
1296
1297     ret = system(SNAT_FLUSH_ALL_CMD); 
1298     if (ret != 0) {
1299         VLOG_ERR("SNAT: problem flushing tables");
1300     }
1301
1302     snat = xcalloc(1, sizeof *snat);
1303     snat->pw = pw;
1304     list_init(&snat->port_list);
1305
1306     port_watcher_register_callback(pw, snat_port_changed_cb, snat);
1307     return make_hook(NULL, snat_remote_packet_cb, NULL, NULL, snat);
1308 }
1309 #endif /* SUPPORT_SNAT */
1310 \f
1311 /* Spanning tree protocol. */
1312
1313 /* Extra time, in seconds, at boot before going into fail-open, to give the
1314  * spanning tree protocol time to figure out the network layout. */
1315 #define STP_EXTRA_BOOT_TIME 30
1316
1317 struct stp_data {
1318     struct stp *stp;
1319     struct port_watcher *pw;
1320     struct rconn *local_rconn;
1321     struct rconn *remote_rconn;
1322     long long int last_tick_256ths;
1323     int n_txq;
1324 };
1325
1326 static bool
1327 stp_local_packet_cb(struct relay *r, void *stp_)
1328 {
1329     struct ofpbuf *msg = r->halves[HALF_LOCAL].rxbuf;
1330     struct ofp_header *oh;
1331     struct stp_data *stp = stp_;
1332     struct ofp_packet_in *opi;
1333     struct eth_header *eth;
1334     struct llc_header *llc;
1335     struct ofpbuf payload;
1336     uint16_t port_no;
1337     struct flow flow;
1338
1339     oh = msg->data;
1340     if (oh->type == OFPT_FEATURES_REPLY
1341         && msg->size >= offsetof(struct ofp_switch_features, ports)) {
1342         struct ofp_switch_features *osf = msg->data;
1343         osf->capabilities |= htonl(OFPC_STP);
1344         return false;
1345     }
1346
1347     if (!get_ofp_packet_eth_header(r, &opi, &eth)
1348         || !eth_addr_equals(eth->eth_dst, stp_eth_addr)) {
1349         return false;
1350     }
1351
1352     port_no = ntohs(opi->in_port);
1353     if (port_no >= STP_MAX_PORTS) {
1354         /* STP only supports 255 ports. */
1355         return false;
1356     }
1357     if (port_watcher_get_config(stp->pw, port_no) & OFPPC_NO_STP) {
1358         /* We're not doing STP on this port. */
1359         return false;
1360     }
1361
1362     if (opi->reason == OFPR_ACTION) {
1363         /* The controller set up a flow for this, so we won't intercept it. */
1364         return false;
1365     }
1366
1367     get_ofp_packet_payload(opi, &payload);
1368     flow_extract(&payload, port_no, &flow);
1369     if (flow.dl_type != htons(OFP_DL_TYPE_NOT_ETH_TYPE)) {
1370         VLOG_DBG("non-LLC frame received on STP multicast address");
1371         return false;
1372     }
1373     llc = ofpbuf_at_assert(&payload, sizeof *eth, sizeof *llc);
1374     if (llc->llc_dsap != STP_LLC_DSAP) {
1375         VLOG_DBG("bad DSAP 0x%02"PRIx8" received on STP multicast address",
1376                  llc->llc_dsap);
1377         return false;
1378     }
1379
1380     /* Trim off padding on payload. */
1381     if (payload.size > ntohs(eth->eth_type) + ETH_HEADER_LEN) {
1382         payload.size = ntohs(eth->eth_type) + ETH_HEADER_LEN;
1383     }
1384     if (ofpbuf_try_pull(&payload, ETH_HEADER_LEN + LLC_HEADER_LEN)) {
1385         struct stp_port *p = stp_get_port(stp->stp, port_no);
1386         stp_received_bpdu(p, payload.data, payload.size);
1387     }
1388
1389     return true;
1390 }
1391
1392 static long long int
1393 time_256ths(void)
1394 {
1395     return time_msec() * 256 / 1000;
1396 }
1397
1398 static void
1399 stp_periodic_cb(void *stp_)
1400 {
1401     struct stp_data *stp = stp_;
1402     long long int now_256ths = time_256ths();
1403     long long int elapsed_256ths = now_256ths - stp->last_tick_256ths;
1404     struct stp_port *p;
1405
1406     if (!port_watcher_is_ready(stp->pw)) {
1407         /* Can't start STP until we know port flags, because port flags can
1408          * disable STP. */
1409         return;
1410     }
1411     if (elapsed_256ths <= 0) {
1412         return;
1413     }
1414
1415     stp_tick(stp->stp, MIN(INT_MAX, elapsed_256ths));
1416     stp->last_tick_256ths = now_256ths;
1417
1418     while (stp_get_changed_port(stp->stp, &p)) {
1419         int port_no = stp_port_no(p);
1420         enum stp_state s_state = stp_port_get_state(p);
1421
1422         if (s_state != STP_DISABLED) {
1423             VLOG_WARN("STP: Port %d entered %s state",
1424                       port_no, stp_state_name(s_state));
1425         }
1426         if (!(port_watcher_get_config(stp->pw, port_no) & OFPPC_NO_STP)) {
1427             uint32_t p_config = 0;
1428             uint32_t p_state;
1429             switch (s_state) {
1430             case STP_LISTENING:
1431                 p_state = OFPPS_STP_LISTEN;
1432                 break;
1433             case STP_LEARNING:
1434                 p_state = OFPPS_STP_LEARN;
1435                 break;
1436             case STP_DISABLED:
1437             case STP_FORWARDING:
1438                 p_state = OFPPS_STP_FORWARD;
1439                 break;
1440             case STP_BLOCKING:
1441                 p_state = OFPPS_STP_BLOCK;
1442                 break;
1443             default:
1444                 VLOG_DBG_RL(&vrl, "STP: Port %d has bad state %x",
1445                             port_no, s_state);
1446                 p_state = OFPPS_STP_FORWARD;
1447                 break;
1448             }
1449             if (!stp_forward_in_state(s_state)) {
1450                 p_config = OFPPC_NO_FLOOD;
1451             }
1452             port_watcher_set_flags(stp->pw, port_no, 
1453                                    p_config, OFPPC_NO_FLOOD,
1454                                    p_state, OFPPS_STP_MASK);
1455         } else {
1456             /* We don't own those flags. */
1457         }
1458     }
1459 }
1460
1461 static void
1462 stp_wait_cb(void *stp_ UNUSED)
1463 {
1464     poll_timer_wait(1000);
1465 }
1466
1467 static void
1468 send_bpdu(const void *bpdu, size_t bpdu_size, int port_no, void *stp_)
1469 {
1470     struct stp_data *stp = stp_;
1471     const uint8_t *port_mac;
1472     struct eth_header *eth;
1473     struct llc_header *llc;
1474     struct ofpbuf pkt, *opo;
1475
1476     port_mac = port_watcher_get_hwaddr(stp->pw, port_no);
1477     if (!port_mac) {
1478         VLOG_WARN_RL(&vrl, "cannot send BPDU on missing port %d", port_no);
1479         return;
1480     }
1481
1482     /* Packet skeleton. */
1483     ofpbuf_init(&pkt, ETH_HEADER_LEN + LLC_HEADER_LEN + bpdu_size);
1484     eth = ofpbuf_put_uninit(&pkt, sizeof *eth);
1485     llc = ofpbuf_put_uninit(&pkt, sizeof *llc);
1486     ofpbuf_put(&pkt, bpdu, bpdu_size);
1487
1488     /* 802.2 header. */
1489     memcpy(eth->eth_dst, stp_eth_addr, ETH_ADDR_LEN);
1490     memcpy(eth->eth_src, port_mac, ETH_ADDR_LEN);
1491     eth->eth_type = htons(pkt.size - ETH_HEADER_LEN);
1492
1493     /* LLC header. */
1494     llc->llc_dsap = STP_LLC_DSAP;
1495     llc->llc_ssap = STP_LLC_SSAP;
1496     llc->llc_cntl = STP_LLC_CNTL;
1497
1498     opo = make_unbuffered_packet_out(&pkt, OFPP_NONE, port_no);
1499     ofpbuf_uninit(&pkt);
1500     rconn_send_with_limit(stp->local_rconn, opo, &stp->n_txq, OFPP_MAX);
1501 }
1502
1503 static bool
1504 stp_is_port_supported(uint16_t port_no)
1505 {
1506     return port_no < STP_MAX_PORTS;
1507 }
1508
1509 static void
1510 stp_port_changed_cb(uint16_t port_no,
1511                     const struct ofp_phy_port *old,
1512                     const struct ofp_phy_port *new,
1513                     void *stp_)
1514 {
1515     struct stp_data *stp = stp_;
1516     struct stp_port *p;
1517
1518     if (!stp_is_port_supported(port_no)) {
1519         return;
1520     }
1521
1522     p = stp_get_port(stp->stp, port_no);
1523     if (!new
1524         || new->config & htonl(OFPPC_NO_STP | OFPPC_PORT_DOWN)
1525         || new->state & htonl(OFPPS_LINK_DOWN)) {
1526         stp_port_disable(p);
1527     } else {
1528         int speed = 0;
1529         stp_port_enable(p);
1530         if (new->curr & (OFPPF_10MB_HD | OFPPF_10MB_FD)) {
1531             speed = 10;
1532         } else if (new->curr & (OFPPF_100MB_HD | OFPPF_100MB_FD)) {
1533             speed = 100;
1534         } else if (new->curr & (OFPPF_1GB_HD | OFPPF_1GB_FD)) {
1535             speed = 1000;
1536         } else if (new->curr & OFPPF_100MB_FD) {
1537             speed = 10000;
1538         }
1539         stp_port_set_speed(p, speed);
1540     }
1541 }
1542
1543 static void
1544 stp_local_port_changed_cb(const struct ofp_phy_port *port, void *stp_)
1545 {
1546     struct stp_data *stp = stp_;
1547     if (port) {
1548         stp_set_bridge_id(stp->stp, eth_addr_to_uint64(port->hw_addr));
1549     }
1550 }
1551
1552 static struct hook
1553 stp_hook_create(const struct settings *s, struct port_watcher *pw,
1554                 struct rconn *local, struct rconn *remote)
1555 {
1556     uint8_t dpid[ETH_ADDR_LEN];
1557     struct stp_data *stp;
1558
1559     stp = xcalloc(1, sizeof *stp);
1560     eth_addr_random(dpid);
1561     stp->stp = stp_create("stp", eth_addr_to_uint64(dpid), send_bpdu, stp);
1562     stp->pw = pw;
1563     stp->local_rconn = local;
1564     stp->remote_rconn = remote;
1565     stp->last_tick_256ths = time_256ths();
1566
1567     port_watcher_register_callback(pw, stp_port_changed_cb, stp);
1568     port_watcher_register_local_port_callback(pw, stp_local_port_changed_cb,
1569                                               stp);
1570     return make_hook(stp_local_packet_cb, NULL,
1571                      stp_periodic_cb, stp_wait_cb, stp);
1572 }
1573 \f
1574 /* In-band control. */
1575
1576 struct in_band_data {
1577     const struct settings *s;
1578     struct mac_learning *ml;
1579     struct netdev *of_device;
1580     struct rconn *controller;
1581     int n_queued;
1582 };
1583
1584 static void
1585 queue_tx(struct rconn *rc, struct in_band_data *in_band, struct ofpbuf *b)
1586 {
1587     rconn_send_with_limit(rc, b, &in_band->n_queued, 10);
1588 }
1589
1590 static const uint8_t *
1591 get_controller_mac(struct in_band_data *in_band)
1592 {
1593     static uint32_t ip, last_nonzero_ip;
1594     static uint8_t mac[ETH_ADDR_LEN], last_nonzero_mac[ETH_ADDR_LEN];
1595     static time_t next_refresh = 0;
1596
1597     uint32_t last_ip = ip;
1598
1599     time_t now = time_now();
1600
1601     ip = rconn_get_ip(in_band->controller);
1602     if (last_ip != ip || !next_refresh || now >= next_refresh) {
1603         bool have_mac;
1604
1605         /* Look up MAC address. */
1606         memset(mac, 0, sizeof mac);
1607         if (ip && in_band->of_device) {
1608             int retval = netdev_arp_lookup(in_band->of_device, ip, mac);
1609             if (retval) {
1610                 VLOG_DBG_RL(&vrl, "cannot look up controller hw address "
1611                             "("IP_FMT"): %s", IP_ARGS(&ip), strerror(retval));
1612             }
1613         }
1614         have_mac = !eth_addr_is_zero(mac);
1615
1616         /* Log changes in IP, MAC addresses. */
1617         if (ip && ip != last_nonzero_ip) {
1618             VLOG_DBG("controller IP address changed from "IP_FMT
1619                      " to "IP_FMT, IP_ARGS(&last_nonzero_ip), IP_ARGS(&ip));
1620             last_nonzero_ip = ip;
1621         }
1622         if (have_mac && memcmp(last_nonzero_mac, mac, ETH_ADDR_LEN)) {
1623             VLOG_DBG("controller MAC address changed from "ETH_ADDR_FMT" to "
1624                      ETH_ADDR_FMT,
1625                      ETH_ADDR_ARGS(last_nonzero_mac), ETH_ADDR_ARGS(mac));
1626             memcpy(last_nonzero_mac, mac, ETH_ADDR_LEN);
1627         }
1628
1629         /* Schedule next refresh.
1630          *
1631          * If we have an IP address but not a MAC address, then refresh
1632          * quickly, since we probably will get a MAC address soon (via ARP).
1633          * Otherwise, we can afford to wait a little while. */
1634         next_refresh = now + (!ip || have_mac ? 10 : 1);
1635     }
1636     return !eth_addr_is_zero(mac) ? mac : NULL;
1637 }
1638
1639 static bool
1640 is_controller_mac(const uint8_t dl_addr[ETH_ADDR_LEN],
1641                   struct in_band_data *in_band)
1642 {
1643     const uint8_t *mac = get_controller_mac(in_band);
1644     return mac && eth_addr_equals(mac, dl_addr);
1645 }
1646
1647 static void
1648 in_band_learn_mac(struct in_band_data *in_band,
1649                   uint16_t in_port, const uint8_t src_mac[ETH_ADDR_LEN])
1650 {
1651     if (mac_learning_learn(in_band->ml, src_mac, in_port)) {
1652         VLOG_DBG_RL(&vrl, "learned that "ETH_ADDR_FMT" is on port %"PRIu16,
1653                     ETH_ADDR_ARGS(src_mac), in_port);
1654     }
1655 }
1656
1657 static bool
1658 in_band_local_packet_cb(struct relay *r, void *in_band_)
1659 {
1660     struct in_band_data *in_band = in_band_;
1661     struct rconn *rc = r->halves[HALF_LOCAL].rconn;
1662     struct ofp_packet_in *opi;
1663     struct eth_header *eth;
1664     struct ofpbuf payload;
1665     struct flow flow;
1666     uint16_t in_port;
1667     int out_port;
1668
1669     if (!get_ofp_packet_eth_header(r, &opi, &eth) || !in_band->of_device) {
1670         return false;
1671     }
1672     in_port = ntohs(opi->in_port);
1673
1674     /* Deal with local stuff. */
1675     if (in_port == OFPP_LOCAL) {
1676         /* Sent by secure channel. */
1677         out_port = mac_learning_lookup(in_band->ml, eth->eth_dst);
1678     } else if (eth_addr_equals(eth->eth_dst,
1679                                netdev_get_etheraddr(in_band->of_device))) {
1680         /* Sent to secure channel. */
1681         out_port = OFPP_LOCAL;
1682         in_band_learn_mac(in_band, in_port, eth->eth_src);
1683     } else if (eth->eth_type == htons(ETH_TYPE_ARP)
1684                && eth_addr_is_broadcast(eth->eth_dst)
1685                && is_controller_mac(eth->eth_src, in_band)) {
1686         /* ARP sent by controller. */
1687         out_port = OFPP_FLOOD;
1688     } else if (is_controller_mac(eth->eth_dst, in_band)
1689                || is_controller_mac(eth->eth_src, in_band)) {
1690         /* Traffic to or from controller.  Switch it by hand. */
1691         in_band_learn_mac(in_band, in_port, eth->eth_src);
1692         out_port = mac_learning_lookup(in_band->ml, eth->eth_dst);
1693     } else {
1694         const uint8_t *controller_mac;
1695         controller_mac = get_controller_mac(in_band);
1696         if (eth->eth_type == htons(ETH_TYPE_ARP)
1697             && eth_addr_is_broadcast(eth->eth_dst)
1698             && is_controller_mac(eth->eth_src, in_band)) {
1699             /* ARP sent by controller. */
1700             out_port = OFPP_FLOOD;
1701         } else if (is_controller_mac(eth->eth_dst, in_band)
1702                    && in_port == mac_learning_lookup(in_band->ml,
1703                                                      controller_mac)) {
1704             /* Drop controller traffic that arrives on the controller port. */
1705             out_port = -1;
1706         } else {
1707             return false;
1708         }
1709     }
1710
1711     get_ofp_packet_payload(opi, &payload);
1712     flow_extract(&payload, in_port, &flow);
1713     if (in_port == out_port) {
1714         /* The input and output port match.  Set up a flow to drop packets. */
1715         queue_tx(rc, in_band, make_add_flow(&flow, ntohl(opi->buffer_id),
1716                                           in_band->s->max_idle, 0));
1717     } else if (out_port != OFPP_FLOOD) {
1718         /* The output port is known, so add a new flow. */
1719         queue_tx(rc, in_band,
1720                  make_add_simple_flow(&flow, ntohl(opi->buffer_id),
1721                                       out_port, in_band->s->max_idle));
1722
1723         /* If the switch didn't buffer the packet, we need to send a copy. */
1724         if (ntohl(opi->buffer_id) == UINT32_MAX) {
1725             queue_tx(rc, in_band,
1726                      make_unbuffered_packet_out(&payload, in_port, out_port));
1727         }
1728     } else {
1729         /* We don't know that MAC.  Send along the packet without setting up a
1730          * flow. */
1731         struct ofpbuf *b;
1732         if (ntohl(opi->buffer_id) == UINT32_MAX) {
1733             b = make_unbuffered_packet_out(&payload, in_port, out_port);
1734         } else {
1735             b = make_buffered_packet_out(ntohl(opi->buffer_id),
1736                                          in_port, out_port);
1737         }
1738         queue_tx(rc, in_band, b);
1739     }
1740     return true;
1741 }
1742
1743 static void
1744 in_band_status_cb(struct status_reply *sr, void *in_band_)
1745 {
1746     struct in_band_data *in_band = in_band_;
1747     struct in_addr local_ip;
1748     uint32_t controller_ip;
1749     const uint8_t *controller_mac;
1750
1751     if (in_band->of_device) {
1752         const uint8_t *mac = netdev_get_etheraddr(in_band->of_device);
1753         if (netdev_get_in4(in_band->of_device, &local_ip)) {
1754             status_reply_put(sr, "local-ip="IP_FMT, IP_ARGS(&local_ip.s_addr));
1755         }
1756         status_reply_put(sr, "local-mac="ETH_ADDR_FMT, ETH_ADDR_ARGS(mac));
1757
1758         controller_ip = rconn_get_ip(in_band->controller);
1759         if (controller_ip) {
1760             status_reply_put(sr, "controller-ip="IP_FMT,
1761                              IP_ARGS(&controller_ip));
1762         }
1763         controller_mac = get_controller_mac(in_band);
1764         if (controller_mac) {
1765             status_reply_put(sr, "controller-mac="ETH_ADDR_FMT,
1766                              ETH_ADDR_ARGS(controller_mac));
1767         }
1768     }
1769 }
1770
1771 static void
1772 get_ofp_packet_payload(struct ofp_packet_in *opi, struct ofpbuf *payload)
1773 {
1774     payload->data = opi->data;
1775     payload->size = ntohs(opi->header.length) - offsetof(struct ofp_packet_in,
1776                                                          data);
1777 }
1778
1779 static void
1780 in_band_local_port_cb(const struct ofp_phy_port *port, void *in_band_)
1781 {
1782     struct in_band_data *in_band = in_band_;
1783     if (port) {
1784         char name[sizeof port->name + 1];
1785         get_port_name(port, name, sizeof name);
1786
1787         if (!in_band->of_device
1788             || strcmp(netdev_get_name(in_band->of_device), name))
1789         {
1790             int error;
1791             netdev_close(in_band->of_device);
1792             error = netdev_open(name, NETDEV_ETH_TYPE_NONE,
1793                                 &in_band->of_device);
1794             if (error) {
1795                 VLOG_ERR("failed to open in-band control network device "
1796                          "\"%s\": %s", name, strerror(errno));
1797             }
1798         }
1799     } else {
1800         netdev_close(in_band->of_device);
1801         in_band->of_device = NULL;
1802     }
1803 }
1804
1805 static struct hook
1806 in_band_hook_create(const struct settings *s, struct switch_status *ss,
1807                     struct port_watcher *pw, struct rconn *remote)
1808 {
1809     struct in_band_data *in_band;
1810
1811     in_band = xcalloc(1, sizeof *in_band);
1812     in_band->s = s;
1813     in_band->ml = mac_learning_create();
1814     in_band->of_device = NULL;
1815     in_band->controller = remote;
1816     switch_status_register_category(ss, "in-band", in_band_status_cb, in_band);
1817     port_watcher_register_local_port_callback(pw, in_band_local_port_cb,
1818                                               in_band);
1819     return make_hook(in_band_local_packet_cb, NULL, NULL, NULL, in_band);
1820 }
1821 \f
1822 /* Fail open support. */
1823
1824 struct fail_open_data {
1825     const struct settings *s;
1826     struct rconn *local_rconn;
1827     struct rconn *remote_rconn;
1828     struct lswitch *lswitch;
1829     int last_disconn_secs;
1830     time_t boot_deadline;
1831 };
1832
1833 /* Causes 'r' to enter or leave fail-open mode, if appropriate. */
1834 static void
1835 fail_open_periodic_cb(void *fail_open_)
1836 {
1837     struct fail_open_data *fail_open = fail_open_;
1838     int disconn_secs;
1839     bool open;
1840
1841     if (time_now() < fail_open->boot_deadline) {
1842         return;
1843     }
1844     disconn_secs = rconn_failure_duration(fail_open->remote_rconn);
1845     open = disconn_secs >= fail_open->s->probe_interval * 3;
1846     if (open != (fail_open->lswitch != NULL)) {
1847         if (!open) {
1848             VLOG_WARN("No longer in fail-open mode");
1849             lswitch_destroy(fail_open->lswitch);
1850             fail_open->lswitch = NULL;
1851         } else {
1852             VLOG_WARN("Could not connect to controller for %d seconds, "
1853                       "failing open", disconn_secs);
1854             fail_open->lswitch = lswitch_create(fail_open->local_rconn, true,
1855                                                 fail_open->s->max_idle);
1856             fail_open->last_disconn_secs = disconn_secs;
1857         }
1858     } else if (open && disconn_secs > fail_open->last_disconn_secs + 60) {
1859         VLOG_WARN("Still in fail-open mode after %d seconds disconnected "
1860                   "from controller", disconn_secs);
1861         fail_open->last_disconn_secs = disconn_secs;
1862     }
1863     if (fail_open->lswitch) {
1864         lswitch_run(fail_open->lswitch, fail_open->local_rconn);
1865     }
1866 }
1867
1868 static void
1869 fail_open_wait_cb(void *fail_open_)
1870 {
1871     struct fail_open_data *fail_open = fail_open_;
1872     if (fail_open->lswitch) {
1873         lswitch_wait(fail_open->lswitch);
1874     }
1875 }
1876
1877 static bool
1878 fail_open_local_packet_cb(struct relay *r, void *fail_open_)
1879 {
1880     struct fail_open_data *fail_open = fail_open_;
1881     if (rconn_is_connected(fail_open->remote_rconn) || !fail_open->lswitch) {
1882         return false;
1883     } else {
1884         lswitch_process_packet(fail_open->lswitch, fail_open->local_rconn,
1885                                r->halves[HALF_LOCAL].rxbuf);
1886         rconn_run(fail_open->local_rconn);
1887         return true;
1888     }
1889 }
1890
1891 static void
1892 fail_open_status_cb(struct status_reply *sr, void *fail_open_)
1893 {
1894     struct fail_open_data *fail_open = fail_open_;
1895     const struct settings *s = fail_open->s;
1896     int trigger_duration = s->probe_interval * 3;
1897     int cur_duration = rconn_failure_duration(fail_open->remote_rconn);
1898
1899     status_reply_put(sr, "trigger-duration=%d", trigger_duration);
1900     status_reply_put(sr, "current-duration=%d", cur_duration);
1901     status_reply_put(sr, "triggered=%s",
1902                      cur_duration >= trigger_duration ? "true" : "false");
1903     status_reply_put(sr, "max-idle=%d", s->max_idle);
1904 }
1905
1906 static struct hook
1907 fail_open_hook_create(const struct settings *s, struct switch_status *ss,
1908                       struct rconn *local_rconn, struct rconn *remote_rconn)
1909 {
1910     struct fail_open_data *fail_open = xmalloc(sizeof *fail_open);
1911     fail_open->s = s;
1912     fail_open->local_rconn = local_rconn;
1913     fail_open->remote_rconn = remote_rconn;
1914     fail_open->lswitch = NULL;
1915     fail_open->boot_deadline = time_now() + s->probe_interval * 3;
1916     if (s->enable_stp) {
1917         fail_open->boot_deadline += STP_EXTRA_BOOT_TIME;
1918     }
1919     switch_status_register_category(ss, "fail-open",
1920                                     fail_open_status_cb, fail_open);
1921     return make_hook(fail_open_local_packet_cb, NULL,
1922                      fail_open_periodic_cb, fail_open_wait_cb, fail_open);
1923 }
1924 \f
1925 struct rate_limiter {
1926     const struct settings *s;
1927     struct rconn *remote_rconn;
1928
1929     /* One queue per physical port. */
1930     struct ofp_queue queues[OFPP_MAX];
1931     int n_queued;               /* Sum over queues[*].n. */
1932     int next_tx_port;           /* Next port to check in round-robin. */
1933
1934     /* Token bucket.
1935      *
1936      * It costs 1000 tokens to send a single packet_in message.  A single token
1937      * per message would be more straightforward, but this choice lets us avoid
1938      * round-off error in refill_bucket()'s calculation of how many tokens to
1939      * add to the bucket, since no division step is needed. */
1940     long long int last_fill;    /* Time at which we last added tokens. */
1941     int tokens;                 /* Current number of tokens. */
1942
1943     /* Transmission queue. */
1944     int n_txq;                  /* No. of packets waiting in rconn for tx. */
1945
1946     /* Statistics reporting. */
1947     unsigned long long n_normal;        /* # txed w/o rate limit queuing. */
1948     unsigned long long n_limited;       /* # queued for rate limiting. */
1949     unsigned long long n_queue_dropped; /* # dropped due to queue overflow. */
1950     unsigned long long n_tx_dropped;    /* # dropped due to tx overflow. */
1951 };
1952
1953 /* Drop a packet from the longest queue in 'rl'. */
1954 static void
1955 drop_packet(struct rate_limiter *rl)
1956 {
1957     struct ofp_queue *longest;  /* Queue currently selected as longest. */
1958     int n_longest;              /* # of queues of same length as 'longest'. */
1959     struct ofp_queue *q;
1960
1961     longest = &rl->queues[0];
1962     n_longest = 1;
1963     for (q = &rl->queues[0]; q < &rl->queues[OFPP_MAX]; q++) {
1964         if (longest->n < q->n) {
1965             longest = q;
1966             n_longest = 1;
1967         } else if (longest->n == q->n) {
1968             n_longest++;
1969
1970             /* Randomly select one of the longest queues, with a uniform
1971              * distribution (Knuth algorithm 3.4.2R). */
1972             if (!random_range(n_longest)) {
1973                 longest = q;
1974             }
1975         }
1976     }
1977
1978     /* FIXME: do we want to pop the tail instead? */
1979     ofpbuf_delete(queue_pop_head(longest));
1980     rl->n_queued--;
1981 }
1982
1983 /* Remove and return the next packet to transmit (in round-robin order). */
1984 static struct ofpbuf *
1985 dequeue_packet(struct rate_limiter *rl)
1986 {
1987     unsigned int i;
1988
1989     for (i = 0; i < OFPP_MAX; i++) {
1990         unsigned int port = (rl->next_tx_port + i) % OFPP_MAX;
1991         struct ofp_queue *q = &rl->queues[port];
1992         if (q->n) {
1993             rl->next_tx_port = (port + 1) % OFPP_MAX;
1994             rl->n_queued--;
1995             return queue_pop_head(q);
1996         }
1997     }
1998     NOT_REACHED();
1999 }
2000
2001 /* Add tokens to the bucket based on elapsed time. */
2002 static void
2003 refill_bucket(struct rate_limiter *rl)
2004 {
2005     const struct settings *s = rl->s;
2006     long long int now = time_msec();
2007     long long int tokens = (now - rl->last_fill) * s->rate_limit + rl->tokens;
2008     if (tokens >= 1000) {
2009         rl->last_fill = now;
2010         rl->tokens = MIN(tokens, s->burst_limit * 1000);
2011     }
2012 }
2013
2014 /* Attempts to remove enough tokens from 'rl' to transmit a packet.  Returns
2015  * true if successful, false otherwise.  (In the latter case no tokens are
2016  * removed.) */
2017 static bool
2018 get_token(struct rate_limiter *rl)
2019 {
2020     if (rl->tokens >= 1000) {
2021         rl->tokens -= 1000;
2022         return true;
2023     } else {
2024         return false;
2025     }
2026 }
2027
2028 static bool
2029 rate_limit_local_packet_cb(struct relay *r, void *rl_)
2030 {
2031     struct rate_limiter *rl = rl_;
2032     const struct settings *s = rl->s;
2033     struct ofp_packet_in *opi;
2034
2035     opi = get_ofp_packet_in(r);
2036     if (!opi) {
2037         return false;
2038     }
2039
2040     if (!rl->n_queued && get_token(rl)) {
2041         /* In the common case where we are not constrained by the rate limit,
2042          * let the packet take the normal path. */
2043         rl->n_normal++;
2044         return false;
2045     } else {
2046         /* Otherwise queue it up for the periodic callback to drain out. */
2047         struct ofpbuf *msg = r->halves[HALF_LOCAL].rxbuf;
2048         int port = ntohs(opi->in_port) % OFPP_MAX;
2049         if (rl->n_queued >= s->burst_limit) {
2050             drop_packet(rl);
2051         }
2052         queue_push_tail(&rl->queues[port], ofpbuf_clone(msg));
2053         rl->n_queued++;
2054         rl->n_limited++;
2055         return true;
2056     }
2057 }
2058
2059 static void
2060 rate_limit_status_cb(struct status_reply *sr, void *rl_)
2061 {
2062     struct rate_limiter *rl = rl_;
2063
2064     status_reply_put(sr, "normal=%llu", rl->n_normal);
2065     status_reply_put(sr, "limited=%llu", rl->n_limited);
2066     status_reply_put(sr, "queue-dropped=%llu", rl->n_queue_dropped);
2067     status_reply_put(sr, "tx-dropped=%llu", rl->n_tx_dropped);
2068 }
2069
2070 static void
2071 rate_limit_periodic_cb(void *rl_)
2072 {
2073     struct rate_limiter *rl = rl_;
2074     int i;
2075
2076     /* Drain some packets out of the bucket if possible, but limit the number
2077      * of iterations to allow other code to get work done too. */
2078     refill_bucket(rl);
2079     for (i = 0; rl->n_queued && get_token(rl) && i < 50; i++) {
2080         /* Use a small, arbitrary limit for the amount of queuing to do here,
2081          * because the TCP connection is responsible for buffering and there is
2082          * no point in trying to transmit faster than the TCP connection can
2083          * handle. */
2084         struct ofpbuf *b = dequeue_packet(rl);
2085         if (rconn_send_with_limit(rl->remote_rconn, b, &rl->n_txq, 10)) {
2086             rl->n_tx_dropped++;
2087         }
2088     }
2089 }
2090
2091 static void
2092 rate_limit_wait_cb(void *rl_)
2093 {
2094     struct rate_limiter *rl = rl_;
2095     if (rl->n_queued) {
2096         if (rl->tokens >= 1000) {
2097             /* We can transmit more packets as soon as we're called again. */
2098             poll_immediate_wake();
2099         } else {
2100             /* We have to wait for the bucket to re-fill.  We could calculate
2101              * the exact amount of time here for increased smoothness. */
2102             poll_timer_wait(TIME_UPDATE_INTERVAL / 2);
2103         }
2104     }
2105 }
2106
2107 static struct hook
2108 rate_limit_hook_create(const struct settings *s, struct switch_status *ss,
2109                        struct rconn *local, struct rconn *remote)
2110 {
2111     struct rate_limiter *rl;
2112     size_t i;
2113
2114     rl = xcalloc(1, sizeof *rl);
2115     rl->s = s;
2116     rl->remote_rconn = remote;
2117     for (i = 0; i < ARRAY_SIZE(rl->queues); i++) {
2118         queue_init(&rl->queues[i]);
2119     }
2120     rl->last_fill = time_msec();
2121     rl->tokens = s->rate_limit * 100;
2122     switch_status_register_category(ss, "rate-limit",
2123                                     rate_limit_status_cb, rl);
2124     return make_hook(rate_limit_local_packet_cb, NULL, rate_limit_periodic_cb,
2125                      rate_limit_wait_cb, rl);
2126 }
2127 \f
2128 /* OFPST_SWITCH statistics. */
2129
2130 struct switch_status_category {
2131     char *name;
2132     void (*cb)(struct status_reply *, void *aux);
2133     void *aux;
2134 };
2135
2136 struct switch_status {
2137     const struct settings *s;
2138     time_t booted;
2139     struct switch_status_category categories[8];
2140     int n_categories;
2141 };
2142
2143 struct status_reply {
2144     struct switch_status_category *category;
2145     struct ds request;
2146     struct ds output;
2147 };
2148
2149 static bool
2150 switch_status_remote_packet_cb(struct relay *r, void *ss_)
2151 {
2152     struct switch_status *ss = ss_;
2153     struct rconn *rc = r->halves[HALF_REMOTE].rconn;
2154     struct ofpbuf *msg = r->halves[HALF_REMOTE].rxbuf;
2155     struct switch_status_category *c;
2156     struct nicira_header *request;
2157     struct nicira_header *reply;
2158     struct status_reply sr;
2159     struct ofpbuf *b;
2160     int retval;
2161
2162     if (msg->size < sizeof(struct nicira_header)) {
2163         return false;
2164     }
2165     request = msg->data;
2166     if (request->header.type != OFPT_VENDOR
2167         || request->vendor != htonl(NX_VENDOR_ID)
2168         || request->subtype != htonl(NXT_STATUS_REQUEST)) {
2169         return false;
2170     }
2171
2172     sr.request.string = (void *) (request + 1);
2173     sr.request.length = msg->size - sizeof *request;
2174     ds_init(&sr.output);
2175     for (c = ss->categories; c < &ss->categories[ss->n_categories]; c++) {
2176         if (!memcmp(c->name, sr.request.string,
2177                     MIN(strlen(c->name), sr.request.length))) {
2178             sr.category = c;
2179             c->cb(&sr, c->aux);
2180         }
2181     }
2182     reply = make_openflow_xid(sizeof *reply + sr.output.length,
2183                               OFPT_VENDOR, request->header.xid, &b);
2184     reply->vendor = htonl(NX_VENDOR_ID);
2185     reply->subtype = htonl(NXT_STATUS_REPLY);
2186     memcpy(reply + 1, sr.output.string, sr.output.length);
2187     retval = rconn_send(rc, b, NULL);
2188     if (retval && retval != EAGAIN) {
2189         VLOG_WARN("send failed (%s)", strerror(retval));
2190     }
2191     ds_destroy(&sr.output);
2192     return true;
2193 }
2194
2195 static void
2196 rconn_status_cb(struct status_reply *sr, void *rconn_)
2197 {
2198     struct rconn *rconn = rconn_;
2199     time_t now = time_now();
2200
2201     status_reply_put(sr, "name=%s", rconn_get_name(rconn));
2202     status_reply_put(sr, "state=%s", rconn_get_state(rconn));
2203     status_reply_put(sr, "backoff=%d", rconn_get_backoff(rconn));
2204     status_reply_put(sr, "is-connected=%s",
2205                      rconn_is_connected(rconn) ? "true" : "false");
2206     status_reply_put(sr, "sent-msgs=%u", rconn_packets_sent(rconn));
2207     status_reply_put(sr, "received-msgs=%u", rconn_packets_received(rconn));
2208     status_reply_put(sr, "attempted-connections=%u",
2209                      rconn_get_attempted_connections(rconn));
2210     status_reply_put(sr, "successful-connections=%u",
2211                      rconn_get_successful_connections(rconn));
2212     status_reply_put(sr, "last-connection=%ld",
2213                      (long int) (now - rconn_get_last_connection(rconn)));
2214     status_reply_put(sr, "time-connected=%lu",
2215                      rconn_get_total_time_connected(rconn));
2216     status_reply_put(sr, "state-elapsed=%u", rconn_get_state_elapsed(rconn));
2217 }
2218
2219 static void
2220 config_status_cb(struct status_reply *sr, void *s_)
2221 {
2222     const struct settings *s = s_;
2223     size_t i;
2224
2225     for (i = 0; i < s->n_listeners; i++) {
2226         status_reply_put(sr, "management%zu=%s", i, s->listener_names[i]);
2227     }
2228     if (s->probe_interval) {
2229         status_reply_put(sr, "probe-interval=%d", s->probe_interval);
2230     }
2231     if (s->max_backoff) {
2232         status_reply_put(sr, "max-backoff=%d", s->max_backoff);
2233     }
2234 }
2235
2236 static void
2237 switch_status_cb(struct status_reply *sr, void *ss_)
2238 {
2239     struct switch_status *ss = ss_;
2240     time_t now = time_now();
2241
2242     status_reply_put(sr, "now=%ld", (long int) now);
2243     status_reply_put(sr, "uptime=%ld", (long int) (now - ss->booted));
2244     status_reply_put(sr, "pid=%ld", (long int) getpid());
2245 }
2246
2247 static struct hook
2248 switch_status_hook_create(const struct settings *s, struct switch_status **ssp)
2249 {
2250     struct switch_status *ss = xcalloc(1, sizeof *ss);
2251     ss->s = s;
2252     ss->booted = time_now();
2253     switch_status_register_category(ss, "config",
2254                                     config_status_cb, (void *) s);
2255     switch_status_register_category(ss, "switch", switch_status_cb, ss);
2256     *ssp = ss;
2257     return make_hook(NULL, switch_status_remote_packet_cb, NULL, NULL, ss);
2258 }
2259
2260 static void
2261 switch_status_register_category(struct switch_status *ss,
2262                                 const char *category,
2263                                 void (*cb)(struct status_reply *,
2264                                            void *aux),
2265                                 void *aux)
2266 {
2267     struct switch_status_category *c;
2268     assert(ss->n_categories < ARRAY_SIZE(ss->categories));
2269     c = &ss->categories[ss->n_categories++];
2270     c->cb = cb;
2271     c->aux = aux;
2272     c->name = xstrdup(category);
2273 }
2274
2275 static void
2276 status_reply_put(struct status_reply *sr, const char *content, ...)
2277 {
2278     size_t old_length = sr->output.length;
2279     size_t added;
2280     va_list args;
2281
2282     /* Append the status reply to the output. */
2283     ds_put_format(&sr->output, "%s.", sr->category->name);
2284     va_start(args, content);
2285     ds_put_format_valist(&sr->output, content, args);
2286     va_end(args);
2287     if (ds_last(&sr->output) != '\n') {
2288         ds_put_char(&sr->output, '\n');
2289     }
2290
2291     /* Drop what we just added if it doesn't match the request. */
2292     added = sr->output.length - old_length;
2293     if (added < sr->request.length
2294         || memcmp(&sr->output.string[old_length],
2295                   sr->request.string, sr->request.length)) {
2296         ds_truncate(&sr->output, old_length);
2297     }
2298 }
2299
2300 \f
2301 /* Controller discovery. */
2302
2303 struct discovery
2304 {
2305     const struct settings *s;
2306     struct dhclient *dhcp;
2307     int n_changes;
2308 };
2309
2310 static void
2311 discovery_status_cb(struct status_reply *sr, void *d_)
2312 {
2313     struct discovery *d = d_;
2314
2315     status_reply_put(sr, "accept-remote=%s", d->s->accept_controller_re);
2316     status_reply_put(sr, "n-changes=%d", d->n_changes);
2317     if (d->dhcp) {
2318         status_reply_put(sr, "state=%s", dhclient_get_state(d->dhcp));
2319         status_reply_put(sr, "state-elapsed=%u",
2320                          dhclient_get_state_elapsed(d->dhcp)); 
2321         if (dhclient_is_bound(d->dhcp)) {
2322             uint32_t ip = dhclient_get_ip(d->dhcp);
2323             uint32_t netmask = dhclient_get_netmask(d->dhcp);
2324             uint32_t router = dhclient_get_router(d->dhcp);
2325
2326             const struct dhcp_msg *cfg = dhclient_get_config(d->dhcp);
2327             uint32_t dns_server;
2328             char *domain_name;
2329             int i;
2330
2331             status_reply_put(sr, "ip="IP_FMT, IP_ARGS(&ip));
2332             status_reply_put(sr, "netmask="IP_FMT, IP_ARGS(&netmask));
2333             if (router) {
2334                 status_reply_put(sr, "router="IP_FMT, IP_ARGS(&router));
2335             }
2336
2337             for (i = 0; dhcp_msg_get_ip(cfg, DHCP_CODE_DNS_SERVER, i,
2338                                         &dns_server);
2339                  i++) {
2340                 status_reply_put(sr, "dns%d="IP_FMT, i, IP_ARGS(&dns_server));
2341             }
2342
2343             domain_name = dhcp_msg_get_string(cfg, DHCP_CODE_DOMAIN_NAME);
2344             if (domain_name) {
2345                 status_reply_put(sr, "domain=%s", domain_name);
2346                 free(domain_name);
2347             }
2348
2349             status_reply_put(sr, "lease-remaining=%u",
2350                              dhclient_get_lease_remaining(d->dhcp));
2351         }
2352     }
2353 }
2354
2355 static void
2356 discovery_local_port_cb(const struct ofp_phy_port *port, void *d_) 
2357 {
2358     struct discovery *d = d_;
2359     if (port) {
2360         char name[OFP_MAX_PORT_NAME_LEN + 1];
2361         struct netdev *netdev;
2362         int retval;
2363
2364         /* Check that this was really a change. */
2365         get_port_name(port, name, sizeof name);
2366         if (d->dhcp && !strcmp(netdev_get_name(dhclient_get_netdev(d->dhcp)),
2367                                name)) {
2368             return;
2369         }
2370
2371         /* Destroy current DHCP client. */
2372         dhclient_destroy(d->dhcp);
2373         d->dhcp = NULL;
2374
2375         /* Bring local network device up. */
2376         retval = netdev_open(name, NETDEV_ETH_TYPE_NONE, &netdev);
2377         if (retval) {
2378             VLOG_ERR("Could not open %s device, discovery disabled: %s",
2379                      name, strerror(retval));
2380             return;
2381         }
2382         retval = netdev_turn_flags_on(netdev, NETDEV_UP, true);
2383         if (retval) {
2384             VLOG_ERR("Could not bring %s device up, discovery disabled: %s",
2385                      name, strerror(retval));
2386             return;
2387         }
2388         netdev_close(netdev);
2389
2390         /* Initialize DHCP client. */
2391         retval = dhclient_create(name, modify_dhcp_request,
2392                                  validate_dhcp_offer, (void *) d->s, &d->dhcp);
2393         if (retval) {
2394             VLOG_ERR("Failed to initialize DHCP client, "
2395                      "discovery disabled: %s", strerror(retval));
2396             return;
2397         }
2398         dhclient_set_max_timeout(d->dhcp, 3);
2399         dhclient_init(d->dhcp, 0);
2400     } else {
2401         dhclient_destroy(d->dhcp);
2402         d->dhcp = NULL;
2403     }
2404 }
2405
2406
2407 static struct discovery *
2408 discovery_init(const struct settings *s, struct port_watcher *pw,
2409                struct switch_status *ss)
2410 {
2411     struct discovery *d;
2412
2413     d = xmalloc(sizeof *d);
2414     d->s = s;
2415     d->dhcp = NULL;
2416     d->n_changes = 0;
2417
2418     switch_status_register_category(ss, "discovery", discovery_status_cb, d);
2419     port_watcher_register_local_port_callback(pw, discovery_local_port_cb, d);
2420
2421     return d;
2422 }
2423
2424 static void
2425 discovery_question_connectivity(struct discovery *d)
2426 {
2427     if (d->dhcp) {
2428         dhclient_force_renew(d->dhcp, 15); 
2429     }
2430 }
2431
2432 static bool
2433 discovery_run(struct discovery *d, char **controller_name)
2434 {
2435     if (!d->dhcp) {
2436         *controller_name = NULL;
2437         return true;
2438     }
2439
2440     dhclient_run(d->dhcp);
2441     if (!dhclient_changed(d->dhcp)) {
2442         return false;
2443     }
2444
2445     dhclient_configure_netdev(d->dhcp);
2446     if (d->s->update_resolv_conf) {
2447         dhclient_update_resolv_conf(d->dhcp);
2448     }
2449
2450     if (dhclient_is_bound(d->dhcp)) {
2451         *controller_name = dhcp_msg_get_string(dhclient_get_config(d->dhcp),
2452                                                DHCP_CODE_OFP_CONTROLLER_VCONN);
2453         VLOG_WARN("%s: discovered controller", *controller_name);
2454         d->n_changes++;
2455     } else {
2456         *controller_name = NULL;
2457         if (d->n_changes) {
2458             VLOG_WARN("discovered controller no longer available");
2459             d->n_changes++;
2460         }
2461     }
2462     return true;
2463 }
2464
2465 static void
2466 discovery_wait(struct discovery *d)
2467 {
2468     if (d->dhcp) {
2469         dhclient_wait(d->dhcp); 
2470     }
2471 }
2472
2473 static void
2474 modify_dhcp_request(struct dhcp_msg *msg, void *aux)
2475 {
2476     dhcp_msg_put_string(msg, DHCP_CODE_VENDOR_CLASS, "OpenFlow");
2477 }
2478
2479 static bool
2480 validate_dhcp_offer(const struct dhcp_msg *msg, void *s_)
2481 {
2482     const struct settings *s = s_;
2483     char *vconn_name;
2484     bool accept;
2485
2486     vconn_name = dhcp_msg_get_string(msg, DHCP_CODE_OFP_CONTROLLER_VCONN);
2487     if (!vconn_name) {
2488         VLOG_WARN_RL(&vrl, "rejecting DHCP offer missing controller vconn");
2489         return false;
2490     }
2491     accept = !regexec(&s->accept_controller_regex, vconn_name, 0, NULL, 0);
2492     if (!accept) {
2493         VLOG_WARN_RL(&vrl, "rejecting controller vconn that fails to match %s",
2494                      s->accept_controller_re);
2495     }
2496     free(vconn_name);
2497     return accept;
2498 }
2499 \f
2500 /* User interface. */
2501
2502 static void
2503 parse_options(int argc, char *argv[], struct settings *s)
2504 {
2505     enum {
2506         OPT_ACCEPT_VCONN = UCHAR_MAX + 1,
2507         OPT_NO_RESOLV_CONF,
2508         OPT_INACTIVITY_PROBE,
2509         OPT_MAX_IDLE,
2510         OPT_MAX_BACKOFF,
2511         OPT_RATE_LIMIT,
2512         OPT_BURST_LIMIT,
2513         OPT_BOOTSTRAP_CA_CERT,
2514         OPT_STP,
2515         OPT_NO_STP,
2516         OPT_OUT_OF_BAND,
2517         OPT_IN_BAND
2518     };
2519     static struct option long_options[] = {
2520         {"accept-vconn", required_argument, 0, OPT_ACCEPT_VCONN},
2521         {"no-resolv-conf", no_argument, 0, OPT_NO_RESOLV_CONF},
2522         {"fail",        required_argument, 0, 'F'},
2523         {"inactivity-probe", required_argument, 0, OPT_INACTIVITY_PROBE},
2524         {"max-idle",    required_argument, 0, OPT_MAX_IDLE},
2525         {"max-backoff", required_argument, 0, OPT_MAX_BACKOFF},
2526         {"listen",      required_argument, 0, 'l'},
2527         {"monitor",     required_argument, 0, 'm'},
2528         {"rate-limit",  optional_argument, 0, OPT_RATE_LIMIT},
2529         {"burst-limit", required_argument, 0, OPT_BURST_LIMIT},
2530         {"stp",         no_argument, 0, OPT_STP},
2531         {"no-stp",      no_argument, 0, OPT_NO_STP},
2532         {"out-of-band", no_argument, 0, OPT_OUT_OF_BAND},
2533         {"in-band",     no_argument, 0, OPT_IN_BAND},
2534         {"verbose",     optional_argument, 0, 'v'},
2535         {"help",        no_argument, 0, 'h'},
2536         {"version",     no_argument, 0, 'V'},
2537         DAEMON_LONG_OPTIONS,
2538 #ifdef HAVE_OPENSSL
2539         VCONN_SSL_LONG_OPTIONS
2540         {"bootstrap-ca-cert", required_argument, 0, OPT_BOOTSTRAP_CA_CERT},
2541 #endif
2542         {0, 0, 0, 0},
2543     };
2544     char *short_options = long_options_to_short_options(long_options);
2545     char *accept_re = NULL;
2546     int retval;
2547
2548     /* Set defaults that we can figure out before parsing options. */
2549     s->n_listeners = 0;
2550     s->monitor_name = NULL;
2551     s->fail_mode = FAIL_OPEN;
2552     s->max_idle = 15;
2553     s->probe_interval = 15;
2554     s->max_backoff = 15;
2555     s->update_resolv_conf = true;
2556     s->rate_limit = 0;
2557     s->burst_limit = 0;
2558     s->enable_stp = false;
2559     s->in_band = true;
2560     for (;;) {
2561         int c;
2562
2563         c = getopt_long(argc, argv, short_options, long_options, NULL);
2564         if (c == -1) {
2565             break;
2566         }
2567
2568         switch (c) {
2569         case OPT_ACCEPT_VCONN:
2570             accept_re = optarg[0] == '^' ? optarg : xasprintf("^%s", optarg);
2571             break;
2572
2573         case OPT_NO_RESOLV_CONF:
2574             s->update_resolv_conf = false;
2575             break;
2576
2577         case 'F':
2578             if (!strcmp(optarg, "open")) {
2579                 s->fail_mode = FAIL_OPEN;
2580             } else if (!strcmp(optarg, "closed")) {
2581                 s->fail_mode = FAIL_CLOSED;
2582             } else {
2583                 ofp_fatal(0, "-f or --fail argument must be \"open\" "
2584                           "or \"closed\"");
2585             }
2586             break;
2587
2588         case OPT_INACTIVITY_PROBE:
2589             s->probe_interval = atoi(optarg);
2590             if (s->probe_interval < 5) {
2591                 ofp_fatal(0, "--inactivity-probe argument must be at least 5");
2592             }
2593             break;
2594
2595         case OPT_MAX_IDLE:
2596             if (!strcmp(optarg, "permanent")) {
2597                 s->max_idle = OFP_FLOW_PERMANENT;
2598             } else {
2599                 s->max_idle = atoi(optarg);
2600                 if (s->max_idle < 1 || s->max_idle > 65535) {
2601                     ofp_fatal(0, "--max-idle argument must be between 1 and "
2602                               "65535 or the word 'permanent'");
2603                 }
2604             }
2605             break;
2606
2607         case OPT_MAX_BACKOFF:
2608             s->max_backoff = atoi(optarg);
2609             if (s->max_backoff < 1) {
2610                 ofp_fatal(0, "--max-backoff argument must be at least 1");
2611             } else if (s->max_backoff > 3600) {
2612                 s->max_backoff = 3600;
2613             }
2614             break;
2615
2616         case OPT_RATE_LIMIT:
2617             if (optarg) {
2618                 s->rate_limit = atoi(optarg);
2619                 if (s->rate_limit < 1) {
2620                     ofp_fatal(0, "--rate-limit argument must be at least 1");
2621                 }
2622             } else {
2623                 s->rate_limit = 1000;
2624             }
2625             break;
2626
2627         case OPT_BURST_LIMIT:
2628             s->burst_limit = atoi(optarg);
2629             if (s->burst_limit < 1) {
2630                 ofp_fatal(0, "--burst-limit argument must be at least 1");
2631             }
2632             break;
2633
2634         case OPT_STP:
2635             s->enable_stp = true;
2636             break;
2637
2638         case OPT_NO_STP:
2639             s->enable_stp = false;
2640             break;
2641
2642         case OPT_OUT_OF_BAND:
2643             s->in_band = false;
2644             break;
2645
2646         case OPT_IN_BAND:
2647             s->in_band = true;
2648             break;
2649
2650         case 'l':
2651             if (s->n_listeners >= MAX_MGMT) {
2652                 ofp_fatal(0,
2653                           "-l or --listen may be specified at most %d times",
2654                           MAX_MGMT);
2655             }
2656             s->listener_names[s->n_listeners++] = optarg;
2657             break;
2658
2659         case 'm':
2660             if (s->monitor_name) {
2661                 ofp_fatal(0, "-m or --monitor may only be specified once");
2662             }
2663             s->monitor_name = optarg;
2664             break;
2665
2666         case 'h':
2667             usage();
2668
2669         case 'V':
2670             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
2671             exit(EXIT_SUCCESS);
2672
2673         case 'v':
2674             vlog_set_verbosity(optarg);
2675             break;
2676
2677         DAEMON_OPTION_HANDLERS
2678
2679 #ifdef HAVE_OPENSSL
2680         VCONN_SSL_OPTION_HANDLERS
2681
2682         case OPT_BOOTSTRAP_CA_CERT:
2683             vconn_ssl_set_ca_cert_file(optarg, true);
2684             break;
2685 #endif
2686
2687         case '?':
2688             exit(EXIT_FAILURE);
2689
2690         default:
2691             abort();
2692         }
2693     }
2694     free(short_options);
2695
2696     argc -= optind;
2697     argv += optind;
2698     if (argc < 1 || argc > 2) {
2699         ofp_fatal(0, "need one or two non-option arguments; "
2700                   "use --help for usage");
2701     }
2702
2703     /* Local and remote vconns. */
2704     s->dp_name = argv[0];
2705     s->controller_name = argc > 1 ? xstrdup(argv[1]) : NULL;
2706
2707     /* Set accept_controller_regex. */
2708     if (!accept_re) {
2709         accept_re = vconn_ssl_is_configured() ? "^ssl:.*" : ".*";
2710     }
2711     retval = regcomp(&s->accept_controller_regex, accept_re,
2712                      REG_NOSUB | REG_EXTENDED);
2713     if (retval) {
2714         size_t length = regerror(retval, &s->accept_controller_regex, NULL, 0);
2715         char *buffer = xmalloc(length);
2716         regerror(retval, &s->accept_controller_regex, buffer, length);
2717         ofp_fatal(0, "%s: %s", accept_re, buffer);
2718     }
2719     s->accept_controller_re = accept_re;
2720
2721     /* Mode of operation. */
2722     s->discovery = s->controller_name == NULL;
2723     if (s->discovery && !s->in_band) {
2724         ofp_fatal(0, "Cannot perform discovery with out-of-band control");
2725     }
2726
2727     /* Rate limiting. */
2728     if (s->rate_limit) {
2729         if (s->rate_limit < 100) {
2730             VLOG_WARN("Rate limit set to unusually low value %d",
2731                       s->rate_limit);
2732         }
2733         if (!s->burst_limit) {
2734             s->burst_limit = s->rate_limit / 4;
2735         }
2736         s->burst_limit = MAX(s->burst_limit, 1);
2737         s->burst_limit = MIN(s->burst_limit, INT_MAX / 1000);
2738     }
2739 }
2740
2741 static void
2742 usage(void)
2743 {
2744     printf("%s: secure channel, a relay for OpenFlow messages.\n"
2745            "usage: %s [OPTIONS] nl:DP_IDX [CONTROLLER]\n"
2746            "where nl:DP_IDX is a datapath that has been added with dpctl.\n"
2747            "CONTROLLER is an active OpenFlow connection method; if it is\n"
2748            "omitted, then secchan performs controller discovery.\n",
2749            program_name, program_name);
2750     vconn_usage(true, true, true);
2751     printf("\nController discovery options:\n"
2752            "  --accept-vconn=REGEX    accept matching discovered controllers\n"
2753            "  --no-resolv-conf        do not update /etc/resolv.conf\n"
2754            "\nNetworking options:\n"
2755            "  -F, --fail=open|closed  when controller connection fails:\n"
2756            "                            closed: drop all packets\n"
2757            "                            open (default): act as learning switch\n"
2758            "  --inactivity-probe=SECS time between inactivity probes\n"
2759            "  --max-idle=SECS         max idle for flows set up by secchan\n"
2760            "  --max-backoff=SECS      max time between controller connection\n"
2761            "                          attempts (default: 15 seconds)\n"
2762            "  -l, --listen=METHOD     allow management connections on METHOD\n"
2763            "                          (a passive OpenFlow connection method)\n"
2764            "  -m, --monitor=METHOD    copy traffic to/from kernel to METHOD\n"
2765            "                          (a passive OpenFlow connection method)\n"
2766            "  --out-of-band           controller connection is out-of-band\n"
2767            "  --stp                   enable 802.1D Spanning Tree Protocol\n"
2768            "  --no-stp                disable 802.1D Spanning Tree Protocol\n"
2769            "\nRate-limiting of \"packet-in\" messages to the controller:\n"
2770            "  --rate-limit[=PACKETS]  max rate, in packets/s (default: 1000)\n"
2771            "  --burst-limit=BURST     limit on packet credit for idle time\n");
2772     daemon_usage();
2773     printf("\nOther options:\n"
2774            "  -v, --verbose=MODULE[:FACILITY[:LEVEL]]  set logging levels\n"
2775            "  -v, --verbose           set maximum verbosity level\n"
2776            "  -h, --help              display this help message\n"
2777            "  -V, --version           display version information\n");
2778     exit(EXIT_SUCCESS);
2779 }