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