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