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