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