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