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