nicira-ext: Name the enum used for flow formats, to clarify code.
[sliver-openvswitch.git] / lib / ofp-util.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 "ofp-print.h"
19 #include <inttypes.h>
20 #include <stdlib.h>
21 #include "byte-order.h"
22 #include "classifier.h"
23 #include "nx-match.h"
24 #include "ofp-util.h"
25 #include "ofpbuf.h"
26 #include "packets.h"
27 #include "random.h"
28 #include "vlog.h"
29
30 VLOG_DEFINE_THIS_MODULE(ofp_util);
31
32 /* Rate limit for OpenFlow message parse errors.  These always indicate a bug
33  * in the peer and so there's not much point in showing a lot of them. */
34 static struct vlog_rate_limit bad_ofmsg_rl = VLOG_RATE_LIMIT_INIT(1, 5);
35
36 /* Given the wildcard bit count in the least-significant 6 of 'wcbits', returns
37  * an IP netmask with a 1 in each bit that must match and a 0 in each bit that
38  * is wildcarded.
39  *
40  * The bits in 'wcbits' are in the format used in enum ofp_flow_wildcards: 0
41  * is exact match, 1 ignores the LSB, 2 ignores the 2 least-significant bits,
42  * ..., 32 and higher wildcard the entire field.  This is the *opposite* of the
43  * usual convention where e.g. /24 indicates that 8 bits (not 24 bits) are
44  * wildcarded. */
45 ovs_be32
46 ofputil_wcbits_to_netmask(int wcbits)
47 {
48     wcbits &= 0x3f;
49     return wcbits < 32 ? htonl(~((1u << wcbits) - 1)) : 0;
50 }
51
52 /* Given the IP netmask 'netmask', returns the number of bits of the IP address
53  * that it wildcards.  'netmask' must be a CIDR netmask (see ip_is_cidr()). */
54 int
55 ofputil_netmask_to_wcbits(ovs_be32 netmask)
56 {
57     assert(ip_is_cidr(netmask));
58 #if __GNUC__ >= 4
59     return netmask == htonl(0) ? 32 : __builtin_ctz(ntohl(netmask));
60 #else
61     int wcbits;
62
63     for (wcbits = 32; netmask; wcbits--) {
64         netmask &= netmask - 1;
65     }
66
67     return wcbits;
68 #endif
69 }
70
71 /* A list of the FWW_* and OFPFW_ bits that have the same value, meaning, and
72  * name. */
73 #define WC_INVARIANT_LIST \
74     WC_INVARIANT_BIT(IN_PORT) \
75     WC_INVARIANT_BIT(DL_SRC) \
76     WC_INVARIANT_BIT(DL_DST) \
77     WC_INVARIANT_BIT(DL_TYPE) \
78     WC_INVARIANT_BIT(NW_PROTO) \
79     WC_INVARIANT_BIT(TP_SRC) \
80     WC_INVARIANT_BIT(TP_DST)
81
82 /* Verify that all of the invariant bits (as defined on WC_INVARIANT_LIST)
83  * actually have the same names and values. */
84 #define WC_INVARIANT_BIT(NAME) BUILD_ASSERT_DECL(FWW_##NAME == OFPFW_##NAME);
85     WC_INVARIANT_LIST
86 #undef WC_INVARIANT_BIT
87
88 /* WC_INVARIANTS is the invariant bits (as defined on WC_INVARIANT_LIST) all
89  * OR'd together. */
90 enum {
91     WC_INVARIANTS = 0
92 #define WC_INVARIANT_BIT(NAME) | FWW_##NAME
93     WC_INVARIANT_LIST
94 #undef WC_INVARIANT_BIT
95 };
96
97 /* Converts the ofp_match in 'match' into a cls_rule in 'rule', with the given
98  * 'priority'.
99  *
100  * 'flow_format' must either NXFF_OPENFLOW10 or NXFF_TUN_ID_FROM_COOKIE.  In
101  * the latter case only, 'flow''s tun_id field will be taken from the high bits
102  * of 'cookie', if 'match''s wildcards do not indicate that tun_id is
103  * wildcarded. */
104 void
105 ofputil_cls_rule_from_match(const struct ofp_match *match,
106                             unsigned int priority,
107                             enum nx_flow_format flow_format,
108                             uint64_t cookie, struct cls_rule *rule)
109 {
110     struct flow_wildcards *wc = &rule->wc;
111     unsigned int ofpfw;
112     ovs_be16 vid, pcp;
113
114     /* Initialize rule->priority. */
115     ofpfw = ntohl(match->wildcards);
116     ofpfw &= flow_format == NXFF_TUN_ID_FROM_COOKIE ? OVSFW_ALL : OFPFW_ALL;
117     rule->priority = !ofpfw ? UINT16_MAX : priority;
118
119     /* Initialize most of rule->wc. */
120     wc->wildcards = ofpfw & WC_INVARIANTS;
121     if (ofpfw & OFPFW_NW_TOS) {
122         wc->wildcards |= FWW_NW_TOS;
123     }
124     memset(wc->reg_masks, 0, sizeof wc->reg_masks);
125     wc->nw_src_mask = ofputil_wcbits_to_netmask(ofpfw >> OFPFW_NW_SRC_SHIFT);
126     wc->nw_dst_mask = ofputil_wcbits_to_netmask(ofpfw >> OFPFW_NW_DST_SHIFT);
127
128     if (flow_format == NXFF_TUN_ID_FROM_COOKIE && !(ofpfw & NXFW_TUN_ID)) {
129         rule->flow.tun_id = htonl(ntohll(cookie) >> 32);
130     } else {
131         wc->wildcards |= FWW_TUN_ID;
132         rule->flow.tun_id = 0;
133     }
134
135     if (ofpfw & OFPFW_DL_DST) {
136         /* OpenFlow 1.0 OFPFW_DL_DST covers the whole Ethernet destination, but
137          * Open vSwitch breaks the Ethernet destination into bits as FWW_DL_DST
138          * and FWW_ETH_MCAST. */
139         wc->wildcards |= FWW_ETH_MCAST;
140     }
141
142     /* Initialize most of rule->flow. */
143     rule->flow.nw_src = match->nw_src;
144     rule->flow.nw_dst = match->nw_dst;
145     rule->flow.in_port = (match->in_port == htons(OFPP_LOCAL) ? ODPP_LOCAL
146                      : ntohs(match->in_port));
147     rule->flow.dl_type = match->dl_type;
148     rule->flow.tp_src = match->tp_src;
149     rule->flow.tp_dst = match->tp_dst;
150     memcpy(rule->flow.dl_src, match->dl_src, ETH_ADDR_LEN);
151     memcpy(rule->flow.dl_dst, match->dl_dst, ETH_ADDR_LEN);
152     rule->flow.nw_tos = match->nw_tos;
153     rule->flow.nw_proto = match->nw_proto;
154
155     /* Translate VLANs. */
156     vid = match->dl_vlan & htons(VLAN_VID_MASK);
157     pcp = htons((match->dl_vlan_pcp << VLAN_PCP_SHIFT) & VLAN_PCP_MASK);
158     switch (ofpfw & (OFPFW_DL_VLAN | OFPFW_DL_VLAN_PCP)) {
159     case OFPFW_DL_VLAN | OFPFW_DL_VLAN_PCP:
160         /* Wildcard everything. */
161         rule->flow.vlan_tci = htons(0);
162         rule->wc.vlan_tci_mask = htons(0);
163         break;
164
165     case OFPFW_DL_VLAN_PCP:
166         if (match->dl_vlan == htons(OFP_VLAN_NONE)) {
167             /* Match only packets without 802.1Q header. */
168             rule->flow.vlan_tci = htons(0);
169             rule->wc.vlan_tci_mask = htons(0xffff);
170         } else {
171             /* Wildcard PCP, specific VID. */
172             rule->flow.vlan_tci = vid | htons(VLAN_CFI);
173             rule->wc.vlan_tci_mask = htons(VLAN_VID_MASK | VLAN_CFI);
174         }
175         break;
176
177     case OFPFW_DL_VLAN:
178         /* Wildcard VID, specific PCP. */
179         rule->flow.vlan_tci = pcp | htons(VLAN_CFI);
180         rule->wc.vlan_tci_mask = htons(VLAN_PCP_MASK | VLAN_CFI);
181         break;
182
183     case 0:
184         if (match->dl_vlan == htons(OFP_VLAN_NONE)) {
185             /* This case is odd, since we can't have a specific PCP without an
186              * 802.1Q header.  However, older versions of OVS treated this as
187              * matching packets withut an 802.1Q header, so we do here too. */
188             rule->flow.vlan_tci = htons(0);
189             rule->wc.vlan_tci_mask = htons(0xffff);
190         } else {
191             /* Specific VID and PCP. */
192             rule->flow.vlan_tci = vid | pcp | htons(VLAN_CFI);
193             rule->wc.vlan_tci_mask = htons(0xffff);
194         }
195         break;
196     }
197
198     /* Clean up. */
199     cls_rule_zero_wildcarded_fields(rule);
200 }
201
202 /* Extract 'flow' with 'wildcards' into the OpenFlow match structure
203  * 'match'.
204  *
205  * 'flow_format' must either NXFF_OPENFLOW10 or NXFF_TUN_ID_FROM_COOKIE.  In
206  * the latter case only, 'match''s NXFW_TUN_ID bit will be filled in; otherwise
207  * it is always set to 0. */
208 void
209 ofputil_cls_rule_to_match(const struct cls_rule *rule,
210                           enum nx_flow_format flow_format,
211                           struct ofp_match *match)
212 {
213     const struct flow_wildcards *wc = &rule->wc;
214     unsigned int ofpfw;
215
216     /* Figure out most OpenFlow wildcards. */
217     ofpfw = wc->wildcards & WC_INVARIANTS;
218     ofpfw |= ofputil_netmask_to_wcbits(wc->nw_src_mask) << OFPFW_NW_SRC_SHIFT;
219     ofpfw |= ofputil_netmask_to_wcbits(wc->nw_dst_mask) << OFPFW_NW_DST_SHIFT;
220     if (wc->wildcards & FWW_NW_TOS) {
221         ofpfw |= OFPFW_NW_TOS;
222     }
223     if (flow_format == NXFF_TUN_ID_FROM_COOKIE && wc->wildcards & FWW_TUN_ID) {
224         ofpfw |= NXFW_TUN_ID;
225     }
226
227     /* Translate VLANs. */
228     match->dl_vlan = htons(0);
229     match->dl_vlan_pcp = 0;
230     if (rule->wc.vlan_tci_mask == htons(0)) {
231         ofpfw |= OFPFW_DL_VLAN | OFPFW_DL_VLAN_PCP;
232     } else if (rule->wc.vlan_tci_mask & htons(VLAN_CFI)
233                && !(rule->flow.vlan_tci & htons(VLAN_CFI))) {
234         match->dl_vlan = htons(OFP_VLAN_NONE);
235     } else {
236         if (!(rule->wc.vlan_tci_mask & htons(VLAN_VID_MASK))) {
237             ofpfw |= OFPFW_DL_VLAN;
238         } else {
239             match->dl_vlan = htons(vlan_tci_to_vid(rule->flow.vlan_tci));
240         }
241
242         if (!(rule->wc.vlan_tci_mask & htons(VLAN_PCP_MASK))) {
243             ofpfw |= OFPFW_DL_VLAN_PCP;
244         } else {
245             match->dl_vlan_pcp = vlan_tci_to_pcp(rule->flow.vlan_tci);
246         }
247     }
248
249     /* Compose most of the match structure. */
250     match->wildcards = htonl(ofpfw);
251     match->in_port = htons(rule->flow.in_port == ODPP_LOCAL ? OFPP_LOCAL
252                            : rule->flow.in_port);
253     memcpy(match->dl_src, rule->flow.dl_src, ETH_ADDR_LEN);
254     memcpy(match->dl_dst, rule->flow.dl_dst, ETH_ADDR_LEN);
255     match->dl_type = rule->flow.dl_type;
256     match->nw_src = rule->flow.nw_src;
257     match->nw_dst = rule->flow.nw_dst;
258     match->nw_tos = rule->flow.nw_tos;
259     match->nw_proto = rule->flow.nw_proto;
260     match->tp_src = rule->flow.tp_src;
261     match->tp_dst = rule->flow.tp_dst;
262     memset(match->pad1, '\0', sizeof match->pad1);
263     memset(match->pad2, '\0', sizeof match->pad2);
264 }
265
266 /* Returns a transaction ID to use for an outgoing OpenFlow message. */
267 static ovs_be32
268 alloc_xid(void)
269 {
270     static uint32_t next_xid = 1;
271     return htonl(next_xid++);
272 }
273
274 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
275  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
276  * an arbitrary transaction id.  Allocated bytes beyond the header, if any, are
277  * zeroed.
278  *
279  * The caller is responsible for freeing '*bufferp' when it is no longer
280  * needed.
281  *
282  * The OpenFlow header length is initially set to 'openflow_len'; if the
283  * message is later extended, the length should be updated with
284  * update_openflow_length() before sending.
285  *
286  * Returns the header. */
287 void *
288 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp)
289 {
290     *bufferp = ofpbuf_new(openflow_len);
291     return put_openflow_xid(openflow_len, type, alloc_xid(), *bufferp);
292 }
293
294 /* Similar to make_openflow() but creates a Nicira vendor extension message
295  * with the specific 'subtype'.  'subtype' should be in host byte order. */
296 void *
297 make_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf **bufferp)
298 {
299     return make_nxmsg_xid(openflow_len, subtype, alloc_xid(), bufferp);
300 }
301
302 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
303  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
304  * transaction id 'xid'.  Allocated bytes beyond the header, if any, are
305  * zeroed.
306  *
307  * The caller is responsible for freeing '*bufferp' when it is no longer
308  * needed.
309  *
310  * The OpenFlow header length is initially set to 'openflow_len'; if the
311  * message is later extended, the length should be updated with
312  * update_openflow_length() before sending.
313  *
314  * Returns the header. */
315 void *
316 make_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
317                   struct ofpbuf **bufferp)
318 {
319     *bufferp = ofpbuf_new(openflow_len);
320     return put_openflow_xid(openflow_len, type, xid, *bufferp);
321 }
322
323 /* Similar to make_openflow_xid() but creates a Nicira vendor extension message
324  * with the specific 'subtype'.  'subtype' should be in host byte order. */
325 void *
326 make_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
327                struct ofpbuf **bufferp)
328 {
329     struct nicira_header *nxh = make_openflow_xid(openflow_len, OFPT_VENDOR,
330                                                   xid, bufferp);
331     nxh->vendor = htonl(NX_VENDOR_ID);
332     nxh->subtype = htonl(subtype);
333     return nxh;
334 }
335
336 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
337  * with the given 'type' and an arbitrary transaction id.  Allocated bytes
338  * beyond the header, if any, are zeroed.
339  *
340  * The OpenFlow header length is initially set to 'openflow_len'; if the
341  * message is later extended, the length should be updated with
342  * update_openflow_length() before sending.
343  *
344  * Returns the header. */
345 void *
346 put_openflow(size_t openflow_len, uint8_t type, struct ofpbuf *buffer)
347 {
348     return put_openflow_xid(openflow_len, type, alloc_xid(), buffer);
349 }
350
351 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
352  * with the given 'type' and an transaction id 'xid'.  Allocated bytes beyond
353  * the header, if any, are zeroed.
354  *
355  * The OpenFlow header length is initially set to 'openflow_len'; if the
356  * message is later extended, the length should be updated with
357  * update_openflow_length() before sending.
358  *
359  * Returns the header. */
360 void *
361 put_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
362                  struct ofpbuf *buffer)
363 {
364     struct ofp_header *oh;
365
366     assert(openflow_len >= sizeof *oh);
367     assert(openflow_len <= UINT16_MAX);
368
369     oh = ofpbuf_put_uninit(buffer, openflow_len);
370     oh->version = OFP_VERSION;
371     oh->type = type;
372     oh->length = htons(openflow_len);
373     oh->xid = xid;
374     memset(oh + 1, 0, openflow_len - sizeof *oh);
375     return oh;
376 }
377
378 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
379  * 'buffer->size'. */
380 void
381 update_openflow_length(struct ofpbuf *buffer)
382 {
383     struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
384     oh->length = htons(buffer->size);
385 }
386
387 struct ofpbuf *
388 make_flow_mod(uint16_t command, const struct cls_rule *rule,
389               size_t actions_len)
390 {
391     struct ofp_flow_mod *ofm;
392     size_t size = sizeof *ofm + actions_len;
393     struct ofpbuf *out = ofpbuf_new(size);
394     ofm = ofpbuf_put_zeros(out, sizeof *ofm);
395     ofm->header.version = OFP_VERSION;
396     ofm->header.type = OFPT_FLOW_MOD;
397     ofm->header.length = htons(size);
398     ofm->cookie = 0;
399     ofm->priority = htons(MIN(rule->priority, UINT16_MAX));
400     ofputil_cls_rule_to_match(rule, NXFF_OPENFLOW10, &ofm->match);
401     ofm->command = htons(command);
402     return out;
403 }
404
405 struct ofpbuf *
406 make_add_flow(const struct cls_rule *rule, uint32_t buffer_id,
407               uint16_t idle_timeout, size_t actions_len)
408 {
409     struct ofpbuf *out = make_flow_mod(OFPFC_ADD, rule, actions_len);
410     struct ofp_flow_mod *ofm = out->data;
411     ofm->idle_timeout = htons(idle_timeout);
412     ofm->hard_timeout = htons(OFP_FLOW_PERMANENT);
413     ofm->buffer_id = htonl(buffer_id);
414     return out;
415 }
416
417 struct ofpbuf *
418 make_del_flow(const struct cls_rule *rule)
419 {
420     struct ofpbuf *out = make_flow_mod(OFPFC_DELETE_STRICT, rule, 0);
421     struct ofp_flow_mod *ofm = out->data;
422     ofm->out_port = htons(OFPP_NONE);
423     return out;
424 }
425
426 struct ofpbuf *
427 make_add_simple_flow(const struct cls_rule *rule,
428                      uint32_t buffer_id, uint16_t out_port,
429                      uint16_t idle_timeout)
430 {
431     if (out_port != OFPP_NONE) {
432         struct ofp_action_output *oao;
433         struct ofpbuf *buffer;
434
435         buffer = make_add_flow(rule, buffer_id, idle_timeout, sizeof *oao);
436         oao = ofpbuf_put_zeros(buffer, sizeof *oao);
437         oao->type = htons(OFPAT_OUTPUT);
438         oao->len = htons(sizeof *oao);
439         oao->port = htons(out_port);
440         return buffer;
441     } else {
442         return make_add_flow(rule, buffer_id, idle_timeout, 0);
443     }
444 }
445
446 struct ofpbuf *
447 make_packet_in(uint32_t buffer_id, uint16_t in_port, uint8_t reason,
448                const struct ofpbuf *payload, int max_send_len)
449 {
450     struct ofp_packet_in *opi;
451     struct ofpbuf *buf;
452     int send_len;
453
454     send_len = MIN(max_send_len, payload->size);
455     buf = ofpbuf_new(sizeof *opi + send_len);
456     opi = put_openflow_xid(offsetof(struct ofp_packet_in, data),
457                            OFPT_PACKET_IN, 0, buf);
458     opi->buffer_id = htonl(buffer_id);
459     opi->total_len = htons(payload->size);
460     opi->in_port = htons(in_port);
461     opi->reason = reason;
462     ofpbuf_put(buf, payload->data, send_len);
463     update_openflow_length(buf);
464
465     return buf;
466 }
467
468 struct ofpbuf *
469 make_packet_out(const struct ofpbuf *packet, uint32_t buffer_id,
470                 uint16_t in_port,
471                 const struct ofp_action_header *actions, size_t n_actions)
472 {
473     size_t actions_len = n_actions * sizeof *actions;
474     struct ofp_packet_out *opo;
475     size_t size = sizeof *opo + actions_len + (packet ? packet->size : 0);
476     struct ofpbuf *out = ofpbuf_new(size);
477
478     opo = ofpbuf_put_uninit(out, sizeof *opo);
479     opo->header.version = OFP_VERSION;
480     opo->header.type = OFPT_PACKET_OUT;
481     opo->header.length = htons(size);
482     opo->header.xid = htonl(0);
483     opo->buffer_id = htonl(buffer_id);
484     opo->in_port = htons(in_port == ODPP_LOCAL ? OFPP_LOCAL : in_port);
485     opo->actions_len = htons(actions_len);
486     ofpbuf_put(out, actions, actions_len);
487     if (packet) {
488         ofpbuf_put(out, packet->data, packet->size);
489     }
490     return out;
491 }
492
493 struct ofpbuf *
494 make_unbuffered_packet_out(const struct ofpbuf *packet,
495                            uint16_t in_port, uint16_t out_port)
496 {
497     struct ofp_action_output action;
498     action.type = htons(OFPAT_OUTPUT);
499     action.len = htons(sizeof action);
500     action.port = htons(out_port);
501     return make_packet_out(packet, UINT32_MAX, in_port,
502                            (struct ofp_action_header *) &action, 1);
503 }
504
505 struct ofpbuf *
506 make_buffered_packet_out(uint32_t buffer_id,
507                          uint16_t in_port, uint16_t out_port)
508 {
509     if (out_port != OFPP_NONE) {
510         struct ofp_action_output action;
511         action.type = htons(OFPAT_OUTPUT);
512         action.len = htons(sizeof action);
513         action.port = htons(out_port);
514         return make_packet_out(NULL, buffer_id, in_port,
515                                (struct ofp_action_header *) &action, 1);
516     } else {
517         return make_packet_out(NULL, buffer_id, in_port, NULL, 0);
518     }
519 }
520
521 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
522 struct ofpbuf *
523 make_echo_request(void)
524 {
525     struct ofp_header *rq;
526     struct ofpbuf *out = ofpbuf_new(sizeof *rq);
527     rq = ofpbuf_put_uninit(out, sizeof *rq);
528     rq->version = OFP_VERSION;
529     rq->type = OFPT_ECHO_REQUEST;
530     rq->length = htons(sizeof *rq);
531     rq->xid = htonl(0);
532     return out;
533 }
534
535 /* Creates and returns an OFPT_ECHO_REPLY message matching the
536  * OFPT_ECHO_REQUEST message in 'rq'. */
537 struct ofpbuf *
538 make_echo_reply(const struct ofp_header *rq)
539 {
540     size_t size = ntohs(rq->length);
541     struct ofpbuf *out = ofpbuf_new(size);
542     struct ofp_header *reply = ofpbuf_put(out, rq, size);
543     reply->type = OFPT_ECHO_REPLY;
544     return out;
545 }
546
547 static int
548 check_message_type(uint8_t got_type, uint8_t want_type)
549 {
550     if (got_type != want_type) {
551         char *want_type_name = ofp_message_type_to_string(want_type);
552         char *got_type_name = ofp_message_type_to_string(got_type);
553         VLOG_WARN_RL(&bad_ofmsg_rl,
554                      "received bad message type %s (expected %s)",
555                      got_type_name, want_type_name);
556         free(want_type_name);
557         free(got_type_name);
558         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE);
559     }
560     return 0;
561 }
562
563 /* Checks that 'msg' has type 'type' and that it is exactly 'size' bytes long.
564  * Returns 0 if the checks pass, otherwise an OpenFlow error code (produced
565  * with ofp_mkerr()). */
566 int
567 check_ofp_message(const struct ofp_header *msg, uint8_t type, size_t size)
568 {
569     size_t got_size;
570     int error;
571
572     error = check_message_type(msg->type, type);
573     if (error) {
574         return error;
575     }
576
577     got_size = ntohs(msg->length);
578     if (got_size != size) {
579         char *type_name = ofp_message_type_to_string(type);
580         VLOG_WARN_RL(&bad_ofmsg_rl,
581                      "received %s message of length %zu (expected %zu)",
582                      type_name, got_size, size);
583         free(type_name);
584         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
585     }
586
587     return 0;
588 }
589
590 /* Checks that 'msg' has type 'type' and that 'msg' is 'size' plus a
591  * nonnegative integer multiple of 'array_elt_size' bytes long.  Returns 0 if
592  * the checks pass, otherwise an OpenFlow error code (produced with
593  * ofp_mkerr()).
594  *
595  * If 'n_array_elts' is nonnull, then '*n_array_elts' is set to the number of
596  * 'array_elt_size' blocks in 'msg' past the first 'min_size' bytes, when
597  * successful. */
598 int
599 check_ofp_message_array(const struct ofp_header *msg, uint8_t type,
600                         size_t min_size, size_t array_elt_size,
601                         size_t *n_array_elts)
602 {
603     size_t got_size;
604     int error;
605
606     assert(array_elt_size);
607
608     error = check_message_type(msg->type, type);
609     if (error) {
610         return error;
611     }
612
613     got_size = ntohs(msg->length);
614     if (got_size < min_size) {
615         char *type_name = ofp_message_type_to_string(type);
616         VLOG_WARN_RL(&bad_ofmsg_rl, "received %s message of length %zu "
617                      "(expected at least %zu)",
618                      type_name, got_size, min_size);
619         free(type_name);
620         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
621     }
622     if ((got_size - min_size) % array_elt_size) {
623         char *type_name = ofp_message_type_to_string(type);
624         VLOG_WARN_RL(&bad_ofmsg_rl,
625                      "received %s message of bad length %zu: the "
626                      "excess over %zu (%zu) is not evenly divisible by %zu "
627                      "(remainder is %zu)",
628                      type_name, got_size, min_size, got_size - min_size,
629                      array_elt_size, (got_size - min_size) % array_elt_size);
630         free(type_name);
631         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
632     }
633     if (n_array_elts) {
634         *n_array_elts = (got_size - min_size) / array_elt_size;
635     }
636     return 0;
637 }
638
639 const struct ofp_flow_stats *
640 flow_stats_first(struct flow_stats_iterator *iter,
641                  const struct ofp_stats_reply *osr)
642 {
643     iter->pos = osr->body;
644     iter->end = osr->body + (ntohs(osr->header.length)
645                              - offsetof(struct ofp_stats_reply, body));
646     return flow_stats_next(iter);
647 }
648
649 const struct ofp_flow_stats *
650 flow_stats_next(struct flow_stats_iterator *iter)
651 {
652     ptrdiff_t bytes_left = iter->end - iter->pos;
653     const struct ofp_flow_stats *fs;
654     size_t length;
655
656     if (bytes_left < sizeof *fs) {
657         if (bytes_left != 0) {
658             VLOG_WARN_RL(&bad_ofmsg_rl,
659                          "%td leftover bytes in flow stats reply", bytes_left);
660         }
661         return NULL;
662     }
663
664     fs = (const void *) iter->pos;
665     length = ntohs(fs->length);
666     if (length < sizeof *fs) {
667         VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu is shorter than "
668                      "min %zu", length, sizeof *fs);
669         return NULL;
670     } else if (length > bytes_left) {
671         VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu but only %td "
672                      "bytes left", length, bytes_left);
673         return NULL;
674     } else if ((length - sizeof *fs) % sizeof fs->actions[0]) {
675         VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu has %zu bytes "
676                      "left over in final action", length,
677                      (length - sizeof *fs) % sizeof fs->actions[0]);
678         return NULL;
679     }
680     iter->pos += length;
681     return fs;
682 }
683
684 static int
685 check_action_exact_len(const union ofp_action *a, unsigned int len,
686                        unsigned int required_len)
687 {
688     if (len != required_len) {
689         VLOG_DBG_RL(&bad_ofmsg_rl,
690                     "action %u has invalid length %"PRIu16" (must be %u)\n",
691                     a->type, ntohs(a->header.len), required_len);
692         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
693     }
694     return 0;
695 }
696
697 /* Checks that 'port' is a valid output port for the OFPAT_OUTPUT action, given
698  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
699  * 'port' is valid, otherwise an ofp_mkerr() return code. */
700 static int
701 check_output_port(uint16_t port, int max_ports)
702 {
703     switch (port) {
704     case OFPP_IN_PORT:
705     case OFPP_TABLE:
706     case OFPP_NORMAL:
707     case OFPP_FLOOD:
708     case OFPP_ALL:
709     case OFPP_CONTROLLER:
710     case OFPP_LOCAL:
711         return 0;
712
713     default:
714         if (port < max_ports) {
715             return 0;
716         }
717         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown output port %x", port);
718         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
719     }
720 }
721
722 /* Checks that 'action' is a valid OFPAT_ENQUEUE action, given that the switch
723  * will never have more than 'max_ports' ports.  Returns 0 if 'port' is valid,
724  * otherwise an ofp_mkerr() return code. */
725 static int
726 check_enqueue_action(const union ofp_action *a, unsigned int len,
727                      int max_ports)
728 {
729     const struct ofp_action_enqueue *oae;
730     uint16_t port;
731     int error;
732
733     error = check_action_exact_len(a, len, 16);
734     if (error) {
735         return error;
736     }
737
738     oae = (const struct ofp_action_enqueue *) a;
739     port = ntohs(oae->port);
740     if (port < max_ports || port == OFPP_IN_PORT) {
741         return 0;
742     }
743     VLOG_WARN_RL(&bad_ofmsg_rl, "unknown enqueue port %x", port);
744     return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
745 }
746
747 static int
748 check_nicira_action(const union ofp_action *a, unsigned int len,
749                     const struct flow *flow)
750 {
751     const struct nx_action_header *nah;
752     int error;
753
754     if (len < 16) {
755         VLOG_DBG_RL(&bad_ofmsg_rl,
756                     "Nicira vendor action only %u bytes", len);
757         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
758     }
759     nah = (const struct nx_action_header *) a;
760
761     switch (ntohs(nah->subtype)) {
762     case NXAST_RESUBMIT:
763     case NXAST_SET_TUNNEL:
764     case NXAST_DROP_SPOOFED_ARP:
765     case NXAST_SET_QUEUE:
766     case NXAST_POP_QUEUE:
767         return check_action_exact_len(a, len, 16);
768
769     case NXAST_REG_MOVE:
770         error = check_action_exact_len(a, len,
771                                        sizeof(struct nx_action_reg_move));
772         if (error) {
773             return error;
774         }
775         return nxm_check_reg_move((const struct nx_action_reg_move *) a, flow);
776
777     case NXAST_REG_LOAD:
778         error = check_action_exact_len(a, len,
779                                        sizeof(struct nx_action_reg_load));
780         if (error) {
781             return error;
782         }
783         return nxm_check_reg_load((const struct nx_action_reg_load *) a, flow);
784
785     case NXAST_NOTE:
786         return 0;
787
788     default:
789         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR_TYPE);
790     }
791 }
792
793 static int
794 check_action(const union ofp_action *a, unsigned int len,
795              const struct flow *flow, int max_ports)
796 {
797     int error;
798
799     switch (ntohs(a->type)) {
800     case OFPAT_OUTPUT:
801         error = check_action_exact_len(a, len, 8);
802         if (error) {
803             return error;
804         }
805         return check_output_port(ntohs(a->output.port), max_ports);
806
807     case OFPAT_SET_VLAN_VID:
808         error = check_action_exact_len(a, len, 8);
809         if (error) {
810             return error;
811         }
812         if (a->vlan_vid.vlan_vid & ~htons(0xfff)) {
813             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
814         }
815         return 0;
816
817     case OFPAT_SET_VLAN_PCP:
818         error = check_action_exact_len(a, len, 8);
819         if (error) {
820             return error;
821         }
822         if (a->vlan_vid.vlan_vid & ~7) {
823             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
824         }
825         return 0;
826
827     case OFPAT_STRIP_VLAN:
828     case OFPAT_SET_NW_SRC:
829     case OFPAT_SET_NW_DST:
830     case OFPAT_SET_NW_TOS:
831     case OFPAT_SET_TP_SRC:
832     case OFPAT_SET_TP_DST:
833         return check_action_exact_len(a, len, 8);
834
835     case OFPAT_SET_DL_SRC:
836     case OFPAT_SET_DL_DST:
837         return check_action_exact_len(a, len, 16);
838
839     case OFPAT_VENDOR:
840         return (a->vendor.vendor == htonl(NX_VENDOR_ID)
841                 ? check_nicira_action(a, len, flow)
842                 : ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR));
843
844     case OFPAT_ENQUEUE:
845         return check_enqueue_action(a, len, max_ports);
846
847     default:
848         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown action type %"PRIu16,
849                 ntohs(a->type));
850         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_TYPE);
851     }
852 }
853
854 int
855 validate_actions(const union ofp_action *actions, size_t n_actions,
856                  const struct flow *flow, int max_ports)
857 {
858     size_t i;
859
860     for (i = 0; i < n_actions; ) {
861         const union ofp_action *a = &actions[i];
862         unsigned int len = ntohs(a->header.len);
863         unsigned int n_slots = len / OFP_ACTION_ALIGN;
864         unsigned int slots_left = &actions[n_actions] - a;
865         int error;
866
867         if (n_slots > slots_left) {
868             VLOG_DBG_RL(&bad_ofmsg_rl,
869                         "action requires %u slots but only %u remain",
870                         n_slots, slots_left);
871             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
872         } else if (!len) {
873             VLOG_DBG_RL(&bad_ofmsg_rl, "action has invalid length 0");
874             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
875         } else if (len % OFP_ACTION_ALIGN) {
876             VLOG_DBG_RL(&bad_ofmsg_rl, "action length %u is not a multiple "
877                         "of %d", len, OFP_ACTION_ALIGN);
878             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
879         }
880
881         error = check_action(a, len, flow, max_ports);
882         if (error) {
883             return error;
884         }
885         i += n_slots;
886     }
887     return 0;
888 }
889
890 /* Returns true if 'action' outputs to 'port' (which must be in network byte
891  * order), false otherwise. */
892 bool
893 action_outputs_to_port(const union ofp_action *action, uint16_t port)
894 {
895     switch (ntohs(action->type)) {
896     case OFPAT_OUTPUT:
897         return action->output.port == port;
898     case OFPAT_ENQUEUE:
899         return ((const struct ofp_action_enqueue *) action)->port == port;
900     default:
901         return false;
902     }
903 }
904
905 /* The set of actions must either come from a trusted source or have been
906  * previously validated with validate_actions(). */
907 const union ofp_action *
908 actions_first(struct actions_iterator *iter,
909               const union ofp_action *oa, size_t n_actions)
910 {
911     iter->pos = oa;
912     iter->end = oa + n_actions;
913     return actions_next(iter);
914 }
915
916 const union ofp_action *
917 actions_next(struct actions_iterator *iter)
918 {
919     if (iter->pos != iter->end) {
920         const union ofp_action *a = iter->pos;
921         unsigned int len = ntohs(a->header.len);
922         iter->pos += len / OFP_ACTION_ALIGN;
923         return a;
924     } else {
925         return NULL;
926     }
927 }
928
929 void
930 normalize_match(struct ofp_match *m)
931 {
932     enum { OFPFW_NW = (OFPFW_NW_SRC_MASK | OFPFW_NW_DST_MASK | OFPFW_NW_PROTO
933                        | OFPFW_NW_TOS) };
934     enum { OFPFW_TP = OFPFW_TP_SRC | OFPFW_TP_DST };
935     uint32_t wc;
936
937     wc = ntohl(m->wildcards) & OVSFW_ALL;
938     if (wc & OFPFW_DL_TYPE) {
939         m->dl_type = 0;
940
941         /* Can't sensibly match on network or transport headers if the
942          * data link type is unknown. */
943         wc |= OFPFW_NW | OFPFW_TP;
944         m->nw_src = m->nw_dst = m->nw_proto = m->nw_tos = 0;
945         m->tp_src = m->tp_dst = 0;
946     } else if (m->dl_type == htons(ETH_TYPE_IP)) {
947         if (wc & OFPFW_NW_PROTO) {
948             m->nw_proto = 0;
949
950             /* Can't sensibly match on transport headers if the network
951              * protocol is unknown. */
952             wc |= OFPFW_TP;
953             m->tp_src = m->tp_dst = 0;
954         } else if (m->nw_proto == IPPROTO_TCP ||
955                    m->nw_proto == IPPROTO_UDP ||
956                    m->nw_proto == IPPROTO_ICMP) {
957             if (wc & OFPFW_TP_SRC) {
958                 m->tp_src = 0;
959             }
960             if (wc & OFPFW_TP_DST) {
961                 m->tp_dst = 0;
962             }
963         } else {
964             /* Transport layer fields will always be extracted as zeros, so we
965              * can do an exact-match on those values.  */
966             wc &= ~OFPFW_TP;
967             m->tp_src = m->tp_dst = 0;
968         }
969         if (wc & OFPFW_NW_SRC_MASK) {
970             m->nw_src &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_SRC_SHIFT);
971         }
972         if (wc & OFPFW_NW_DST_MASK) {
973             m->nw_dst &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_DST_SHIFT);
974         }
975         if (wc & OFPFW_NW_TOS) {
976             m->nw_tos = 0;
977         } else {
978             m->nw_tos &= IP_DSCP_MASK;
979         }
980     } else if (m->dl_type == htons(ETH_TYPE_ARP)) {
981         if (wc & OFPFW_NW_PROTO) {
982             m->nw_proto = 0;
983         }
984         if (wc & OFPFW_NW_SRC_MASK) {
985             m->nw_src &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_SRC_SHIFT);
986         }
987         if (wc & OFPFW_NW_DST_MASK) {
988             m->nw_dst &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_DST_SHIFT);
989         }
990         m->tp_src = m->tp_dst = m->nw_tos = 0;
991     } else {
992         /* Network and transport layer fields will always be extracted as
993          * zeros, so we can do an exact-match on those values. */
994         wc &= ~(OFPFW_NW | OFPFW_TP);
995         m->nw_proto = m->nw_src = m->nw_dst = m->nw_tos = 0;
996         m->tp_src = m->tp_dst = 0;
997     }
998     if (wc & OFPFW_DL_SRC) {
999         memset(m->dl_src, 0, sizeof m->dl_src);
1000     }
1001     if (wc & OFPFW_DL_DST) {
1002         memset(m->dl_dst, 0, sizeof m->dl_dst);
1003     }
1004     m->wildcards = htonl(wc);
1005 }
1006
1007 /* Returns a string that describes 'match' in a very literal way, without
1008  * interpreting its contents except in a very basic fashion.  The returned
1009  * string is intended to be fixed-length, so that it is easy to see differences
1010  * between two such strings if one is put above another.  This is useful for
1011  * describing changes made by normalize_match().
1012  *
1013  * The caller must free the returned string (with free()). */
1014 char *
1015 ofp_match_to_literal_string(const struct ofp_match *match)
1016 {
1017     return xasprintf("wildcards=%#10"PRIx32" "
1018                      " in_port=%5"PRId16" "
1019                      " dl_src="ETH_ADDR_FMT" "
1020                      " dl_dst="ETH_ADDR_FMT" "
1021                      " dl_vlan=%5"PRId16" "
1022                      " dl_vlan_pcp=%3"PRId8" "
1023                      " dl_type=%#6"PRIx16" "
1024                      " nw_tos=%#4"PRIx8" "
1025                      " nw_proto=%#4"PRIx16" "
1026                      " nw_src=%#10"PRIx32" "
1027                      " nw_dst=%#10"PRIx32" "
1028                      " tp_src=%5"PRId16" "
1029                      " tp_dst=%5"PRId16,
1030                      ntohl(match->wildcards),
1031                      ntohs(match->in_port),
1032                      ETH_ADDR_ARGS(match->dl_src),
1033                      ETH_ADDR_ARGS(match->dl_dst),
1034                      ntohs(match->dl_vlan),
1035                      match->dl_vlan_pcp,
1036                      ntohs(match->dl_type),
1037                      match->nw_tos,
1038                      match->nw_proto,
1039                      ntohl(match->nw_src),
1040                      ntohl(match->nw_dst),
1041                      ntohs(match->tp_src),
1042                      ntohs(match->tp_dst));
1043 }
1044
1045 static uint32_t
1046 vendor_code_to_id(uint8_t code)
1047 {
1048     switch (code) {
1049 #define OFPUTIL_VENDOR(NAME, VENDOR_ID) case NAME: return VENDOR_ID;
1050         OFPUTIL_VENDORS
1051 #undef OFPUTIL_VENDOR
1052     default:
1053         return UINT32_MAX;
1054     }
1055 }
1056
1057 /* Creates and returns an OpenFlow message of type OFPT_ERROR with the error
1058  * information taken from 'error', whose encoding must be as described in the
1059  * large comment in ofp-util.h.  If 'oh' is nonnull, then the error will use
1060  * oh->xid as its transaction ID, and it will include up to the first 64 bytes
1061  * of 'oh'.
1062  *
1063  * Returns NULL if 'error' is not an OpenFlow error code. */
1064 struct ofpbuf *
1065 make_ofp_error_msg(int error, const struct ofp_header *oh)
1066 {
1067     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1068
1069     struct ofpbuf *buf;
1070     const void *data;
1071     size_t len;
1072     uint8_t vendor;
1073     uint16_t type;
1074     uint16_t code;
1075     ovs_be32 xid;
1076
1077     if (!is_ofp_error(error)) {
1078         /* We format 'error' with strerror() here since it seems likely to be
1079          * a system errno value. */
1080         VLOG_WARN_RL(&rl, "invalid OpenFlow error code %d (%s)",
1081                      error, strerror(error));
1082         return NULL;
1083     }
1084
1085     if (oh) {
1086         xid = oh->xid;
1087         data = oh;
1088         len = ntohs(oh->length);
1089         if (len > 64) {
1090             len = 64;
1091         }
1092     } else {
1093         xid = 0;
1094         data = NULL;
1095         len = 0;
1096     }
1097
1098     vendor = get_ofp_err_vendor(error);
1099     type = get_ofp_err_type(error);
1100     code = get_ofp_err_code(error);
1101     if (vendor == OFPUTIL_VENDOR_OPENFLOW) {
1102         struct ofp_error_msg *oem;
1103
1104         oem = make_openflow_xid(len + sizeof *oem, OFPT_ERROR, xid, &buf);
1105         oem->type = htons(type);
1106         oem->code = htons(code);
1107     } else {
1108         struct ofp_error_msg *oem;
1109         struct nx_vendor_error *nve;
1110         uint32_t vendor_id;
1111
1112         vendor_id = vendor_code_to_id(vendor);
1113         if (vendor_id == UINT32_MAX) {
1114             VLOG_WARN_RL(&rl, "error %x contains invalid vendor code %d",
1115                          error, vendor);
1116             return NULL;
1117         }
1118
1119         oem = make_openflow_xid(len + sizeof *oem + sizeof *nve,
1120                                 OFPT_ERROR, xid, &buf);
1121         oem->type = htons(NXET_VENDOR);
1122         oem->code = htons(NXVC_VENDOR_ERROR);
1123
1124         nve = ofpbuf_put_uninit(buf, sizeof *nve);
1125         nve->vendor = htonl(vendor_id);
1126         nve->type = htons(type);
1127         nve->code = htons(code);
1128     }
1129
1130     if (len) {
1131         ofpbuf_put(buf, data, len);
1132     }
1133
1134     return buf;
1135 }
1136
1137 /* Attempts to pull 'actions_len' bytes from the front of 'b'.  Returns 0 if
1138  * successful, otherwise an OpenFlow error.
1139  *
1140  * If successful, the first action is stored in '*actionsp' and the number of
1141  * "union ofp_action" size elements into '*n_actionsp'.  Otherwise NULL and 0
1142  * are stored, respectively.
1143  *
1144  * This function does not check that the actions are valid (the caller should
1145  * do so, with validate_actions()).  The caller is also responsible for making
1146  * sure that 'b->data' is initially aligned appropriately for "union
1147  * ofp_action". */
1148 int
1149 ofputil_pull_actions(struct ofpbuf *b, unsigned int actions_len,
1150                      union ofp_action **actionsp, size_t *n_actionsp)
1151 {
1152     if (actions_len % OFP_ACTION_ALIGN != 0) {
1153         VLOG_DBG_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
1154                     "is not a multiple of %d", actions_len, OFP_ACTION_ALIGN);
1155         goto error;
1156     }
1157
1158     *actionsp = ofpbuf_try_pull(b, actions_len);
1159     if (*actionsp == NULL) {
1160         VLOG_DBG_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
1161                     "exceeds remaining message length (%zu)",
1162                     actions_len, b->size);
1163         goto error;
1164     }
1165
1166     *n_actionsp = actions_len / OFP_ACTION_ALIGN;
1167     return 0;
1168
1169 error:
1170     *actionsp = NULL;
1171     *n_actionsp = 0;
1172     return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1173 }