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