Remove secchan dependence on Netlink for connecting to the datapath.
[openvswitch] / 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         VLOG_WARN("Identified data path local port as \"%s\".", name);
724     } else {
725         VLOG_WARN("Data path has no local port.");
726     }
727     strcpy(pw->local_port_name, name);
728
729     /* Invoke callbacks. */
730     for (i = 0; i < pw->n_local_cbs; i++) {
731         local_port_changed_cb_func *cb = pw->local_cbs[i].local_port_changed;
732         (cb)(port, pw->local_cbs[i].aux);
733     }
734 }
735
736 static void
737 update_phy_port(struct port_watcher *pw, struct ofp_phy_port *opp,
738                 uint8_t reason, bool seen[OFPP_MAX + 1])
739 {
740     struct ofp_phy_port *pw_opp;
741     struct ofp_phy_port old;
742     uint16_t port_no;
743     int idx;
744
745     port_no = ntohs(opp->port_no);
746     idx = port_no_to_pw_idx(port_no);
747     if (idx < 0) {
748         return;
749     }
750
751     if (seen) {
752         seen[idx] = true;
753     }
754
755     pw_opp = &pw->ports[idx];
756     old = *pw_opp;
757     if (reason == OFPPR_DELETE) {
758         memset(pw_opp, 0, sizeof *pw_opp);
759         pw_opp->port_no = htons(OFPP_NONE);
760     } else if (reason == OFPPR_MODIFY || reason == OFPPR_ADD) {
761         *pw_opp = *opp;
762         sanitize_opp(pw_opp);
763     }
764     call_port_changed_callbacks(pw, port_no, &old, pw_opp);
765 }
766
767 static bool
768 port_watcher_local_packet_cb(struct relay *r, void *pw_)
769 {
770     struct port_watcher *pw = pw_;
771     struct ofpbuf *msg = r->halves[HALF_LOCAL].rxbuf;
772     struct ofp_header *oh = msg->data;
773
774     if (oh->type == OFPT_FEATURES_REPLY
775         && msg->size >= offsetof(struct ofp_switch_features, ports)) {
776         struct ofp_switch_features *osf = msg->data;
777         bool seen[ARRAY_SIZE(pw->ports)];
778         size_t n_ports;
779         size_t i;
780
781         pw->got_feature_reply = true;
782
783         /* Update each port included in the message. */
784         memset(seen, 0, sizeof seen);
785         n_ports = ((msg->size - offsetof(struct ofp_switch_features, ports))
786                    / sizeof *osf->ports);
787         for (i = 0; i < n_ports; i++) {
788             struct ofp_phy_port *opp = &osf->ports[i];
789             update_phy_port(pw, opp, OFPPR_MODIFY, seen);
790         }
791
792         /* Delete all the ports not included in the message. */
793         for (i = 0; i < ARRAY_SIZE(pw->ports); i++) {
794             if (!seen[i]) {
795                 update_phy_port(pw, &pw->ports[i], OFPPR_DELETE, NULL);
796             }
797         }
798
799         call_local_port_changed_callbacks(pw);
800     } else if (oh->type == OFPT_PORT_STATUS
801                && msg->size >= sizeof(struct ofp_port_status)) {
802         struct ofp_port_status *ops = msg->data;
803         update_phy_port(pw, &ops->desc, ops->reason, NULL);
804         if (ops->desc.port_no == htons(OFPP_LOCAL)) {
805             call_local_port_changed_callbacks(pw);
806         }
807     }
808     return false;
809 }
810
811 static bool
812 port_watcher_remote_packet_cb(struct relay *r, void *pw_)
813 {
814     struct port_watcher *pw = pw_;
815     struct ofpbuf *msg = r->halves[HALF_REMOTE].rxbuf;
816     struct ofp_header *oh = msg->data;
817
818     if (oh->type == OFPT_PORT_MOD
819         && msg->size >= sizeof(struct ofp_port_mod)) {
820         struct ofp_port_mod *opm = msg->data;
821         uint16_t port_no = ntohs(opm->port_no);
822         int idx = port_no_to_pw_idx(port_no);
823         if (idx >= 0) {
824             struct ofp_phy_port *pw_opp = &pw->ports[idx];
825             if (pw_opp->port_no != htons(OFPP_NONE)) {
826                 struct ofp_phy_port old = *pw_opp;
827                 pw_opp->config = ((pw_opp->config & ~opm->mask)
828                                  | (opm->config & opm->mask));
829                 call_port_changed_callbacks(pw, port_no, &old, pw_opp);
830                 if (pw_opp->port_no == htons(OFPP_LOCAL)) {
831                     call_local_port_changed_callbacks(pw);
832                 }
833             }
834         }
835     }
836     return false;
837 }
838
839 static void
840 port_watcher_periodic_cb(void *pw_)
841 {
842     struct port_watcher *pw = pw_;
843
844     if (!pw->got_feature_reply
845         && time_now() >= pw->last_feature_request + 5
846         && rconn_is_connected(pw->local_rconn)) {
847         struct ofpbuf *b;
848         make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &b);
849         rconn_send_with_limit(pw->local_rconn, b, &pw->n_txq, 1);
850         pw->last_feature_request = time_now();
851     }
852 }
853
854 static void
855 port_watcher_wait_cb(void *pw_)
856 {
857     struct port_watcher *pw = pw_;
858     if (!pw->got_feature_reply && rconn_is_connected(pw->local_rconn)) {
859         if (pw->last_feature_request != TIME_MIN) {
860             poll_timer_wait(pw->last_feature_request + 5 - time_now());
861         } else {
862             poll_immediate_wake();
863         }
864     }
865 }
866
867 static void
868 put_duplexes(struct ds *ds, const char *name, uint32_t features,
869              uint32_t hd_bit, uint32_t fd_bit)
870 {
871     if (features & (hd_bit | fd_bit)) {
872         ds_put_format(ds, " %s", name);
873         if (features & hd_bit) {
874             ds_put_cstr(ds, "(HD)");
875         }
876         if (features & fd_bit) {
877             ds_put_cstr(ds, "(FD)");
878         }
879     }
880 }
881
882 static void
883 put_features(struct ds *ds, const char *name, uint32_t features)
884 {
885     if (features & (OFPPF_10MB_HD | OFPPF_10MB_FD
886                     | OFPPF_100MB_HD | OFPPF_100MB_FD
887                     | OFPPF_1GB_HD | OFPPF_1GB_FD | OFPPF_10GB_FD)) {
888         ds_put_cstr(ds, name);
889         put_duplexes(ds, "10M", features, OFPPF_10MB_HD, OFPPF_10MB_FD);
890         put_duplexes(ds, "100M", features,
891                      OFPPF_100MB_HD, OFPPF_100MB_FD);
892         put_duplexes(ds, "1G", features, OFPPF_100MB_HD, OFPPF_100MB_FD);
893         if (features & OFPPF_10GB_FD) {
894             ds_put_cstr(ds, " 10G");
895         }
896         if (features & OFPPF_AUTONEG) {
897             ds_put_cstr(ds, " AUTO_NEG");
898         }
899         if (features & OFPPF_PAUSE) {
900             ds_put_cstr(ds, " PAUSE");
901         }
902         if (features & OFPPF_PAUSE_ASYM) {
903             ds_put_cstr(ds, " PAUSE_ASYM");
904         }
905     }
906 }
907
908 static void
909 log_port_status(uint16_t port_no,
910                 const struct ofp_phy_port *old,
911                 const struct ofp_phy_port *new,
912                 void *aux)
913 {
914     if (VLOG_IS_DBG_ENABLED()) {
915         bool was_enabled = old->port_no != htons(OFPP_NONE);
916         bool now_enabled = new->port_no != htons(OFPP_NONE);
917         uint32_t curr = ntohl(new->curr);
918         uint32_t supported = ntohl(new->supported);
919         struct ds ds;
920
921         if (((old->config != new->config) || (old->state != new->state))
922                 && opp_differs(old, new) == 1) {
923             /* Don't care if only flags changed. */
924             return;
925         }
926
927         ds_init(&ds);
928         ds_put_format(&ds, "\"%s\", "ETH_ADDR_FMT, new->name,
929                       ETH_ADDR_ARGS(new->hw_addr));
930         if (curr) {
931             put_features(&ds, ", current", curr);
932         }
933         if (supported) {
934             put_features(&ds, ", supports", supported);
935         }
936         if (was_enabled != now_enabled) {
937             if (now_enabled) {
938                 VLOG_DBG("Port %d added: %s", port_no, ds_cstr(&ds));
939             } else {
940                 VLOG_DBG("Port %d deleted", port_no);
941             }
942         } else {
943             VLOG_DBG("Port %d changed: %s", port_no, ds_cstr(&ds));
944         }
945         ds_destroy(&ds);
946     }
947 }
948
949 static void
950 port_watcher_register_callback(struct port_watcher *pw,
951                                port_changed_cb_func *port_changed,
952                                void *aux)
953 {
954     assert(pw->n_cbs < ARRAY_SIZE(pw->cbs));
955     pw->cbs[pw->n_cbs].port_changed = port_changed;
956     pw->cbs[pw->n_cbs].aux = aux;
957     pw->n_cbs++;
958 }
959
960 static void
961 port_watcher_register_local_port_callback(struct port_watcher *pw,
962                                           local_port_changed_cb_func *cb,
963                                           void *aux)
964 {
965     assert(pw->n_local_cbs < ARRAY_SIZE(pw->local_cbs));
966     pw->local_cbs[pw->n_local_cbs].local_port_changed = cb;
967     pw->local_cbs[pw->n_local_cbs].aux = aux;
968     pw->n_local_cbs++;
969 }
970
971 static uint32_t
972 port_watcher_get_config(const struct port_watcher *pw, int port_no)
973 {
974     int idx = port_no_to_pw_idx(port_no);
975     return idx >= 0 ? ntohl(pw->ports[idx].config) : 0;
976 }
977
978 static void
979 port_watcher_set_flags(struct port_watcher *pw, int port_no, 
980                        uint32_t config, uint32_t c_mask,
981                        uint32_t state, uint32_t s_mask)
982 {
983     struct ofp_phy_port old;
984     struct ofp_phy_port *p;
985     struct ofp_port_mod *opm;
986     struct ofp_port_status *ops;
987     struct ofpbuf *b;
988     int idx;
989
990     idx = port_no_to_pw_idx(port_no);
991     if (idx < 0) {
992         return;
993     }
994
995     p = &pw->ports[idx];
996     if (!((ntohl(p->state) ^ state) & s_mask) 
997             && (!((ntohl(p->config) ^ config) & c_mask))) {
998         return;
999     }
1000     old = *p;
1001
1002     /* Update our idea of the flags. */
1003     p->config = htonl((ntohl(p->config) & ~c_mask) | (config & c_mask));
1004     p->state = htonl((ntohl(p->state) & ~s_mask) | (state & s_mask));
1005     call_port_changed_callbacks(pw, port_no, &old, p);
1006
1007     /* Change the flags in the datapath. */
1008     opm = make_openflow(sizeof *opm, OFPT_PORT_MOD, &b);
1009     opm->port_no = p->port_no;
1010     memcpy(opm->hw_addr, p->hw_addr, OFP_ETH_ALEN);
1011     opm->config = p->config;
1012     opm->mask = htonl(c_mask);
1013     opm->advertise = htonl(0);
1014     rconn_send(pw->local_rconn, b, NULL);
1015
1016     /* Notify the controller that the flags changed. */
1017     ops = make_openflow(sizeof *ops, OFPT_PORT_STATUS, &b);
1018     ops->reason = OFPPR_MODIFY;
1019     ops->desc = *p;
1020     rconn_send(pw->remote_rconn, b, NULL);
1021 }
1022
1023 static bool
1024 port_watcher_is_ready(const struct port_watcher *pw)
1025 {
1026     return pw->got_feature_reply;
1027 }
1028
1029 static struct hook
1030 port_watcher_create(struct rconn *local_rconn, struct rconn *remote_rconn,
1031                     struct port_watcher **pwp)
1032 {
1033     struct port_watcher *pw;
1034     int i;
1035
1036     pw = *pwp = xcalloc(1, sizeof *pw);
1037     pw->local_rconn = local_rconn;
1038     pw->remote_rconn = remote_rconn;
1039     pw->last_feature_request = TIME_MIN;
1040     for (i = 0; i < OFPP_MAX; i++) {
1041         pw->ports[i].port_no = htons(OFPP_NONE);
1042     }
1043     pw->local_port_name[0] = '\0';
1044     port_watcher_register_callback(pw, log_port_status, NULL);
1045     return make_hook(port_watcher_local_packet_cb,
1046                      port_watcher_remote_packet_cb,
1047                      port_watcher_periodic_cb,
1048                      port_watcher_wait_cb, pw);
1049 }
1050 \f
1051 /* Spanning tree protocol. */
1052
1053 /* Extra time, in seconds, at boot before going into fail-open, to give the
1054  * spanning tree protocol time to figure out the network layout. */
1055 #define STP_EXTRA_BOOT_TIME 30
1056
1057 struct stp_data {
1058     struct stp *stp;
1059     struct port_watcher *pw;
1060     struct rconn *local_rconn;
1061     struct rconn *remote_rconn;
1062     long long int last_tick_256ths;
1063     int n_txq;
1064 };
1065
1066 static bool
1067 stp_local_packet_cb(struct relay *r, void *stp_)
1068 {
1069     struct ofpbuf *msg = r->halves[HALF_LOCAL].rxbuf;
1070     struct ofp_header *oh;
1071     struct stp_data *stp = stp_;
1072     struct ofp_packet_in *opi;
1073     struct eth_header *eth;
1074     struct llc_header *llc;
1075     struct ofpbuf payload;
1076     uint16_t port_no;
1077     struct flow flow;
1078
1079     oh = msg->data;
1080     if (oh->type == OFPT_FEATURES_REPLY
1081         && msg->size >= offsetof(struct ofp_switch_features, ports)) {
1082         struct ofp_switch_features *osf = msg->data;
1083         osf->capabilities |= htonl(OFPC_STP);
1084         return false;
1085     }
1086
1087     if (!get_ofp_packet_eth_header(r, &opi, &eth)
1088         || !eth_addr_equals(eth->eth_dst, stp_eth_addr)) {
1089         return false;
1090     }
1091
1092     port_no = ntohs(opi->in_port);
1093     if (port_no >= STP_MAX_PORTS) {
1094         /* STP only supports 255 ports. */
1095         return false;
1096     }
1097     if (port_watcher_get_config(stp->pw, port_no) & OFPPC_NO_STP) {
1098         /* We're not doing STP on this port. */
1099         return false;
1100     }
1101
1102     if (opi->reason == OFPR_ACTION) {
1103         /* The controller set up a flow for this, so we won't intercept it. */
1104         return false;
1105     }
1106
1107     get_ofp_packet_payload(opi, &payload);
1108     flow_extract(&payload, port_no, &flow);
1109     if (flow.dl_type != htons(OFP_DL_TYPE_NOT_ETH_TYPE)) {
1110         VLOG_DBG("non-LLC frame received on STP multicast address");
1111         return false;
1112     }
1113     llc = ofpbuf_at_assert(&payload, sizeof *eth, sizeof *llc);
1114     if (llc->llc_dsap != STP_LLC_DSAP) {
1115         VLOG_DBG("bad DSAP 0x%02"PRIx8" received on STP multicast address",
1116                  llc->llc_dsap);
1117         return false;
1118     }
1119
1120     /* Trim off padding on payload. */
1121     if (payload.size > ntohs(eth->eth_type) + ETH_HEADER_LEN) {
1122         payload.size = ntohs(eth->eth_type) + ETH_HEADER_LEN;
1123     }
1124     if (ofpbuf_try_pull(&payload, ETH_HEADER_LEN + LLC_HEADER_LEN)) {
1125         struct stp_port *p = stp_get_port(stp->stp, port_no);
1126         stp_received_bpdu(p, payload.data, payload.size);
1127     }
1128
1129     return true;
1130 }
1131
1132 static long long int
1133 time_256ths(void)
1134 {
1135     return time_msec() * 256 / 1000;
1136 }
1137
1138 static void
1139 stp_periodic_cb(void *stp_)
1140 {
1141     struct stp_data *stp = stp_;
1142     long long int now_256ths = time_256ths();
1143     long long int elapsed_256ths = now_256ths - stp->last_tick_256ths;
1144     struct stp_port *p;
1145
1146     if (!port_watcher_is_ready(stp->pw)) {
1147         /* Can't start STP until we know port flags, because port flags can
1148          * disable STP. */
1149         return;
1150     }
1151     if (elapsed_256ths <= 0) {
1152         return;
1153     }
1154
1155     stp_tick(stp->stp, MIN(INT_MAX, elapsed_256ths));
1156     stp->last_tick_256ths = now_256ths;
1157
1158     while (stp_get_changed_port(stp->stp, &p)) {
1159         int port_no = stp_port_no(p);
1160         enum stp_state s_state = stp_port_get_state(p);
1161
1162         if (s_state != STP_DISABLED) {
1163             VLOG_WARN("STP: Port %d entered %s state",
1164                       port_no, stp_state_name(s_state));
1165         }
1166         if (!(port_watcher_get_config(stp->pw, port_no) & OFPPC_NO_STP)) {
1167             uint32_t p_config = 0;
1168             uint32_t p_state;
1169             switch (s_state) {
1170             case STP_LISTENING:
1171                 p_state = OFPPS_STP_LISTEN;
1172                 break;
1173             case STP_LEARNING:
1174                 p_state = OFPPS_STP_LEARN;
1175                 break;
1176             case STP_DISABLED:
1177             case STP_FORWARDING:
1178                 p_state = OFPPS_STP_FORWARD;
1179                 break;
1180             case STP_BLOCKING:
1181                 p_state = OFPPS_STP_BLOCK;
1182                 break;
1183             default:
1184                 VLOG_DBG_RL(&vrl, "STP: Port %d has bad state %x",
1185                             port_no, s_state);
1186                 p_state = OFPPS_STP_FORWARD;
1187                 break;
1188             }
1189             if (!stp_forward_in_state(s_state)) {
1190                 p_config = OFPPC_NO_FLOOD;
1191             }
1192             port_watcher_set_flags(stp->pw, port_no, 
1193                                    p_config, OFPPC_NO_FLOOD,
1194                                    p_state, OFPPS_STP_MASK);
1195         } else {
1196             /* We don't own those flags. */
1197         }
1198     }
1199 }
1200
1201 static void
1202 stp_wait_cb(void *stp_ UNUSED)
1203 {
1204     poll_timer_wait(1000);
1205 }
1206
1207 static void
1208 send_bpdu(const void *bpdu, size_t bpdu_size, int port_no, void *stp_)
1209 {
1210     struct stp_data *stp = stp_;
1211     struct eth_header *eth;
1212     struct llc_header *llc;
1213     struct ofpbuf pkt, *opo;
1214
1215     /* Packet skeleton. */
1216     ofpbuf_init(&pkt, ETH_HEADER_LEN + LLC_HEADER_LEN + bpdu_size);
1217     eth = ofpbuf_put_uninit(&pkt, sizeof *eth);
1218     llc = ofpbuf_put_uninit(&pkt, sizeof *llc);
1219     ofpbuf_put(&pkt, bpdu, bpdu_size);
1220
1221     /* 802.2 header. */
1222     memcpy(eth->eth_dst, stp_eth_addr, ETH_ADDR_LEN);
1223     memcpy(eth->eth_src, stp->pw->ports[port_no].hw_addr, ETH_ADDR_LEN);
1224     eth->eth_type = htons(pkt.size - ETH_HEADER_LEN);
1225
1226     /* LLC header. */
1227     llc->llc_dsap = STP_LLC_DSAP;
1228     llc->llc_ssap = STP_LLC_SSAP;
1229     llc->llc_cntl = STP_LLC_CNTL;
1230
1231     opo = make_unbuffered_packet_out(&pkt, OFPP_NONE, port_no);
1232     ofpbuf_uninit(&pkt);
1233     rconn_send_with_limit(stp->local_rconn, opo, &stp->n_txq, OFPP_MAX);
1234 }
1235
1236 static bool
1237 stp_is_port_supported(uint16_t port_no)
1238 {
1239     /* We should be able to support STP on all possible OpenFlow physical
1240      * ports.  (But we don't support STP on OFPP_LOCAL.)  */
1241     BUILD_ASSERT_DECL(STP_MAX_PORTS >= OFPP_MAX);
1242     return port_no < STP_MAX_PORTS;
1243 }
1244
1245 static void
1246 stp_port_changed_cb(uint16_t port_no,
1247                     const struct ofp_phy_port *old,
1248                     const struct ofp_phy_port *new,
1249                     void *stp_)
1250 {
1251     struct stp_data *stp = stp_;
1252     struct stp_port *p;
1253
1254     if (!stp_is_port_supported(port_no)) {
1255         return;
1256     }
1257
1258     p = stp_get_port(stp->stp, port_no);
1259     if (new->port_no == htons(OFPP_NONE)
1260         || new->config & htonl(OFPPC_NO_STP | OFPPC_PORT_DOWN)
1261         || new->state & htonl(OFPPS_LINK_DOWN)) {
1262         stp_port_disable(p);
1263     } else {
1264         int speed = 0;
1265         stp_port_enable(p);
1266         if (new->curr & (OFPPF_10MB_HD | OFPPF_10MB_FD)) {
1267             speed = 10;
1268         } else if (new->curr & (OFPPF_100MB_HD | OFPPF_100MB_FD)) {
1269             speed = 100;
1270         } else if (new->curr & (OFPPF_1GB_HD | OFPPF_1GB_FD)) {
1271             speed = 1000;
1272         } else if (new->curr & OFPPF_100MB_FD) {
1273             speed = 10000;
1274         }
1275         stp_port_set_speed(p, speed);
1276     }
1277 }
1278
1279 static void
1280 stp_local_port_changed_cb(const struct ofp_phy_port *port, void *stp_)
1281 {
1282     struct stp_data *stp = stp_;
1283     if (port) {
1284         stp_set_bridge_id(stp->stp, eth_addr_to_uint64(port->hw_addr));
1285     }
1286 }
1287
1288 static struct hook
1289 stp_hook_create(const struct settings *s, struct port_watcher *pw,
1290                 struct rconn *local, struct rconn *remote)
1291 {
1292     uint8_t dpid[ETH_ADDR_LEN];
1293     struct stp_data *stp;
1294
1295     stp = xcalloc(1, sizeof *stp);
1296     eth_addr_random(dpid);
1297     stp->stp = stp_create("stp", eth_addr_to_uint64(dpid), send_bpdu, stp);
1298     stp->pw = pw;
1299     stp->local_rconn = local;
1300     stp->remote_rconn = remote;
1301     stp->last_tick_256ths = time_256ths();
1302
1303     port_watcher_register_callback(pw, stp_port_changed_cb, stp);
1304     port_watcher_register_local_port_callback(pw, stp_local_port_changed_cb,
1305                                               stp);
1306     return make_hook(stp_local_packet_cb, NULL,
1307                      stp_periodic_cb, stp_wait_cb, stp);
1308 }
1309 \f
1310 /* In-band control. */
1311
1312 struct in_band_data {
1313     const struct settings *s;
1314     struct mac_learning *ml;
1315     struct netdev *of_device;
1316     struct rconn *controller;
1317     int n_queued;
1318 };
1319
1320 static void
1321 queue_tx(struct rconn *rc, struct in_band_data *in_band, struct ofpbuf *b)
1322 {
1323     rconn_send_with_limit(rc, b, &in_band->n_queued, 10);
1324 }
1325
1326 static const uint8_t *
1327 get_controller_mac(struct in_band_data *in_band)
1328 {
1329     static uint32_t ip, last_nonzero_ip;
1330     static uint8_t mac[ETH_ADDR_LEN], last_nonzero_mac[ETH_ADDR_LEN];
1331     static time_t next_refresh = 0;
1332
1333     uint32_t last_ip = ip;
1334
1335     time_t now = time_now();
1336
1337     ip = rconn_get_ip(in_band->controller);
1338     if (last_ip != ip || !next_refresh || now >= next_refresh) {
1339         bool have_mac;
1340
1341         /* Look up MAC address. */
1342         memset(mac, 0, sizeof mac);
1343         if (ip && in_band->of_device) {
1344             int retval = netdev_arp_lookup(in_band->of_device, ip, mac);
1345             if (retval) {
1346                 VLOG_DBG_RL(&vrl, "cannot look up controller hw address "
1347                             "("IP_FMT"): %s", IP_ARGS(&ip), strerror(retval));
1348             }
1349         }
1350         have_mac = !eth_addr_is_zero(mac);
1351
1352         /* Log changes in IP, MAC addresses. */
1353         if (ip && ip != last_nonzero_ip) {
1354             VLOG_DBG("controller IP address changed from "IP_FMT
1355                      " to "IP_FMT, IP_ARGS(&last_nonzero_ip), IP_ARGS(&ip));
1356             last_nonzero_ip = ip;
1357         }
1358         if (have_mac && memcmp(last_nonzero_mac, mac, ETH_ADDR_LEN)) {
1359             VLOG_DBG("controller MAC address changed from "ETH_ADDR_FMT" to "
1360                      ETH_ADDR_FMT,
1361                      ETH_ADDR_ARGS(last_nonzero_mac), ETH_ADDR_ARGS(mac));
1362             memcpy(last_nonzero_mac, mac, ETH_ADDR_LEN);
1363         }
1364
1365         /* Schedule next refresh.
1366          *
1367          * If we have an IP address but not a MAC address, then refresh
1368          * quickly, since we probably will get a MAC address soon (via ARP).
1369          * Otherwise, we can afford to wait a little while. */
1370         next_refresh = now + (!ip || have_mac ? 10 : 1);
1371     }
1372     return !eth_addr_is_zero(mac) ? mac : NULL;
1373 }
1374
1375 static bool
1376 is_controller_mac(const uint8_t dl_addr[ETH_ADDR_LEN],
1377                   struct in_band_data *in_band)
1378 {
1379     const uint8_t *mac = get_controller_mac(in_band);
1380     return mac && eth_addr_equals(mac, dl_addr);
1381 }
1382
1383 static void
1384 in_band_learn_mac(struct in_band_data *in_band,
1385                   uint16_t in_port, const uint8_t src_mac[ETH_ADDR_LEN])
1386 {
1387     if (mac_learning_learn(in_band->ml, src_mac, in_port)) {
1388         VLOG_DBG_RL(&vrl, "learned that "ETH_ADDR_FMT" is on port %"PRIu16,
1389                     ETH_ADDR_ARGS(src_mac), in_port);
1390     }
1391 }
1392
1393 static bool
1394 in_band_local_packet_cb(struct relay *r, void *in_band_)
1395 {
1396     struct in_band_data *in_band = in_band_;
1397     struct rconn *rc = r->halves[HALF_LOCAL].rconn;
1398     struct ofp_packet_in *opi;
1399     struct eth_header *eth;
1400     struct ofpbuf payload;
1401     struct flow flow;
1402     uint16_t in_port;
1403     int out_port;
1404
1405     if (!get_ofp_packet_eth_header(r, &opi, &eth) || !in_band->of_device) {
1406         return false;
1407     }
1408     in_port = ntohs(opi->in_port);
1409
1410     /* Deal with local stuff. */
1411     if (in_port == OFPP_LOCAL) {
1412         /* Sent by secure channel. */
1413         out_port = mac_learning_lookup(in_band->ml, eth->eth_dst);
1414     } else if (eth_addr_equals(eth->eth_dst,
1415                                netdev_get_etheraddr(in_band->of_device))) {
1416         /* Sent to secure channel. */
1417         out_port = OFPP_LOCAL;
1418         in_band_learn_mac(in_band, in_port, eth->eth_src);
1419     } else if (eth->eth_type == htons(ETH_TYPE_ARP)
1420                && eth_addr_is_broadcast(eth->eth_dst)
1421                && is_controller_mac(eth->eth_src, in_band)) {
1422         /* ARP sent by controller. */
1423         out_port = OFPP_FLOOD;
1424     } else if (is_controller_mac(eth->eth_dst, in_band)
1425                || is_controller_mac(eth->eth_src, in_band)) {
1426         /* Traffic to or from controller.  Switch it by hand. */
1427         in_band_learn_mac(in_band, in_port, eth->eth_src);
1428         out_port = mac_learning_lookup(in_band->ml, eth->eth_dst);
1429     } else {
1430         const uint8_t *controller_mac;
1431         controller_mac = get_controller_mac(in_band);
1432         if (eth->eth_type == htons(ETH_TYPE_ARP)
1433             && eth_addr_is_broadcast(eth->eth_dst)
1434             && is_controller_mac(eth->eth_src, in_band)) {
1435             /* ARP sent by controller. */
1436             out_port = OFPP_FLOOD;
1437         } else if (is_controller_mac(eth->eth_dst, in_band)
1438                    && in_port == mac_learning_lookup(in_band->ml,
1439                                                      controller_mac)) {
1440             /* Drop controller traffic that arrives on the controller port. */
1441             out_port = -1;
1442         } else {
1443             return false;
1444         }
1445     }
1446
1447     get_ofp_packet_payload(opi, &payload);
1448     flow_extract(&payload, in_port, &flow);
1449     if (in_port == out_port) {
1450         /* The input and output port match.  Set up a flow to drop packets. */
1451         queue_tx(rc, in_band, make_add_flow(&flow, ntohl(opi->buffer_id),
1452                                           in_band->s->max_idle, 0));
1453     } else if (out_port != OFPP_FLOOD) {
1454         /* The output port is known, so add a new flow. */
1455         queue_tx(rc, in_band,
1456                  make_add_simple_flow(&flow, ntohl(opi->buffer_id),
1457                                       out_port, in_band->s->max_idle));
1458
1459         /* If the switch didn't buffer the packet, we need to send a copy. */
1460         if (ntohl(opi->buffer_id) == UINT32_MAX) {
1461             queue_tx(rc, in_band,
1462                      make_unbuffered_packet_out(&payload, in_port, out_port));
1463         }
1464     } else {
1465         /* We don't know that MAC.  Send along the packet without setting up a
1466          * flow. */
1467         struct ofpbuf *b;
1468         if (ntohl(opi->buffer_id) == UINT32_MAX) {
1469             b = make_unbuffered_packet_out(&payload, in_port, out_port);
1470         } else {
1471             b = make_buffered_packet_out(ntohl(opi->buffer_id),
1472                                          in_port, out_port);
1473         }
1474         queue_tx(rc, in_band, b);
1475     }
1476     return true;
1477 }
1478
1479 static void
1480 in_band_status_cb(struct status_reply *sr, void *in_band_)
1481 {
1482     struct in_band_data *in_band = in_band_;
1483     struct in_addr local_ip;
1484     uint32_t controller_ip;
1485     const uint8_t *controller_mac;
1486
1487     if (in_band->of_device) {
1488         const uint8_t *mac = netdev_get_etheraddr(in_band->of_device);
1489         if (netdev_get_in4(in_band->of_device, &local_ip)) {
1490             status_reply_put(sr, "local-ip="IP_FMT, IP_ARGS(&local_ip.s_addr));
1491         }
1492         status_reply_put(sr, "local-mac="ETH_ADDR_FMT, ETH_ADDR_ARGS(mac));
1493
1494         controller_ip = rconn_get_ip(in_band->controller);
1495         if (controller_ip) {
1496             status_reply_put(sr, "controller-ip="IP_FMT,
1497                              IP_ARGS(&controller_ip));
1498         }
1499         controller_mac = get_controller_mac(in_band);
1500         if (controller_mac) {
1501             status_reply_put(sr, "controller-mac="ETH_ADDR_FMT,
1502                              ETH_ADDR_ARGS(controller_mac));
1503         }
1504     }
1505 }
1506
1507 static void
1508 get_ofp_packet_payload(struct ofp_packet_in *opi, struct ofpbuf *payload)
1509 {
1510     payload->data = opi->data;
1511     payload->size = ntohs(opi->header.length) - offsetof(struct ofp_packet_in,
1512                                                          data);
1513 }
1514
1515 static void
1516 in_band_local_port_cb(const struct ofp_phy_port *port, void *in_band_)
1517 {
1518     struct in_band_data *in_band = in_band_;
1519     if (port) {
1520         char name[sizeof port->name + 1];
1521         get_port_name(port, name, sizeof name);
1522
1523         if (!in_band->of_device
1524             || strcmp(netdev_get_name(in_band->of_device), name))
1525         {
1526             int error;
1527             netdev_close(in_band->of_device);
1528             error = netdev_open(name, NETDEV_ETH_TYPE_NONE,
1529                                 &in_band->of_device);
1530             if (error) {
1531                 VLOG_ERR("failed to open in-band control network device "
1532                          "\"%s\": %s", name, strerror(errno));
1533             }
1534         }
1535     } else {
1536         netdev_close(in_band->of_device);
1537         in_band->of_device = NULL;
1538     }
1539 }
1540
1541 static struct hook
1542 in_band_hook_create(const struct settings *s, struct switch_status *ss,
1543                     struct port_watcher *pw, struct rconn *remote)
1544 {
1545     struct in_band_data *in_band;
1546
1547     in_band = xcalloc(1, sizeof *in_band);
1548     in_band->s = s;
1549     in_band->ml = mac_learning_create();
1550     in_band->of_device = NULL;
1551     in_band->controller = remote;
1552     switch_status_register_category(ss, "in-band", in_band_status_cb, in_band);
1553     port_watcher_register_local_port_callback(pw, in_band_local_port_cb,
1554                                               in_band);
1555     return make_hook(in_band_local_packet_cb, NULL, NULL, NULL, in_band);
1556 }
1557 \f
1558 /* Fail open support. */
1559
1560 struct fail_open_data {
1561     const struct settings *s;
1562     struct rconn *local_rconn;
1563     struct rconn *remote_rconn;
1564     struct lswitch *lswitch;
1565     int last_disconn_secs;
1566     time_t boot_deadline;
1567 };
1568
1569 /* Causes 'r' to enter or leave fail-open mode, if appropriate. */
1570 static void
1571 fail_open_periodic_cb(void *fail_open_)
1572 {
1573     struct fail_open_data *fail_open = fail_open_;
1574     int disconn_secs;
1575     bool open;
1576
1577     if (time_now() < fail_open->boot_deadline) {
1578         return;
1579     }
1580     disconn_secs = rconn_disconnected_duration(fail_open->remote_rconn);
1581     open = disconn_secs >= fail_open->s->probe_interval * 3;
1582     if (open != (fail_open->lswitch != NULL)) {
1583         if (!open) {
1584             VLOG_WARN("No longer in fail-open mode");
1585             lswitch_destroy(fail_open->lswitch);
1586             fail_open->lswitch = NULL;
1587         } else {
1588             VLOG_WARN("Could not connect to controller for %d seconds, "
1589                       "failing open", disconn_secs);
1590             fail_open->lswitch = lswitch_create(fail_open->local_rconn, true,
1591                                                 fail_open->s->max_idle);
1592             fail_open->last_disconn_secs = disconn_secs;
1593         }
1594     } else if (open && disconn_secs > fail_open->last_disconn_secs + 60) {
1595         VLOG_WARN("Still in fail-open mode after %d seconds disconnected "
1596                   "from controller", disconn_secs);
1597         fail_open->last_disconn_secs = disconn_secs;
1598     }
1599 }
1600
1601 static bool
1602 fail_open_local_packet_cb(struct relay *r, void *fail_open_)
1603 {
1604     struct fail_open_data *fail_open = fail_open_;
1605     if (!fail_open->lswitch) {
1606         return false;
1607     } else {
1608         lswitch_process_packet(fail_open->lswitch, fail_open->local_rconn,
1609                                r->halves[HALF_LOCAL].rxbuf);
1610         rconn_run(fail_open->local_rconn);
1611         return true;
1612     }
1613 }
1614
1615 static void
1616 fail_open_status_cb(struct status_reply *sr, void *fail_open_)
1617 {
1618     struct fail_open_data *fail_open = fail_open_;
1619     const struct settings *s = fail_open->s;
1620     int trigger_duration = s->probe_interval * 3;
1621     int cur_duration = rconn_disconnected_duration(fail_open->remote_rconn);
1622
1623     status_reply_put(sr, "trigger-duration=%d", trigger_duration);
1624     status_reply_put(sr, "current-duration=%d", cur_duration);
1625     status_reply_put(sr, "triggered=%s",
1626                      cur_duration >= trigger_duration ? "true" : "false");
1627     status_reply_put(sr, "max-idle=%d", s->max_idle);
1628 }
1629
1630 static struct hook
1631 fail_open_hook_create(const struct settings *s, struct switch_status *ss,
1632                       struct rconn *local_rconn, struct rconn *remote_rconn)
1633 {
1634     struct fail_open_data *fail_open = xmalloc(sizeof *fail_open);
1635     fail_open->s = s;
1636     fail_open->local_rconn = local_rconn;
1637     fail_open->remote_rconn = remote_rconn;
1638     fail_open->lswitch = NULL;
1639     fail_open->boot_deadline = time_now() + s->probe_interval * 3;
1640     if (s->enable_stp) {
1641         fail_open->boot_deadline += STP_EXTRA_BOOT_TIME;
1642     }
1643     switch_status_register_category(ss, "fail-open",
1644                                     fail_open_status_cb, fail_open);
1645     return make_hook(fail_open_local_packet_cb, NULL,
1646                      fail_open_periodic_cb, NULL, fail_open);
1647 }
1648 \f
1649 struct rate_limiter {
1650     const struct settings *s;
1651     struct rconn *remote_rconn;
1652
1653     /* One queue per physical port. */
1654     struct ofp_queue queues[OFPP_MAX];
1655     int n_queued;               /* Sum over queues[*].n. */
1656     int next_tx_port;           /* Next port to check in round-robin. */
1657
1658     /* Token bucket.
1659      *
1660      * It costs 1000 tokens to send a single packet_in message.  A single token
1661      * per message would be more straightforward, but this choice lets us avoid
1662      * round-off error in refill_bucket()'s calculation of how many tokens to
1663      * add to the bucket, since no division step is needed. */
1664     long long int last_fill;    /* Time at which we last added tokens. */
1665     int tokens;                 /* Current number of tokens. */
1666
1667     /* Transmission queue. */
1668     int n_txq;                  /* No. of packets waiting in rconn for tx. */
1669
1670     /* Statistics reporting. */
1671     unsigned long long n_normal;        /* # txed w/o rate limit queuing. */
1672     unsigned long long n_limited;       /* # queued for rate limiting. */
1673     unsigned long long n_queue_dropped; /* # dropped due to queue overflow. */
1674     unsigned long long n_tx_dropped;    /* # dropped due to tx overflow. */
1675 };
1676
1677 /* Drop a packet from the longest queue in 'rl'. */
1678 static void
1679 drop_packet(struct rate_limiter *rl)
1680 {
1681     struct ofp_queue *longest;  /* Queue currently selected as longest. */
1682     int n_longest;              /* # of queues of same length as 'longest'. */
1683     struct ofp_queue *q;
1684
1685     longest = &rl->queues[0];
1686     n_longest = 1;
1687     for (q = &rl->queues[0]; q < &rl->queues[OFPP_MAX]; q++) {
1688         if (longest->n < q->n) {
1689             longest = q;
1690             n_longest = 1;
1691         } else if (longest->n == q->n) {
1692             n_longest++;
1693
1694             /* Randomly select one of the longest queues, with a uniform
1695              * distribution (Knuth algorithm 3.4.2R). */
1696             if (!random_range(n_longest)) {
1697                 longest = q;
1698             }
1699         }
1700     }
1701
1702     /* FIXME: do we want to pop the tail instead? */
1703     ofpbuf_delete(queue_pop_head(longest));
1704     rl->n_queued--;
1705 }
1706
1707 /* Remove and return the next packet to transmit (in round-robin order). */
1708 static struct ofpbuf *
1709 dequeue_packet(struct rate_limiter *rl)
1710 {
1711     unsigned int i;
1712
1713     for (i = 0; i < OFPP_MAX; i++) {
1714         unsigned int port = (rl->next_tx_port + i) % OFPP_MAX;
1715         struct ofp_queue *q = &rl->queues[port];
1716         if (q->n) {
1717             rl->next_tx_port = (port + 1) % OFPP_MAX;
1718             rl->n_queued--;
1719             return queue_pop_head(q);
1720         }
1721     }
1722     NOT_REACHED();
1723 }
1724
1725 /* Add tokens to the bucket based on elapsed time. */
1726 static void
1727 refill_bucket(struct rate_limiter *rl)
1728 {
1729     const struct settings *s = rl->s;
1730     long long int now = time_msec();
1731     long long int tokens = (now - rl->last_fill) * s->rate_limit + rl->tokens;
1732     if (tokens >= 1000) {
1733         rl->last_fill = now;
1734         rl->tokens = MIN(tokens, s->burst_limit * 1000);
1735     }
1736 }
1737
1738 /* Attempts to remove enough tokens from 'rl' to transmit a packet.  Returns
1739  * true if successful, false otherwise.  (In the latter case no tokens are
1740  * removed.) */
1741 static bool
1742 get_token(struct rate_limiter *rl)
1743 {
1744     if (rl->tokens >= 1000) {
1745         rl->tokens -= 1000;
1746         return true;
1747     } else {
1748         return false;
1749     }
1750 }
1751
1752 static bool
1753 rate_limit_local_packet_cb(struct relay *r, void *rl_)
1754 {
1755     struct rate_limiter *rl = rl_;
1756     const struct settings *s = rl->s;
1757     struct ofp_packet_in *opi;
1758
1759     opi = get_ofp_packet_in(r);
1760     if (!opi) {
1761         return false;
1762     }
1763
1764     if (!rl->n_queued && get_token(rl)) {
1765         /* In the common case where we are not constrained by the rate limit,
1766          * let the packet take the normal path. */
1767         rl->n_normal++;
1768         return false;
1769     } else {
1770         /* Otherwise queue it up for the periodic callback to drain out. */
1771         struct ofpbuf *msg = r->halves[HALF_LOCAL].rxbuf;
1772         int port = ntohs(opi->in_port) % OFPP_MAX;
1773         if (rl->n_queued >= s->burst_limit) {
1774             drop_packet(rl);
1775         }
1776         queue_push_tail(&rl->queues[port], ofpbuf_clone(msg));
1777         rl->n_queued++;
1778         rl->n_limited++;
1779         return true;
1780     }
1781 }
1782
1783 static void
1784 rate_limit_status_cb(struct status_reply *sr, void *rl_)
1785 {
1786     struct rate_limiter *rl = rl_;
1787
1788     status_reply_put(sr, "normal=%llu", rl->n_normal);
1789     status_reply_put(sr, "limited=%llu", rl->n_limited);
1790     status_reply_put(sr, "queue-dropped=%llu", rl->n_queue_dropped);
1791     status_reply_put(sr, "tx-dropped=%llu", rl->n_tx_dropped);
1792 }
1793
1794 static void
1795 rate_limit_periodic_cb(void *rl_)
1796 {
1797     struct rate_limiter *rl = rl_;
1798     int i;
1799
1800     /* Drain some packets out of the bucket if possible, but limit the number
1801      * of iterations to allow other code to get work done too. */
1802     refill_bucket(rl);
1803     for (i = 0; rl->n_queued && get_token(rl) && i < 50; i++) {
1804         /* Use a small, arbitrary limit for the amount of queuing to do here,
1805          * because the TCP connection is responsible for buffering and there is
1806          * no point in trying to transmit faster than the TCP connection can
1807          * handle. */
1808         struct ofpbuf *b = dequeue_packet(rl);
1809         if (rconn_send_with_limit(rl->remote_rconn, b, &rl->n_txq, 10)) {
1810             rl->n_tx_dropped++;
1811         }
1812     }
1813 }
1814
1815 static void
1816 rate_limit_wait_cb(void *rl_)
1817 {
1818     struct rate_limiter *rl = rl_;
1819     if (rl->n_queued) {
1820         if (rl->tokens >= 1000) {
1821             /* We can transmit more packets as soon as we're called again. */
1822             poll_immediate_wake();
1823         } else {
1824             /* We have to wait for the bucket to re-fill.  We could calculate
1825              * the exact amount of time here for increased smoothness. */
1826             poll_timer_wait(TIME_UPDATE_INTERVAL / 2);
1827         }
1828     }
1829 }
1830
1831 static struct hook
1832 rate_limit_hook_create(const struct settings *s, struct switch_status *ss,
1833                        struct rconn *local, struct rconn *remote)
1834 {
1835     struct rate_limiter *rl;
1836     size_t i;
1837
1838     rl = xcalloc(1, sizeof *rl);
1839     rl->s = s;
1840     rl->remote_rconn = remote;
1841     for (i = 0; i < ARRAY_SIZE(rl->queues); i++) {
1842         queue_init(&rl->queues[i]);
1843     }
1844     rl->last_fill = time_msec();
1845     rl->tokens = s->rate_limit * 100;
1846     switch_status_register_category(ss, "rate-limit",
1847                                     rate_limit_status_cb, rl);
1848     return make_hook(rate_limit_local_packet_cb, NULL, rate_limit_periodic_cb,
1849                      rate_limit_wait_cb, rl);
1850 }
1851 \f
1852 /* OFPST_SWITCH statistics. */
1853
1854 struct switch_status_category {
1855     char *name;
1856     void (*cb)(struct status_reply *, void *aux);
1857     void *aux;
1858 };
1859
1860 struct switch_status {
1861     const struct settings *s;
1862     time_t booted;
1863     struct switch_status_category categories[8];
1864     int n_categories;
1865 };
1866
1867 struct status_reply {
1868     struct switch_status_category *category;
1869     struct ds request;
1870     struct ds output;
1871 };
1872
1873 static bool
1874 switch_status_remote_packet_cb(struct relay *r, void *ss_)
1875 {
1876     struct switch_status *ss = ss_;
1877     struct rconn *rc = r->halves[HALF_REMOTE].rconn;
1878     struct ofpbuf *msg = r->halves[HALF_REMOTE].rxbuf;
1879     struct switch_status_category *c;
1880     struct nicira_header *request;
1881     struct nicira_header *reply;
1882     struct status_reply sr;
1883     struct ofpbuf *b;
1884     int retval;
1885
1886     if (msg->size < sizeof(struct nicira_header)) {
1887         return false;
1888     }
1889     request = msg->data;
1890     if (request->header.type != OFPT_VENDOR
1891         || request->vendor_id != htonl(NX_VENDOR_ID)
1892         || request->subtype != htonl(NXT_STATUS_REQUEST)) {
1893         return false;
1894     }
1895
1896     sr.request.string = (void *) (request + 1);
1897     sr.request.length = msg->size - sizeof *request;
1898     ds_init(&sr.output);
1899     for (c = ss->categories; c < &ss->categories[ss->n_categories]; c++) {
1900         if (!memcmp(c->name, sr.request.string,
1901                     MIN(strlen(c->name), sr.request.length))) {
1902             sr.category = c;
1903             c->cb(&sr, c->aux);
1904         }
1905     }
1906     reply = make_openflow_xid(sizeof *reply + sr.output.length,
1907                               OFPT_VENDOR, request->header.xid, &b);
1908     reply->vendor_id = htonl(NX_VENDOR_ID);
1909     reply->subtype = htonl(NXT_STATUS_REPLY);
1910     memcpy(reply + 1, sr.output.string, sr.output.length);
1911     retval = rconn_send(rc, b, NULL);
1912     if (retval && retval != EAGAIN) {
1913         VLOG_WARN("send failed (%s)", strerror(retval));
1914     }
1915     ds_destroy(&sr.output);
1916     return true;
1917 }
1918
1919 static void
1920 rconn_status_cb(struct status_reply *sr, void *rconn_)
1921 {
1922     struct rconn *rconn = rconn_;
1923     time_t now = time_now();
1924
1925     status_reply_put(sr, "name=%s", rconn_get_name(rconn));
1926     status_reply_put(sr, "state=%s", rconn_get_state(rconn));
1927     status_reply_put(sr, "backoff=%d", rconn_get_backoff(rconn));
1928     status_reply_put(sr, "is-connected=%s",
1929                      rconn_is_connected(rconn) ? "true" : "false");
1930     status_reply_put(sr, "sent-msgs=%u", rconn_packets_sent(rconn));
1931     status_reply_put(sr, "received-msgs=%u", rconn_packets_received(rconn));
1932     status_reply_put(sr, "attempted-connections=%u",
1933                      rconn_get_attempted_connections(rconn));
1934     status_reply_put(sr, "successful-connections=%u",
1935                      rconn_get_successful_connections(rconn));
1936     status_reply_put(sr, "last-connection=%ld",
1937                      (long int) (now - rconn_get_last_connection(rconn)));
1938     status_reply_put(sr, "time-connected=%lu",
1939                      rconn_get_total_time_connected(rconn));
1940     status_reply_put(sr, "state-elapsed=%u", rconn_get_state_elapsed(rconn));
1941 }
1942
1943 static void
1944 config_status_cb(struct status_reply *sr, void *s_)
1945 {
1946     const struct settings *s = s_;
1947     size_t i;
1948
1949     for (i = 0; i < s->n_listeners; i++) {
1950         status_reply_put(sr, "management%zu=%s", i, s->listener_names[i]);
1951     }
1952     if (s->probe_interval) {
1953         status_reply_put(sr, "probe-interval=%d", s->probe_interval);
1954     }
1955     if (s->max_backoff) {
1956         status_reply_put(sr, "max-backoff=%d", s->max_backoff);
1957     }
1958 }
1959
1960 static void
1961 switch_status_cb(struct status_reply *sr, void *ss_)
1962 {
1963     struct switch_status *ss = ss_;
1964     time_t now = time_now();
1965
1966     status_reply_put(sr, "now=%ld", (long int) now);
1967     status_reply_put(sr, "uptime=%ld", (long int) (now - ss->booted));
1968     status_reply_put(sr, "pid=%ld", (long int) getpid());
1969 }
1970
1971 static struct hook
1972 switch_status_hook_create(const struct settings *s, struct switch_status **ssp)
1973 {
1974     struct switch_status *ss = xcalloc(1, sizeof *ss);
1975     ss->s = s;
1976     ss->booted = time_now();
1977     switch_status_register_category(ss, "config",
1978                                     config_status_cb, (void *) s);
1979     switch_status_register_category(ss, "switch", switch_status_cb, ss);
1980     *ssp = ss;
1981     return make_hook(NULL, switch_status_remote_packet_cb, NULL, NULL, ss);
1982 }
1983
1984 static void
1985 switch_status_register_category(struct switch_status *ss,
1986                                 const char *category,
1987                                 void (*cb)(struct status_reply *,
1988                                            void *aux),
1989                                 void *aux)
1990 {
1991     struct switch_status_category *c;
1992     assert(ss->n_categories < ARRAY_SIZE(ss->categories));
1993     c = &ss->categories[ss->n_categories++];
1994     c->cb = cb;
1995     c->aux = aux;
1996     c->name = xstrdup(category);
1997 }
1998
1999 static void
2000 status_reply_put(struct status_reply *sr, const char *content, ...)
2001 {
2002     size_t old_length = sr->output.length;
2003     size_t added;
2004     va_list args;
2005
2006     /* Append the status reply to the output. */
2007     ds_put_format(&sr->output, "%s.", sr->category->name);
2008     va_start(args, content);
2009     ds_put_format_valist(&sr->output, content, args);
2010     va_end(args);
2011     if (ds_last(&sr->output) != '\n') {
2012         ds_put_char(&sr->output, '\n');
2013     }
2014
2015     /* Drop what we just added if it doesn't match the request. */
2016     added = sr->output.length - old_length;
2017     if (added < sr->request.length
2018         || memcmp(&sr->output.string[old_length],
2019                   sr->request.string, sr->request.length)) {
2020         ds_truncate(&sr->output, old_length);
2021     }
2022 }
2023
2024 \f
2025 /* Controller discovery. */
2026
2027 struct discovery
2028 {
2029     const struct settings *s;
2030     struct dhclient *dhcp;
2031     int n_changes;
2032 };
2033
2034 static void
2035 discovery_status_cb(struct status_reply *sr, void *d_)
2036 {
2037     struct discovery *d = d_;
2038
2039     status_reply_put(sr, "accept-remote=%s", d->s->accept_controller_re);
2040     status_reply_put(sr, "n-changes=%d", d->n_changes);
2041     if (d->dhcp) {
2042         status_reply_put(sr, "state=%s", dhclient_get_state(d->dhcp));
2043         status_reply_put(sr, "state-elapsed=%u",
2044                          dhclient_get_state_elapsed(d->dhcp)); 
2045         if (dhclient_is_bound(d->dhcp)) {
2046             uint32_t ip = dhclient_get_ip(d->dhcp);
2047             uint32_t netmask = dhclient_get_netmask(d->dhcp);
2048             uint32_t router = dhclient_get_router(d->dhcp);
2049
2050             const struct dhcp_msg *cfg = dhclient_get_config(d->dhcp);
2051             uint32_t dns_server;
2052             char *domain_name;
2053             int i;
2054
2055             status_reply_put(sr, "ip="IP_FMT, IP_ARGS(&ip));
2056             status_reply_put(sr, "netmask="IP_FMT, IP_ARGS(&netmask));
2057             if (router) {
2058                 status_reply_put(sr, "router="IP_FMT, IP_ARGS(&router));
2059             }
2060
2061             for (i = 0; dhcp_msg_get_ip(cfg, DHCP_CODE_DNS_SERVER, i,
2062                                         &dns_server);
2063                  i++) {
2064                 status_reply_put(sr, "dns%d="IP_FMT, i, IP_ARGS(&dns_server));
2065             }
2066
2067             domain_name = dhcp_msg_get_string(cfg, DHCP_CODE_DOMAIN_NAME);
2068             if (domain_name) {
2069                 status_reply_put(sr, "domain=%s", domain_name);
2070                 free(domain_name);
2071             }
2072
2073             status_reply_put(sr, "lease-remaining=%u",
2074                              dhclient_get_lease_remaining(d->dhcp));
2075         }
2076     }
2077 }
2078
2079 static void
2080 discovery_local_port_cb(const struct ofp_phy_port *port, void *d_) 
2081 {
2082     struct discovery *d = d_;
2083     if (port) {
2084         char name[OFP_MAX_PORT_NAME_LEN + 1];
2085         struct netdev *netdev;
2086         int retval;
2087
2088         /* Check that this was really a change. */
2089         get_port_name(port, name, sizeof name);
2090         if (d->dhcp && !strcmp(netdev_get_name(dhclient_get_netdev(d->dhcp)),
2091                                name)) {
2092             return;
2093         }
2094
2095         /* Destroy current DHCP client. */
2096         dhclient_destroy(d->dhcp);
2097         d->dhcp = NULL;
2098
2099         /* Bring local network device up. */
2100         retval = netdev_open(name, NETDEV_ETH_TYPE_NONE, &netdev);
2101         if (retval) {
2102             VLOG_ERR("Could not open %s device, discovery disabled: %s",
2103                      name, strerror(retval));
2104             return;
2105         }
2106         retval = netdev_turn_flags_on(netdev, NETDEV_UP, true);
2107         if (retval) {
2108             VLOG_ERR("Could not bring %s device up, discovery disabled: %s",
2109                      name, strerror(retval));
2110             return;
2111         }
2112         netdev_close(netdev);
2113
2114         /* Initialize DHCP client. */
2115         retval = dhclient_create(name, modify_dhcp_request,
2116                                  validate_dhcp_offer, (void *) d->s, &d->dhcp);
2117         if (retval) {
2118             VLOG_ERR("Failed to initialize DHCP client, "
2119                      "discovery disabled: %s", strerror(retval));
2120             return;
2121         }
2122         dhclient_init(d->dhcp, 0);
2123     } else {
2124         dhclient_destroy(d->dhcp);
2125         d->dhcp = NULL;
2126     }
2127 }
2128
2129
2130 static struct discovery *
2131 discovery_init(const struct settings *s, struct port_watcher *pw,
2132                struct switch_status *ss)
2133 {
2134     struct discovery *d;
2135
2136     d = xmalloc(sizeof *d);
2137     d->s = s;
2138     d->dhcp = NULL;
2139     d->n_changes = 0;
2140
2141     switch_status_register_category(ss, "discovery", discovery_status_cb, d);
2142     port_watcher_register_local_port_callback(pw, discovery_local_port_cb, d);
2143
2144     return d;
2145 }
2146
2147 static void
2148 discovery_question_connectivity(struct discovery *d)
2149 {
2150     if (d->dhcp) {
2151         dhclient_force_renew(d->dhcp, 15); 
2152     }
2153 }
2154
2155 static bool
2156 discovery_run(struct discovery *d, char **controller_name)
2157 {
2158     if (!d->dhcp) {
2159         *controller_name = NULL;
2160         return true;
2161     }
2162
2163     dhclient_run(d->dhcp);
2164     if (!dhclient_changed(d->dhcp)) {
2165         return false;
2166     }
2167
2168     dhclient_configure_netdev(d->dhcp);
2169     if (d->s->update_resolv_conf) {
2170         dhclient_update_resolv_conf(d->dhcp);
2171     }
2172
2173     if (dhclient_is_bound(d->dhcp)) {
2174         *controller_name = dhcp_msg_get_string(dhclient_get_config(d->dhcp),
2175                                                DHCP_CODE_OFP_CONTROLLER_VCONN);
2176         VLOG_WARN("%s: discovered controller", *controller_name);
2177         d->n_changes++;
2178     } else {
2179         *controller_name = NULL;
2180         if (d->n_changes) {
2181             VLOG_WARN("discovered controller no longer available");
2182             d->n_changes++;
2183         }
2184     }
2185     return true;
2186 }
2187
2188 static void
2189 discovery_wait(struct discovery *d)
2190 {
2191     if (d->dhcp) {
2192         dhclient_wait(d->dhcp); 
2193     }
2194 }
2195
2196 static void
2197 modify_dhcp_request(struct dhcp_msg *msg, void *aux)
2198 {
2199     dhcp_msg_put_string(msg, DHCP_CODE_VENDOR_CLASS, "OpenFlow");
2200 }
2201
2202 static bool
2203 validate_dhcp_offer(const struct dhcp_msg *msg, void *s_)
2204 {
2205     const struct settings *s = s_;
2206     char *vconn_name;
2207     bool accept;
2208
2209     vconn_name = dhcp_msg_get_string(msg, DHCP_CODE_OFP_CONTROLLER_VCONN);
2210     if (!vconn_name) {
2211         VLOG_WARN_RL(&vrl, "rejecting DHCP offer missing controller vconn");
2212         return false;
2213     }
2214     accept = !regexec(&s->accept_controller_regex, vconn_name, 0, NULL, 0);
2215     if (!accept) {
2216         VLOG_WARN_RL(&vrl, "rejecting controller vconn that fails to match %s",
2217                      s->accept_controller_re);
2218     }
2219     free(vconn_name);
2220     return accept;
2221 }
2222 \f
2223 /* User interface. */
2224
2225 static void
2226 parse_options(int argc, char *argv[], struct settings *s)
2227 {
2228     enum {
2229         OPT_ACCEPT_VCONN = UCHAR_MAX + 1,
2230         OPT_NO_RESOLV_CONF,
2231         OPT_INACTIVITY_PROBE,
2232         OPT_MAX_IDLE,
2233         OPT_MAX_BACKOFF,
2234         OPT_RATE_LIMIT,
2235         OPT_BURST_LIMIT,
2236         OPT_BOOTSTRAP_CA_CERT,
2237         OPT_STP,
2238         OPT_NO_STP,
2239         OPT_OUT_OF_BAND,
2240         OPT_IN_BAND
2241     };
2242     static struct option long_options[] = {
2243         {"accept-vconn", required_argument, 0, OPT_ACCEPT_VCONN},
2244         {"no-resolv-conf", no_argument, 0, OPT_NO_RESOLV_CONF},
2245         {"fail",        required_argument, 0, 'F'},
2246         {"inactivity-probe", required_argument, 0, OPT_INACTIVITY_PROBE},
2247         {"max-idle",    required_argument, 0, OPT_MAX_IDLE},
2248         {"max-backoff", required_argument, 0, OPT_MAX_BACKOFF},
2249         {"listen",      required_argument, 0, 'l'},
2250         {"monitor",     required_argument, 0, 'm'},
2251         {"rate-limit",  optional_argument, 0, OPT_RATE_LIMIT},
2252         {"burst-limit", required_argument, 0, OPT_BURST_LIMIT},
2253         {"stp",         no_argument, 0, OPT_STP},
2254         {"no-stp",      no_argument, 0, OPT_NO_STP},
2255         {"out-of-band", no_argument, 0, OPT_OUT_OF_BAND},
2256         {"in-band",     no_argument, 0, OPT_IN_BAND},
2257         {"detach",      no_argument, 0, 'D'},
2258         {"force",       no_argument, 0, 'f'},
2259         {"pidfile",     optional_argument, 0, 'P'},
2260         {"verbose",     optional_argument, 0, 'v'},
2261         {"help",        no_argument, 0, 'h'},
2262         {"version",     no_argument, 0, 'V'},
2263 #ifdef HAVE_OPENSSL
2264         VCONN_SSL_LONG_OPTIONS
2265         {"bootstrap-ca-cert", required_argument, 0, OPT_BOOTSTRAP_CA_CERT},
2266 #endif
2267         {0, 0, 0, 0},
2268     };
2269     char *short_options = long_options_to_short_options(long_options);
2270     char *accept_re = NULL;
2271     int retval;
2272
2273     /* Set defaults that we can figure out before parsing options. */
2274     s->n_listeners = 0;
2275     s->monitor_name = NULL;
2276     s->fail_mode = FAIL_OPEN;
2277     s->max_idle = 15;
2278     s->probe_interval = 15;
2279     s->max_backoff = 15;
2280     s->update_resolv_conf = true;
2281     s->rate_limit = 0;
2282     s->burst_limit = 0;
2283     s->enable_stp = false;
2284     s->in_band = true;
2285     for (;;) {
2286         int c;
2287
2288         c = getopt_long(argc, argv, short_options, long_options, NULL);
2289         if (c == -1) {
2290             break;
2291         }
2292
2293         switch (c) {
2294         case OPT_ACCEPT_VCONN:
2295             accept_re = optarg[0] == '^' ? optarg : xasprintf("^%s", optarg);
2296             break;
2297
2298         case OPT_NO_RESOLV_CONF:
2299             s->update_resolv_conf = false;
2300             break;
2301
2302         case 'F':
2303             if (!strcmp(optarg, "open")) {
2304                 s->fail_mode = FAIL_OPEN;
2305             } else if (!strcmp(optarg, "closed")) {
2306                 s->fail_mode = FAIL_CLOSED;
2307             } else {
2308                 ofp_fatal(0, "-f or --fail argument must be \"open\" "
2309                           "or \"closed\"");
2310             }
2311             break;
2312
2313         case OPT_INACTIVITY_PROBE:
2314             s->probe_interval = atoi(optarg);
2315             if (s->probe_interval < 5) {
2316                 ofp_fatal(0, "--inactivity-probe argument must be at least 5");
2317             }
2318             break;
2319
2320         case OPT_MAX_IDLE:
2321             if (!strcmp(optarg, "permanent")) {
2322                 s->max_idle = OFP_FLOW_PERMANENT;
2323             } else {
2324                 s->max_idle = atoi(optarg);
2325                 if (s->max_idle < 1 || s->max_idle > 65535) {
2326                     ofp_fatal(0, "--max-idle argument must be between 1 and "
2327                               "65535 or the word 'permanent'");
2328                 }
2329             }
2330             break;
2331
2332         case OPT_MAX_BACKOFF:
2333             s->max_backoff = atoi(optarg);
2334             if (s->max_backoff < 1) {
2335                 ofp_fatal(0, "--max-backoff argument must be at least 1");
2336             } else if (s->max_backoff > 3600) {
2337                 s->max_backoff = 3600;
2338             }
2339             break;
2340
2341         case OPT_RATE_LIMIT:
2342             if (optarg) {
2343                 s->rate_limit = atoi(optarg);
2344                 if (s->rate_limit < 1) {
2345                     ofp_fatal(0, "--rate-limit argument must be at least 1");
2346                 }
2347             } else {
2348                 s->rate_limit = 1000;
2349             }
2350             break;
2351
2352         case OPT_BURST_LIMIT:
2353             s->burst_limit = atoi(optarg);
2354             if (s->burst_limit < 1) {
2355                 ofp_fatal(0, "--burst-limit argument must be at least 1");
2356             }
2357             break;
2358
2359         case OPT_STP:
2360             s->enable_stp = true;
2361             break;
2362
2363         case OPT_NO_STP:
2364             s->enable_stp = false;
2365             break;
2366
2367         case OPT_OUT_OF_BAND:
2368             s->in_band = false;
2369             break;
2370
2371         case OPT_IN_BAND:
2372             s->in_band = true;
2373             break;
2374
2375         case 'D':
2376             set_detach();
2377             break;
2378
2379         case 'P':
2380             set_pidfile(optarg);
2381             break;
2382
2383         case 'f':
2384             ignore_existing_pidfile();
2385             break;
2386
2387         case 'l':
2388             if (s->n_listeners >= MAX_MGMT) {
2389                 ofp_fatal(0,
2390                           "-l or --listen may be specified at most %d times",
2391                           MAX_MGMT);
2392             }
2393             s->listener_names[s->n_listeners++] = optarg;
2394             break;
2395
2396         case 'm':
2397             if (s->monitor_name) {
2398                 ofp_fatal(0, "-m or --monitor may only be specified once");
2399             }
2400             s->monitor_name = optarg;
2401             break;
2402
2403         case 'h':
2404             usage();
2405
2406         case 'V':
2407             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
2408             exit(EXIT_SUCCESS);
2409
2410         case 'v':
2411             vlog_set_verbosity(optarg);
2412             break;
2413
2414 #ifdef HAVE_OPENSSL
2415         VCONN_SSL_OPTION_HANDLERS
2416
2417         case OPT_BOOTSTRAP_CA_CERT:
2418             vconn_ssl_set_ca_cert_file(optarg, true);
2419             break;
2420 #endif
2421
2422         case '?':
2423             exit(EXIT_FAILURE);
2424
2425         default:
2426             abort();
2427         }
2428     }
2429     free(short_options);
2430
2431     argc -= optind;
2432     argv += optind;
2433     if (argc < 1 || argc > 2) {
2434         ofp_fatal(0, "need one or two non-option arguments; "
2435                   "use --help for usage");
2436     }
2437
2438     /* Local and remote vconns. */
2439     s->dp_name = argv[0];
2440     s->controller_name = argc > 1 ? xstrdup(argv[1]) : NULL;
2441
2442     /* Set accept_controller_regex. */
2443     if (!accept_re) {
2444         accept_re = vconn_ssl_is_configured() ? "^ssl:.*" : ".*";
2445     }
2446     retval = regcomp(&s->accept_controller_regex, accept_re,
2447                      REG_NOSUB | REG_EXTENDED);
2448     if (retval) {
2449         size_t length = regerror(retval, &s->accept_controller_regex, NULL, 0);
2450         char *buffer = xmalloc(length);
2451         regerror(retval, &s->accept_controller_regex, buffer, length);
2452         ofp_fatal(0, "%s: %s", accept_re, buffer);
2453     }
2454     s->accept_controller_re = accept_re;
2455
2456     /* Mode of operation. */
2457     s->discovery = s->controller_name == NULL;
2458     if (s->discovery && !s->in_band) {
2459         ofp_fatal(0, "Cannot perform discovery with out-of-band control");
2460     }
2461
2462     /* Rate limiting. */
2463     if (s->rate_limit) {
2464         if (s->rate_limit < 100) {
2465             VLOG_WARN("Rate limit set to unusually low value %d",
2466                       s->rate_limit);
2467         }
2468         if (!s->burst_limit) {
2469             s->burst_limit = s->rate_limit / 4;
2470         }
2471         s->burst_limit = MAX(s->burst_limit, 1);
2472         s->burst_limit = MIN(s->burst_limit, INT_MAX / 1000);
2473     }
2474 }
2475
2476 static void
2477 usage(void)
2478 {
2479     printf("%s: secure channel, a relay for OpenFlow messages.\n"
2480            "usage: %s [OPTIONS] nl:DP_IDX [CONTROLLER]\n"
2481            "where nl:DP_IDX is a datapath that has been added with dpctl.\n"
2482            "CONTROLLER is an active OpenFlow connection method; if it is\n"
2483            "omitted, then secchan performs controller discovery.\n",
2484            program_name, program_name);
2485     vconn_usage(true, true, true);
2486     printf("\nController discovery options:\n"
2487            "  --accept-vconn=REGEX    accept matching discovered controllers\n"
2488            "  --no-resolv-conf        do not update /etc/resolv.conf\n"
2489            "\nNetworking options:\n"
2490            "  -F, --fail=open|closed  when controller connection fails:\n"
2491            "                            closed: drop all packets\n"
2492            "                            open (default): act as learning switch\n"
2493            "  --inactivity-probe=SECS time between inactivity probes\n"
2494            "  --max-idle=SECS         max idle for flows set up by secchan\n"
2495            "  --max-backoff=SECS      max time between controller connection\n"
2496            "                          attempts (default: 15 seconds)\n"
2497            "  -l, --listen=METHOD     allow management connections on METHOD\n"
2498            "                          (a passive OpenFlow connection method)\n"
2499            "  -m, --monitor=METHOD    copy traffic to/from kernel to METHOD\n"
2500            "                          (a passive OpenFlow connection method)\n"
2501            "  --out-of-band           controller connection is out-of-band\n"
2502            "  --stp                   enable 802.1D Spanning Tree Protocol\n"
2503            "  --no-stp                disable 802.1D Spanning Tree Protocol\n"
2504            "\nRate-limiting of \"packet-in\" messages to the controller:\n"
2505            "  --rate-limit[=PACKETS]  max rate, in packets/s (default: 1000)\n"
2506            "  --burst-limit=BURST     limit on packet credit for idle time\n"
2507            "\nOther options:\n"
2508            "  -D, --detach            run in background as daemon\n"
2509            "  -P, --pidfile[=FILE]    create pidfile (default: %s/secchan.pid)\n"
2510            "  -f, --force             with -P, start even if already running\n"
2511            "  -v, --verbose=MODULE[:FACILITY[:LEVEL]]  set logging levels\n"
2512            "  -v, --verbose           set maximum verbosity level\n"
2513            "  -h, --help              display this help message\n"
2514            "  -V, --version           display version information\n",
2515            RUNDIR);
2516     exit(EXIT_SUCCESS);
2517 }