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