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