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