Merge "master" into "wdp".
[sliver-openvswitch.git] / ofproto / in-band.c
1 /*
2  * Copyright (c) 2008, 2009, 2010 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "in-band.h"
19 #include <arpa/inet.h>
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <net/if.h>
23 #include <string.h>
24 #include <stdlib.h>
25 #include "dhcp.h"
26 #include "flow.h"
27 #include "netdev.h"
28 #include "ofproto.h"
29 #include "ofpbuf.h"
30 #include "openflow/openflow.h"
31 #include "packets.h"
32 #include "poll-loop.h"
33 #include "status.h"
34 #include "timeval.h"
35 #include "wdp.h"
36
37 #define THIS_MODULE VLM_in_band
38 #include "vlog.h"
39
40 /* In-band control allows a single network to be used for OpenFlow
41  * traffic and other data traffic.  Refer to ovs-vswitchd.conf(5) and 
42  * secchan(8) for a description of configuring in-band control.
43  *
44  * This comment is an attempt to describe how in-band control works at a
45  * wire- and implementation-level.  Correctly implementing in-band
46  * control has proven difficult due to its many subtleties, and has thus
47  * gone through many iterations.  Please read through and understand the
48  * reasoning behind the chosen rules before making modifications.
49  *
50  * In Open vSwitch, in-band control is implemented as "hidden" flows (in that
51  * they are not visible through OpenFlow) and at a higher priority than
52  * wildcarded flows can be set up by through OpenFlow.  This is done so that
53  * the OpenFlow controller cannot interfere with them and possibly break
54  * connectivity with its switches.  It is possible to see all flows, including
55  * in-band ones, with the ovs-appctl "bridge/dump-flows" command.
56  *
57  * The Open vSwitch implementation of in-band control can hide traffic to
58  * arbitrary "remotes", where each remote is one TCP port on one IP address.
59  * Currently the remotes are automatically configured as the in-band OpenFlow
60  * controllers plus the OVSDB managers, if any.  (The latter is a requirement
61  * because OVSDB managers are responsible for configuring OpenFlow controllers,
62  * so if the manager cannot be reached then OpenFlow cannot be reconfigured.)
63  *
64  * The following rules (with the OFPP_NORMAL action) are set up on any bridge
65  * that has any remotes:
66  *
67  *    (a) DHCP requests sent from the local port.
68  *    (b) ARP replies to the local port's MAC address.
69  *    (c) ARP requests from the local port's MAC address.
70  *
71  * In-band also sets up the following rules for each unique next-hop MAC
72  * address for the remotes' IPs (the "next hop" is either the remote
73  * itself, if it is on a local subnet, or the gateway to reach the remote):
74  * 
75  *    (d) ARP replies to the next hop's MAC address.
76  *    (e) ARP requests from the next hop's MAC address.
77  *
78  * In-band also sets up the following rules for each unique remote IP address:
79  *
80  *    (f) ARP replies containing the remote's IP address as a target.
81  *    (g) ARP requests containing the remote's IP address as a source.
82  *
83  * In-band also sets up the following rules for each unique remote (IP,port)
84  * pair:
85  *
86  *    (h) TCP traffic to the remote's IP and port.
87  *    (i) TCP traffic from the remote's IP and port.
88  *
89  * The goal of these rules is to be as narrow as possible to allow a
90  * switch to join a network and be able to communicate with the
91  * remotes.  As mentioned earlier, these rules have higher priority
92  * than the controller's rules, so if they are too broad, they may 
93  * prevent the controller from implementing its policy.  As such,
94  * in-band actively monitors some aspects of flow and packet processing
95  * so that the rules can be made more precise.
96  *
97  * In-band control monitors attempts to add flows into the datapath that
98  * could interfere with its duties.  The datapath only allows exact
99  * match entries, so in-band control is able to be very precise about
100  * the flows it prevents.  Flows that miss in the datapath are sent to
101  * userspace to be processed, so preventing these flows from being
102  * cached in the "fast path" does not affect correctness.  The only type 
103  * of flow that is currently prevented is one that would prevent DHCP 
104  * replies from being seen by the local port.  For example, a rule that 
105  * forwarded all DHCP traffic to the controller would not be allowed, 
106  * but one that forwarded to all ports (including the local port) would.
107  *
108  * As mentioned earlier, packets that miss in the datapath are sent to
109  * the userspace for processing.  The userspace has its own flow table,
110  * the "classifier", so in-band checks whether any special processing 
111  * is needed before the classifier is consulted.  If a packet is a DHCP 
112  * response to a request from the local port, the packet is forwarded to 
113  * the local port, regardless of the flow table.  Note that this requires 
114  * L7 processing of DHCP replies to determine whether the 'chaddr' field 
115  * matches the MAC address of the local port.
116  *
117  * It is interesting to note that for an L3-based in-band control
118  * mechanism, the majority of rules are devoted to ARP traffic.  At first 
119  * glance, some of these rules appear redundant.  However, each serves an 
120  * important role.  First, in order to determine the MAC address of the 
121  * remote side (controller or gateway) for other ARP rules, we must allow 
122  * ARP traffic for our local port with rules (b) and (c).  If we are 
123  * between a switch and its connection to the remote, we have to 
124  * allow the other switch's ARP traffic to through.  This is done with 
125  * rules (d) and (e), since we do not know the addresses of the other
126  * switches a priori, but do know the remote's or gateway's.  Finally, 
127  * if the remote is running in a local guest VM that is not reached 
128  * through the local port, the switch that is connected to the VM must 
129  * allow ARP traffic based on the remote's IP address, since it will 
130  * not know the MAC address of the local port that is sending the traffic 
131  * or the MAC address of the remote in the guest VM.
132  *
133  * With a few notable exceptions below, in-band should work in most
134  * network setups.  The following are considered "supported' in the
135  * current implementation: 
136  *
137  *    - Locally Connected.  The switch and remote are on the same
138  *      subnet.  This uses rules (a), (b), (c), (h), and (i).
139  *
140  *    - Reached through Gateway.  The switch and remote are on
141  *      different subnets and must go through a gateway.  This uses
142  *      rules (a), (b), (c), (h), and (i).
143  *
144  *    - Between Switch and Remote.  This switch is between another
145  *      switch and the remote, and we want to allow the other
146  *      switch's traffic through.  This uses rules (d), (e), (h), and
147  *      (i).  It uses (b) and (c) indirectly in order to know the MAC
148  *      address for rules (d) and (e).  Note that DHCP for the other
149  *      switch will not work unless an OpenFlow controller explicitly lets this
150  *      switch pass the traffic.
151  *
152  *    - Between Switch and Gateway.  This switch is between another
153  *      switch and the gateway, and we want to allow the other switch's
154  *      traffic through.  This uses the same rules and logic as the
155  *      "Between Switch and Remote" configuration described earlier.
156  *
157  *    - Remote on Local VM.  The remote is a guest VM on the
158  *      system running in-band control.  This uses rules (a), (b), (c), 
159  *      (h), and (i).
160  *
161  *    - Remote on Local VM with Different Networks.  The remote
162  *      is a guest VM on the system running in-band control, but the
163  *      local port is not used to connect to the remote.  For
164  *      example, an IP address is configured on eth0 of the switch.  The
165  *      remote's VM is connected through eth1 of the switch, but an
166  *      IP address has not been configured for that port on the switch.
167  *      As such, the switch will use eth0 to connect to the remote,
168  *      and eth1's rules about the local port will not work.  In the
169  *      example, the switch attached to eth0 would use rules (a), (b), 
170  *      (c), (h), and (i) on eth0.  The switch attached to eth1 would use 
171  *      rules (f), (g), (h), and (i).
172  *
173  * The following are explicitly *not* supported by in-band control:
174  *
175  *    - Specify Remote by Name.  Currently, the remote must be 
176  *      identified by IP address.  A naive approach would be to permit
177  *      all DNS traffic.  Unfortunately, this would prevent the
178  *      controller from defining any policy over DNS.  Since switches
179  *      that are located behind us need to connect to the remote, 
180  *      in-band cannot simply add a rule that allows DNS traffic from
181  *      the local port.  The "correct" way to support this is to parse
182  *      DNS requests to allow all traffic related to a request for the
183  *      remote's name through.  Due to the potential security
184  *      problems and amount of processing, we decided to hold off for
185  *      the time-being.
186  *
187  *    - Differing Remotes for Switches.  All switches must know
188  *      the L3 addresses for all the remotes that other switches 
189  *      may use, since rules need to be set up to allow traffic related
190  *      to those remotes through.  See rules (f), (g), (h), and (i).
191  *
192  *    - Differing Routes for Switches.  In order for the switch to 
193  *      allow other switches to connect to a remote through a 
194  *      gateway, it allows the gateway's traffic through with rules (d)
195  *      and (e).  If the routes to the remote differ for the two
196  *      switches, we will not know the MAC address of the alternate 
197  *      gateway.
198  */
199
200 /* Priorities used in classifier for in-band rules.  These values are higher
201  * than any that may be set with OpenFlow, and "18" kind of looks like "IB".
202  * The ordering of priorities is not important because all of the rules set up
203  * by in-band control have the same action.  The only reason to use more than
204  * one priority is to make the kind of flow easier to see during debugging. */
205 enum {
206     /* One set per bridge. */
207     IBR_FROM_LOCAL_DHCP = 180000, /* (a) From local port, DHCP. */
208     IBR_TO_LOCAL_ARP,             /* (b) To local port, ARP. */
209     IBR_FROM_LOCAL_ARP,           /* (c) From local port, ARP. */
210
211     /* One set per unique next-hop MAC. */
212     IBR_TO_NEXT_HOP_ARP,          /* (d) To remote MAC, ARP. */
213     IBR_FROM_NEXT_HOP_ARP,        /* (e) From remote MAC, ARP. */
214
215     /* One set per unique remote IP address. */
216     IBR_TO_REMOTE_ARP,            /* (f) To remote IP, ARP. */
217     IBR_FROM_REMOTE_ARP,          /* (g) From remote IP, ARP. */
218
219     /* One set per unique remote (IP,port) pair. */
220     IBR_TO_REMOTE_TCP,            /* (h) To remote IP, TCP port. */
221     IBR_FROM_REMOTE_TCP           /* (i) From remote IP, TCP port. */
222 };
223
224 struct in_band_rule {
225     flow_t flow;
226 };
227
228 /* Track one remote IP and next hop information. */
229 struct in_band_remote {
230     struct sockaddr_in remote_addr; /* IP address, in network byte order. */
231     uint8_t remote_mac[ETH_ADDR_LEN]; /* Next-hop MAC, all-zeros if unknown. */
232     uint8_t last_remote_mac[ETH_ADDR_LEN]; /* Previous nonzero next-hop MAC. */
233     struct netdev *remote_netdev; /* Device to send to next-hop MAC. */
234 };
235
236 struct in_band {
237     struct ofproto *ofproto;
238     struct status_category *ss_cat;
239
240     /* Remote information. */
241     time_t next_remote_refresh; /* Refresh timer. */
242     struct in_band_remote *remotes;
243     size_t n_remotes;
244
245     /* Local information. */
246     time_t next_local_refresh;       /* Refresh timer. */
247     uint8_t local_mac[ETH_ADDR_LEN]; /* Current MAC. */
248     struct netdev *local_netdev;     /* Local port's network device. */
249
250     /* Local and remote addresses that are installed as flows. */
251     uint8_t installed_local_mac[ETH_ADDR_LEN];
252     struct sockaddr_in *remote_addrs;
253     size_t n_remote_addrs;
254     uint8_t *remote_macs;
255     size_t n_remote_macs;
256 };
257
258 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 60);
259
260 static int
261 refresh_remote(struct in_band *ib, struct in_band_remote *r)
262 {
263     struct in_addr next_hop_inaddr;
264     char *next_hop_dev;
265     int retval;
266
267     /* Find the next-hop IP address. */
268     memset(r->remote_mac, 0, sizeof r->remote_mac);
269     retval = netdev_get_next_hop(ib->local_netdev, &r->remote_addr.sin_addr,
270                                  &next_hop_inaddr, &next_hop_dev);
271     if (retval) {
272         VLOG_WARN("cannot find route for controller ("IP_FMT"): %s",
273                   IP_ARGS(&r->remote_addr.sin_addr), strerror(retval));
274         return 1;
275     }
276     if (!next_hop_inaddr.s_addr) {
277         next_hop_inaddr = r->remote_addr.sin_addr;
278     }
279
280     /* Open the next-hop network device. */
281     if (!r->remote_netdev
282         || strcmp(netdev_get_name(r->remote_netdev), next_hop_dev))
283     {
284         netdev_close(r->remote_netdev);
285
286         retval = netdev_open_default(next_hop_dev, &r->remote_netdev);
287         if (retval) {
288             VLOG_WARN_RL(&rl, "cannot open netdev %s (next hop "
289                          "to controller "IP_FMT"): %s",
290                          next_hop_dev, IP_ARGS(&r->remote_addr.sin_addr),
291                          strerror(retval));
292             free(next_hop_dev);
293             return 1;
294         }
295     }
296     free(next_hop_dev);
297
298     /* Look up the MAC address of the next-hop IP address. */
299     retval = netdev_arp_lookup(r->remote_netdev, next_hop_inaddr.s_addr,
300                                r->remote_mac);
301     if (retval) {
302         VLOG_DBG_RL(&rl, "cannot look up remote MAC address ("IP_FMT"): %s",
303                     IP_ARGS(&next_hop_inaddr.s_addr), strerror(retval));
304     }
305
306     /* If we don't have a MAC address, then refresh quickly, since we probably
307      * will get a MAC address soon (via ARP).  Otherwise, we can afford to wait
308      * a little while. */
309     return eth_addr_is_zero(r->remote_mac) ? 1 : 10;
310 }
311
312 static bool
313 refresh_remotes(struct in_band *ib)
314 {
315     struct in_band_remote *r;
316     bool any_changes;
317
318     if (time_now() < ib->next_remote_refresh) {
319         return false;
320     }
321
322     any_changes = false;
323     ib->next_remote_refresh = TIME_MAX;
324     for (r = ib->remotes; r < &ib->remotes[ib->n_remotes]; r++) {
325         uint8_t old_remote_mac[ETH_ADDR_LEN];
326         time_t next_refresh;
327
328         /* Save old MAC. */
329         memcpy(old_remote_mac, r->remote_mac, ETH_ADDR_LEN);
330
331         /* Refresh remote information. */
332         next_refresh = refresh_remote(ib, r) + time_now();
333         ib->next_remote_refresh = MIN(ib->next_remote_refresh, next_refresh);
334
335         /* If the MAC changed, log the changes. */
336         if (!eth_addr_equals(r->remote_mac, old_remote_mac)) {
337             any_changes = true;
338             if (!eth_addr_is_zero(r->remote_mac)
339                 && !eth_addr_equals(r->last_remote_mac, r->remote_mac)) {
340                 VLOG_DBG("remote MAC address changed from "ETH_ADDR_FMT
341                          " to "ETH_ADDR_FMT,
342                          ETH_ADDR_ARGS(r->last_remote_mac),
343                          ETH_ADDR_ARGS(r->remote_mac));
344                 memcpy(r->last_remote_mac, r->remote_mac, ETH_ADDR_LEN);
345             }
346         }
347     }
348
349     return any_changes;
350 }
351
352 /* Refreshes the MAC address of the local port into ib->local_mac, if it is due
353  * for a refresh.  Returns true if anything changed, otherwise false.  */
354 static bool
355 refresh_local(struct in_band *ib)
356 {
357     uint8_t ea[ETH_ADDR_LEN];
358     time_t now;
359
360     now = time_now();
361     if (now < ib->next_local_refresh) {
362         return false;
363     }
364     ib->next_local_refresh = now + 1;
365
366     if (netdev_get_etheraddr(ib->local_netdev, ea)
367         || eth_addr_equals(ea, ib->local_mac)) {
368         return false;
369     }
370
371     memcpy(ib->local_mac, ea, ETH_ADDR_LEN);
372     return true;
373 }
374
375 static void
376 in_band_status_cb(struct status_reply *sr, void *in_band_)
377 {
378     struct in_band *in_band = in_band_;
379
380     if (!eth_addr_is_zero(in_band->local_mac)) {
381         status_reply_put(sr, "local-mac="ETH_ADDR_FMT,
382                          ETH_ADDR_ARGS(in_band->local_mac));
383     }
384
385     if (in_band->n_remotes
386         && !eth_addr_is_zero(in_band->remotes[0].remote_mac)) {
387         status_reply_put(sr, "remote-mac="ETH_ADDR_FMT,
388                          ETH_ADDR_ARGS(in_band->remotes[0].remote_mac));
389     }
390 }
391
392 static void
393 init_rule(struct in_band_rule *rule, unsigned int priority)
394 {
395     /* Clearing the flow is not strictly necessary but it seems cleaner. */
396     memset(&rule->flow, 0, sizeof rule->flow);
397
398     rule->flow.wildcards = OVSFW_ALL;
399     rule->flow.priority = priority;
400 }
401
402 static void
403 set_in_port(struct in_band_rule *rule, uint16_t ofp_port)
404 {
405     rule->flow.wildcards &= ~OFPFW_IN_PORT;
406     rule->flow.in_port = ofp_port;
407 }
408
409 static void
410 set_dl_type(struct in_band_rule *rule, uint16_t dl_type)
411 {
412     rule->flow.wildcards &= ~OFPFW_DL_TYPE;
413     rule->flow.dl_type = dl_type;
414 }
415
416 static void
417 set_dl_src(struct in_band_rule *rule, const uint8_t dl_src[ETH_ADDR_LEN])
418 {
419     rule->flow.wildcards &= ~OFPFW_DL_SRC;
420     memcpy(rule->flow.dl_src, dl_src, ETH_ADDR_LEN);
421 }
422
423 static void
424 set_dl_dst(struct in_band_rule *rule, const uint8_t dl_dst[ETH_ADDR_LEN])
425 {
426     rule->flow.wildcards &= ~OFPFW_DL_DST;
427     memcpy(rule->flow.dl_dst, dl_dst, ETH_ADDR_LEN);
428 }
429
430 static void
431 set_tp_src(struct in_band_rule *rule, uint16_t tp_src)
432 {
433     rule->flow.wildcards &= ~OFPFW_TP_SRC;
434     rule->flow.tp_src = tp_src;
435 }
436
437 static void
438 set_tp_dst(struct in_band_rule *rule, uint16_t tp_dst)
439 {
440     rule->flow.wildcards &= ~OFPFW_TP_DST;
441     rule->flow.tp_dst = tp_dst;
442 }
443
444 static void
445 set_nw_proto(struct in_band_rule *rule, uint8_t nw_proto)
446 {
447     rule->flow.wildcards &= ~OFPFW_NW_PROTO;
448     rule->flow.nw_proto = nw_proto;
449 }
450
451 static void
452 set_nw_src(struct in_band_rule *rule, const struct in_addr nw_src)
453 {
454     rule->flow.wildcards &= ~OFPFW_NW_SRC_MASK;
455     rule->flow.nw_src = nw_src.s_addr;
456 }
457
458 static void
459 set_nw_dst(struct in_band_rule *rule, const struct in_addr nw_dst)
460 {
461     rule->flow.wildcards &= ~OFPFW_NW_DST_MASK;
462     rule->flow.nw_dst = nw_dst.s_addr;
463 }
464
465 static void
466 make_rules(struct in_band *ib,
467            void (*cb)(struct in_band *, const struct in_band_rule *))
468 {
469     struct in_band_rule rule;
470     size_t i;
471
472     if (!eth_addr_is_zero(ib->installed_local_mac)) {
473         /* (a) Allow DHCP requests sent from the local port. */
474         init_rule(&rule, IBR_FROM_LOCAL_DHCP);
475         set_in_port(&rule, OFPP_LOCAL);
476         set_dl_type(&rule, htons(ETH_TYPE_IP));
477         set_dl_src(&rule, ib->installed_local_mac);
478         set_nw_proto(&rule, IP_TYPE_UDP);
479         set_tp_src(&rule, htons(DHCP_CLIENT_PORT));
480         set_tp_dst(&rule, htons(DHCP_SERVER_PORT));
481         cb(ib, &rule);
482
483         /* (b) Allow ARP replies to the local port's MAC address. */
484         init_rule(&rule, IBR_TO_LOCAL_ARP);
485         set_dl_type(&rule, htons(ETH_TYPE_ARP));
486         set_dl_dst(&rule, ib->installed_local_mac);
487         set_nw_proto(&rule, ARP_OP_REPLY);
488         cb(ib, &rule);
489
490         /* (c) Allow ARP requests from the local port's MAC address.  */
491         init_rule(&rule, IBR_FROM_LOCAL_ARP);
492         set_dl_type(&rule, htons(ETH_TYPE_ARP));
493         set_dl_src(&rule, ib->installed_local_mac);
494         set_nw_proto(&rule, ARP_OP_REQUEST);
495         cb(ib, &rule);
496     }
497
498     for (i = 0; i < ib->n_remote_macs; i++) {
499         const uint8_t *remote_mac = &ib->remote_macs[i * ETH_ADDR_LEN];
500
501         if (i > 0) {
502             const uint8_t *prev_mac = &ib->remote_macs[(i - 1) * ETH_ADDR_LEN];
503             if (eth_addr_equals(remote_mac, prev_mac)) {
504                 /* Skip duplicates. */
505                 continue;
506             }
507         }
508
509         /* (d) Allow ARP replies to the next hop's MAC address. */
510         init_rule(&rule, IBR_TO_NEXT_HOP_ARP);
511         set_dl_type(&rule, htons(ETH_TYPE_ARP));
512         set_dl_dst(&rule, remote_mac);
513         set_nw_proto(&rule, ARP_OP_REPLY);
514         cb(ib, &rule);
515
516         /* (e) Allow ARP requests from the next hop's MAC address. */
517         init_rule(&rule, IBR_FROM_NEXT_HOP_ARP);
518         set_dl_type(&rule, htons(ETH_TYPE_ARP));
519         set_dl_src(&rule, remote_mac);
520         set_nw_proto(&rule, ARP_OP_REQUEST);
521         cb(ib, &rule);
522     }
523
524     for (i = 0; i < ib->n_remote_addrs; i++) {
525         const struct sockaddr_in *a = &ib->remote_addrs[i];
526
527         if (!i || a->sin_addr.s_addr != a[-1].sin_addr.s_addr) {
528             /* (f) Allow ARP replies containing the remote's IP address as a
529              * target. */
530             init_rule(&rule, IBR_TO_REMOTE_ARP);
531             set_dl_type(&rule, htons(ETH_TYPE_ARP));
532             set_nw_proto(&rule, ARP_OP_REPLY);
533             set_nw_dst(&rule, a->sin_addr);
534             cb(ib, &rule);
535
536             /* (g) Allow ARP requests containing the remote's IP address as a
537              * source. */
538             init_rule(&rule, IBR_FROM_REMOTE_ARP);
539             set_dl_type(&rule, htons(ETH_TYPE_ARP));
540             set_nw_proto(&rule, ARP_OP_REQUEST);
541             set_nw_src(&rule, a->sin_addr);
542             cb(ib, &rule);
543         }
544
545         if (!i
546             || a->sin_addr.s_addr != a[-1].sin_addr.s_addr
547             || a->sin_port != a[-1].sin_port) {
548             /* (h) Allow TCP traffic to the remote's IP and port. */
549             init_rule(&rule, IBR_TO_REMOTE_TCP);
550             set_dl_type(&rule, htons(ETH_TYPE_IP));
551             set_nw_proto(&rule, IP_TYPE_TCP);
552             set_nw_dst(&rule, a->sin_addr);
553             set_tp_dst(&rule, a->sin_port);
554             cb(ib, &rule);
555
556             /* (i) Allow TCP traffic from the remote's IP and port. */
557             init_rule(&rule, IBR_FROM_REMOTE_TCP);
558             set_dl_type(&rule, htons(ETH_TYPE_IP));
559             set_nw_proto(&rule, IP_TYPE_TCP);
560             set_nw_src(&rule, a->sin_addr);
561             set_tp_src(&rule, a->sin_port);
562             cb(ib, &rule);
563         }
564     }
565 }
566
567 static void
568 drop_rule(struct in_band *ib, const struct in_band_rule *rule)
569 {
570     ofproto_delete_flow(ib->ofproto, &rule->flow);
571 }
572
573 /* Drops from the flow table all of the flows set up by 'ib', then clears out
574  * the information about the installed flows so that they can be filled in
575  * again if necessary. */
576 static void
577 drop_rules(struct in_band *ib)
578 {
579     /* Drop rules. */
580     make_rules(ib, drop_rule);
581
582     /* Clear out state. */
583     memset(ib->installed_local_mac, 0, sizeof ib->installed_local_mac);
584
585     free(ib->remote_addrs);
586     ib->remote_addrs = NULL;
587     ib->n_remote_addrs = 0;
588
589     free(ib->remote_macs);
590     ib->remote_macs = NULL;
591     ib->n_remote_macs = 0;
592 }
593
594 static void
595 add_rule(struct in_band *ib, const struct in_band_rule *rule)
596 {
597     union ofp_action action;
598
599     action.type = htons(OFPAT_OUTPUT);
600     action.output.len = htons(sizeof action);
601     action.output.port = htons(OFPP_NORMAL);
602     action.output.max_len = htons(0);
603     ofproto_add_flow(ib->ofproto, &rule->flow, &action, 1, 0);
604 }
605
606 /* Inserts flows into the flow table for the current state of 'ib'. */
607 static void
608 add_rules(struct in_band *ib)
609 {
610     make_rules(ib, add_rule);
611 }
612
613 static int
614 compare_addrs(const void *a_, const void *b_)
615 {
616     const struct sockaddr_in *a = a_;
617     const struct sockaddr_in *b = b_;
618     int cmp;
619
620     cmp = memcmp(&a->sin_addr.s_addr,
621                  &b->sin_addr.s_addr,
622                  sizeof a->sin_addr.s_addr);
623     if (cmp) {
624         return cmp;
625     }
626     return memcmp(&a->sin_port, &b->sin_port, sizeof a->sin_port);
627 }
628
629 static int
630 compare_macs(const void *a, const void *b)
631 {
632     return memcmp(a, b, ETH_ADDR_LEN);
633 }
634
635 void
636 in_band_run(struct in_band *ib)
637 {
638     struct in_band_remote *r;
639     bool local_change, remote_change;
640
641     local_change = refresh_local(ib);
642     remote_change = refresh_remotes(ib);
643     if (!local_change && !remote_change) {
644         /* Nothing changed, nothing to do. */
645         return;
646     }
647
648     /* Drop old rules. */
649     drop_rules(ib);
650
651     /* Figure out new rules. */
652     memcpy(ib->installed_local_mac, ib->local_mac, ETH_ADDR_LEN);
653     ib->remote_addrs = xmalloc(ib->n_remotes * sizeof *ib->remote_addrs);
654     ib->n_remote_addrs = 0;
655     ib->remote_macs = xmalloc(ib->n_remotes * ETH_ADDR_LEN);
656     ib->n_remote_macs = 0;
657     for (r = ib->remotes; r < &ib->remotes[ib->n_remotes]; r++) {
658         ib->remote_addrs[ib->n_remote_addrs++] = r->remote_addr;
659         if (!eth_addr_is_zero(r->remote_mac)) {
660             memcpy(&ib->remote_macs[ib->n_remote_macs * ETH_ADDR_LEN],
661                    r->remote_mac, ETH_ADDR_LEN);
662             ib->n_remote_macs++;
663         }
664     }
665
666     /* Sort, to allow make_rules() to easily skip duplicates. */
667     qsort(ib->remote_addrs, ib->n_remote_addrs, sizeof *ib->remote_addrs,
668           compare_addrs);
669     qsort(ib->remote_macs, ib->n_remote_macs, ETH_ADDR_LEN, compare_macs);
670
671     /* Add new rules. */
672     add_rules(ib);
673 }
674
675 void
676 in_band_wait(struct in_band *in_band)
677 {
678     time_t now = time_now();
679     time_t wakeup 
680             = MIN(in_band->next_remote_refresh, in_band->next_local_refresh);
681     if (wakeup > now) {
682         poll_timer_wait((wakeup - now) * 1000);
683     } else {
684         poll_immediate_wake();
685     }
686 }
687
688 /* ofproto has flushed all flows from the flow table and it is calling us back
689  * to allow us to reinstall the ones that are important to us. */
690 void
691 in_band_flushed(struct in_band *in_band)
692 {
693     add_rules(in_band);
694 }
695
696 int
697 in_band_create(struct ofproto *ofproto, struct wdp *wdp,
698                struct switch_status *ss, struct in_band **in_bandp)
699 {
700     struct in_band *in_band;
701     struct netdev *local_netdev;
702     char *local_name;
703     int error;
704
705     error = wdp_port_get_name(wdp, OFPP_LOCAL, &local_name);
706     if (error) {
707         VLOG_ERR("failed to initialize in-band control: cannot get name "
708                  "of datapath local port (%s)", strerror(error));
709         return error;
710     }
711
712     error = netdev_open_default(local_name, &local_netdev);
713     if (error) {
714         VLOG_ERR("failed to initialize in-band control: cannot open "
715                  "datapath local port %s (%s)", local_name, strerror(error));
716         free(local_name);
717         return error;
718     }
719     free(local_name);
720
721     in_band = xzalloc(sizeof *in_band);
722     in_band->ofproto = ofproto;
723     in_band->ss_cat = switch_status_register(ss, "in-band",
724                                              in_band_status_cb, in_band);
725     in_band->next_remote_refresh = TIME_MIN;
726     in_band->next_local_refresh = TIME_MIN;
727     in_band->local_netdev = local_netdev;
728
729     *in_bandp = in_band;
730
731     return 0;
732 }
733
734 void
735 in_band_destroy(struct in_band *ib)
736 {
737     if (ib) {
738         drop_rules(ib);
739         in_band_set_remotes(ib, NULL, 0);
740         switch_status_unregister(ib->ss_cat);
741         netdev_close(ib->local_netdev);
742         free(ib);
743     }
744 }
745
746 static bool
747 any_addresses_changed(struct in_band *ib,
748                       const struct sockaddr_in *addresses, size_t n)
749 {
750     size_t i;
751
752     if (n != ib->n_remotes) {
753         return true;
754     }
755
756     for (i = 0; i < n; i++) {
757         const struct sockaddr_in *old = &ib->remotes[i].remote_addr;
758         const struct sockaddr_in *new = &addresses[i];
759
760         if (old->sin_addr.s_addr != new->sin_addr.s_addr ||
761             old->sin_port != new->sin_port) {
762             return true;
763         }
764     }
765
766     return false;
767 }
768
769 void
770 in_band_set_remotes(struct in_band *ib,
771                     const struct sockaddr_in *addresses, size_t n)
772 {
773     size_t i;
774
775     if (!any_addresses_changed(ib, addresses, n)) {
776         return;
777     }
778
779     /* Clear old remotes. */
780     for (i = 0; i < ib->n_remotes; i++) {
781         netdev_close(ib->remotes[i].remote_netdev);
782     }
783     free(ib->remotes);
784
785     /* Set up new remotes. */
786     ib->remotes = n ? xzalloc(n * sizeof *ib->remotes) : NULL;
787     ib->n_remotes = n;
788     for (i = 0; i < n; i++) {
789         ib->remotes[i].remote_addr = addresses[i];
790     }
791
792     /* Force refresh in next call to in_band_run(). */
793     ib->next_remote_refresh = TIME_MIN;
794 }