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