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