Implement arbitrary bitwise masks for tun_id field.
[sliver-openvswitch.git] / lib / ofp-util.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "ofp-print.h"
19 #include <errno.h>
20 #include <inttypes.h>
21 #include <stdlib.h>
22 #include "byte-order.h"
23 #include "classifier.h"
24 #include "dynamic-string.h"
25 #include "multipath.h"
26 #include "nx-match.h"
27 #include "ofp-errors.h"
28 #include "ofp-util.h"
29 #include "ofpbuf.h"
30 #include "packets.h"
31 #include "random.h"
32 #include "type-props.h"
33 #include "vlog.h"
34
35 VLOG_DEFINE_THIS_MODULE(ofp_util);
36
37 /* Rate limit for OpenFlow message parse errors.  These always indicate a bug
38  * in the peer and so there's not much point in showing a lot of them. */
39 static struct vlog_rate_limit bad_ofmsg_rl = VLOG_RATE_LIMIT_INIT(1, 5);
40
41 /* Given the wildcard bit count in the least-significant 6 of 'wcbits', returns
42  * an IP netmask with a 1 in each bit that must match and a 0 in each bit that
43  * is wildcarded.
44  *
45  * The bits in 'wcbits' are in the format used in enum ofp_flow_wildcards: 0
46  * is exact match, 1 ignores the LSB, 2 ignores the 2 least-significant bits,
47  * ..., 32 and higher wildcard the entire field.  This is the *opposite* of the
48  * usual convention where e.g. /24 indicates that 8 bits (not 24 bits) are
49  * wildcarded. */
50 ovs_be32
51 ofputil_wcbits_to_netmask(int wcbits)
52 {
53     wcbits &= 0x3f;
54     return wcbits < 32 ? htonl(~((1u << wcbits) - 1)) : 0;
55 }
56
57 /* Given the IP netmask 'netmask', returns the number of bits of the IP address
58  * that it wildcards.  'netmask' must be a CIDR netmask (see ip_is_cidr()). */
59 int
60 ofputil_netmask_to_wcbits(ovs_be32 netmask)
61 {
62     assert(ip_is_cidr(netmask));
63 #if __GNUC__ >= 4
64     return netmask == htonl(0) ? 32 : __builtin_ctz(ntohl(netmask));
65 #else
66     int wcbits;
67
68     for (wcbits = 32; netmask; wcbits--) {
69         netmask &= netmask - 1;
70     }
71
72     return wcbits;
73 #endif
74 }
75
76 /* A list of the FWW_* and OFPFW_ bits that have the same value, meaning, and
77  * name. */
78 #define WC_INVARIANT_LIST \
79     WC_INVARIANT_BIT(IN_PORT) \
80     WC_INVARIANT_BIT(DL_SRC) \
81     WC_INVARIANT_BIT(DL_DST) \
82     WC_INVARIANT_BIT(DL_TYPE) \
83     WC_INVARIANT_BIT(NW_PROTO) \
84     WC_INVARIANT_BIT(TP_SRC) \
85     WC_INVARIANT_BIT(TP_DST)
86
87 /* Verify that all of the invariant bits (as defined on WC_INVARIANT_LIST)
88  * actually have the same names and values. */
89 #define WC_INVARIANT_BIT(NAME) BUILD_ASSERT_DECL(FWW_##NAME == OFPFW_##NAME);
90     WC_INVARIANT_LIST
91 #undef WC_INVARIANT_BIT
92
93 /* WC_INVARIANTS is the invariant bits (as defined on WC_INVARIANT_LIST) all
94  * OR'd together. */
95 enum {
96     WC_INVARIANTS = 0
97 #define WC_INVARIANT_BIT(NAME) | FWW_##NAME
98     WC_INVARIANT_LIST
99 #undef WC_INVARIANT_BIT
100 };
101
102 /* Converts the ofp_match in 'match' into a cls_rule in 'rule', with the given
103  * 'priority'.
104  *
105  * 'flow_format' must either NXFF_OPENFLOW10 or NXFF_TUN_ID_FROM_COOKIE.  In
106  * the latter case only, 'flow''s tun_id field will be taken from the high bits
107  * of 'cookie', if 'match''s wildcards do not indicate that tun_id is
108  * wildcarded. */
109 void
110 ofputil_cls_rule_from_match(const struct ofp_match *match,
111                             unsigned int priority,
112                             enum nx_flow_format flow_format,
113                             ovs_be64 cookie, struct cls_rule *rule)
114 {
115     struct flow_wildcards *wc = &rule->wc;
116     unsigned int ofpfw;
117     ovs_be16 vid, pcp;
118
119     /* Initialize rule->priority. */
120     ofpfw = ntohl(match->wildcards);
121     ofpfw &= flow_format == NXFF_TUN_ID_FROM_COOKIE ? OVSFW_ALL : OFPFW_ALL;
122     rule->priority = !ofpfw ? UINT16_MAX : priority;
123
124     /* Initialize most of rule->wc. */
125     flow_wildcards_init_catchall(wc);
126     wc->wildcards = ofpfw & WC_INVARIANTS;
127     if (ofpfw & OFPFW_NW_TOS) {
128         wc->wildcards |= FWW_NW_TOS;
129     }
130     wc->nw_src_mask = ofputil_wcbits_to_netmask(ofpfw >> OFPFW_NW_SRC_SHIFT);
131     wc->nw_dst_mask = ofputil_wcbits_to_netmask(ofpfw >> OFPFW_NW_DST_SHIFT);
132
133     if (flow_format == NXFF_TUN_ID_FROM_COOKIE && !(ofpfw & NXFW_TUN_ID)) {
134         rule->flow.tun_id = htonll(ntohll(cookie) >> 32);
135     }
136
137     if (ofpfw & OFPFW_DL_DST) {
138         /* OpenFlow 1.0 OFPFW_DL_DST covers the whole Ethernet destination, but
139          * Open vSwitch breaks the Ethernet destination into bits as FWW_DL_DST
140          * and FWW_ETH_MCAST. */
141         wc->wildcards |= FWW_ETH_MCAST;
142     }
143
144     /* Initialize most of rule->flow. */
145     rule->flow.nw_src = match->nw_src;
146     rule->flow.nw_dst = match->nw_dst;
147     rule->flow.in_port = (match->in_port == htons(OFPP_LOCAL) ? ODPP_LOCAL
148                      : ntohs(match->in_port));
149     rule->flow.dl_type = match->dl_type;
150     rule->flow.tp_src = match->tp_src;
151     rule->flow.tp_dst = match->tp_dst;
152     memcpy(rule->flow.dl_src, match->dl_src, ETH_ADDR_LEN);
153     memcpy(rule->flow.dl_dst, match->dl_dst, ETH_ADDR_LEN);
154     rule->flow.nw_tos = match->nw_tos;
155     rule->flow.nw_proto = match->nw_proto;
156
157     /* Translate VLANs. */
158     vid = match->dl_vlan & htons(VLAN_VID_MASK);
159     pcp = htons((match->dl_vlan_pcp << VLAN_PCP_SHIFT) & VLAN_PCP_MASK);
160     switch (ofpfw & (OFPFW_DL_VLAN | OFPFW_DL_VLAN_PCP)) {
161     case OFPFW_DL_VLAN | OFPFW_DL_VLAN_PCP:
162         /* Wildcard everything. */
163         rule->flow.vlan_tci = htons(0);
164         rule->wc.vlan_tci_mask = htons(0);
165         break;
166
167     case OFPFW_DL_VLAN_PCP:
168         if (match->dl_vlan == htons(OFP_VLAN_NONE)) {
169             /* Match only packets without 802.1Q header. */
170             rule->flow.vlan_tci = htons(0);
171             rule->wc.vlan_tci_mask = htons(0xffff);
172         } else {
173             /* Wildcard PCP, specific VID. */
174             rule->flow.vlan_tci = vid | htons(VLAN_CFI);
175             rule->wc.vlan_tci_mask = htons(VLAN_VID_MASK | VLAN_CFI);
176         }
177         break;
178
179     case OFPFW_DL_VLAN:
180         /* Wildcard VID, specific PCP. */
181         rule->flow.vlan_tci = pcp | htons(VLAN_CFI);
182         rule->wc.vlan_tci_mask = htons(VLAN_PCP_MASK | VLAN_CFI);
183         break;
184
185     case 0:
186         if (match->dl_vlan == htons(OFP_VLAN_NONE)) {
187             /* This case is odd, since we can't have a specific PCP without an
188              * 802.1Q header.  However, older versions of OVS treated this as
189              * matching packets withut an 802.1Q header, so we do here too. */
190             rule->flow.vlan_tci = htons(0);
191             rule->wc.vlan_tci_mask = htons(0xffff);
192         } else {
193             /* Specific VID and PCP. */
194             rule->flow.vlan_tci = vid | pcp | htons(VLAN_CFI);
195             rule->wc.vlan_tci_mask = htons(0xffff);
196         }
197         break;
198     }
199
200     /* Clean up. */
201     cls_rule_zero_wildcarded_fields(rule);
202 }
203
204 /* Convert 'rule' into the OpenFlow match structure 'match'.  'flow_format'
205  * must either NXFF_OPENFLOW10 or NXFF_TUN_ID_FROM_COOKIE.
206  *
207  * The NXFF_TUN_ID_FROM_COOKIE flow format requires modifying the flow cookie.
208  * This function can help with that, if 'cookie_out' is nonnull.  For
209  * NXFF_OPENFLOW10, or if the tunnel ID is wildcarded, 'cookie_in' will be
210  * copied directly to '*cookie_out'.  For NXFF_TUN_ID_FROM_COOKIE when tunnel
211  * ID is matched, 'cookie_in' will be modified appropriately before setting
212  * '*cookie_out'.
213  */
214 void
215 ofputil_cls_rule_to_match(const struct cls_rule *rule,
216                           enum nx_flow_format flow_format,
217                           struct ofp_match *match,
218                           ovs_be64 cookie_in, ovs_be64 *cookie_out)
219 {
220     const struct flow_wildcards *wc = &rule->wc;
221     unsigned int ofpfw;
222
223     /* Figure out most OpenFlow wildcards. */
224     ofpfw = wc->wildcards & WC_INVARIANTS;
225     ofpfw |= ofputil_netmask_to_wcbits(wc->nw_src_mask) << OFPFW_NW_SRC_SHIFT;
226     ofpfw |= ofputil_netmask_to_wcbits(wc->nw_dst_mask) << OFPFW_NW_DST_SHIFT;
227     if (wc->wildcards & FWW_NW_TOS) {
228         ofpfw |= OFPFW_NW_TOS;
229     }
230
231     /* Tunnel ID. */
232     if (flow_format == NXFF_TUN_ID_FROM_COOKIE) {
233         if (wc->tun_id_mask == htonll(0)) {
234             ofpfw |= NXFW_TUN_ID;
235         } else {
236             uint32_t cookie_lo = ntohll(cookie_in);
237             uint32_t cookie_hi = ntohll(rule->flow.tun_id);
238             cookie_in = htonll(cookie_lo | ((uint64_t) cookie_hi << 32));
239         }
240     }
241     if (cookie_out) {
242         *cookie_out = cookie_in;
243     }
244
245     /* Translate VLANs. */
246     match->dl_vlan = htons(0);
247     match->dl_vlan_pcp = 0;
248     if (rule->wc.vlan_tci_mask == htons(0)) {
249         ofpfw |= OFPFW_DL_VLAN | OFPFW_DL_VLAN_PCP;
250     } else if (rule->wc.vlan_tci_mask & htons(VLAN_CFI)
251                && !(rule->flow.vlan_tci & htons(VLAN_CFI))) {
252         match->dl_vlan = htons(OFP_VLAN_NONE);
253     } else {
254         if (!(rule->wc.vlan_tci_mask & htons(VLAN_VID_MASK))) {
255             ofpfw |= OFPFW_DL_VLAN;
256         } else {
257             match->dl_vlan = htons(vlan_tci_to_vid(rule->flow.vlan_tci));
258         }
259
260         if (!(rule->wc.vlan_tci_mask & htons(VLAN_PCP_MASK))) {
261             ofpfw |= OFPFW_DL_VLAN_PCP;
262         } else {
263             match->dl_vlan_pcp = vlan_tci_to_pcp(rule->flow.vlan_tci);
264         }
265     }
266
267     /* Compose most of the match structure. */
268     match->wildcards = htonl(ofpfw);
269     match->in_port = htons(rule->flow.in_port == ODPP_LOCAL ? OFPP_LOCAL
270                            : rule->flow.in_port);
271     memcpy(match->dl_src, rule->flow.dl_src, ETH_ADDR_LEN);
272     memcpy(match->dl_dst, rule->flow.dl_dst, ETH_ADDR_LEN);
273     match->dl_type = rule->flow.dl_type;
274     match->nw_src = rule->flow.nw_src;
275     match->nw_dst = rule->flow.nw_dst;
276     match->nw_tos = rule->flow.nw_tos;
277     match->nw_proto = rule->flow.nw_proto;
278     match->tp_src = rule->flow.tp_src;
279     match->tp_dst = rule->flow.tp_dst;
280     memset(match->pad1, '\0', sizeof match->pad1);
281     memset(match->pad2, '\0', sizeof match->pad2);
282 }
283
284 /* Returns a transaction ID to use for an outgoing OpenFlow message. */
285 static ovs_be32
286 alloc_xid(void)
287 {
288     static uint32_t next_xid = 1;
289     return htonl(next_xid++);
290 }
291 \f
292 /* Basic parsing of OpenFlow messages. */
293
294 struct ofputil_msg_type {
295     enum ofputil_msg_code code; /* OFPUTIL_*. */
296     uint32_t value;             /* OFPT_*, OFPST_*, NXT_*, or NXST_*. */
297     const char *name;           /* e.g. "OFPT_FLOW_REMOVED". */
298     unsigned int min_size;      /* Minimum total message size in bytes. */
299     /* 0 if 'min_size' is the exact size that the message must be.  Otherwise,
300      * the message may exceed 'min_size' by an even multiple of this value. */
301     unsigned int extra_multiple;
302 };
303
304 struct ofputil_msg_category {
305     const char *name;           /* e.g. "OpenFlow message" */
306     const struct ofputil_msg_type *types;
307     size_t n_types;
308     int missing_error;          /* ofp_mkerr() value for missing type. */
309 };
310
311 static bool
312 ofputil_length_ok(const struct ofputil_msg_category *cat,
313                   const struct ofputil_msg_type *type,
314                   unsigned int size)
315 {
316     switch (type->extra_multiple) {
317     case 0:
318         if (size != type->min_size) {
319             VLOG_WARN_RL(&bad_ofmsg_rl, "received %s %s with incorrect "
320                          "length %u (expected length %u)",
321                          cat->name, type->name, size, type->min_size);
322             return false;
323         }
324         return true;
325
326     case 1:
327         if (size < type->min_size) {
328             VLOG_WARN_RL(&bad_ofmsg_rl, "received %s %s with incorrect "
329                          "length %u (expected length at least %u bytes)",
330                          cat->name, type->name, size, type->min_size);
331             return false;
332         }
333         return true;
334
335     default:
336         if (size < type->min_size
337             || (size - type->min_size) % type->extra_multiple) {
338             VLOG_WARN_RL(&bad_ofmsg_rl, "received %s %s with incorrect "
339                          "length %u (must be exactly %u bytes or longer "
340                          "by an integer multiple of %u bytes)",
341                          cat->name, type->name, size,
342                          type->min_size, type->extra_multiple);
343             return false;
344         }
345         return true;
346     }
347 }
348
349 static int
350 ofputil_lookup_openflow_message(const struct ofputil_msg_category *cat,
351                                 uint32_t value, unsigned int size,
352                                 const struct ofputil_msg_type **typep)
353 {
354     const struct ofputil_msg_type *type;
355
356     for (type = cat->types; type < &cat->types[cat->n_types]; type++) {
357         if (type->value == value) {
358             if (!ofputil_length_ok(cat, type, size)) {
359                 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
360             }
361             *typep = type;
362             return 0;
363         }
364     }
365
366     VLOG_WARN_RL(&bad_ofmsg_rl, "received %s of unknown type %"PRIu32,
367                  cat->name, value);
368     return cat->missing_error;
369 }
370
371 static int
372 ofputil_decode_vendor(const struct ofp_header *oh,
373                       const struct ofputil_msg_type **typep)
374 {
375     static const struct ofputil_msg_type nxt_messages[] = {
376         { OFPUTIL_NXT_STATUS_REQUEST,
377           NXT_STATUS_REQUEST, "NXT_STATUS_REQUEST",
378           sizeof(struct nicira_header), 1 },
379
380         { OFPUTIL_NXT_STATUS_REPLY,
381           NXT_STATUS_REPLY, "NXT_STATUS_REPLY",
382           sizeof(struct nicira_header), 1 },
383
384         { OFPUTIL_NXT_TUN_ID_FROM_COOKIE,
385           NXT_TUN_ID_FROM_COOKIE, "NXT_TUN_ID_FROM_COOKIE",
386           sizeof(struct nxt_tun_id_cookie), 0 },
387
388         { OFPUTIL_NXT_ROLE_REQUEST,
389           NXT_ROLE_REQUEST, "NXT_ROLE_REQUEST",
390           sizeof(struct nx_role_request), 0 },
391
392         { OFPUTIL_NXT_ROLE_REPLY,
393           NXT_ROLE_REPLY, "NXT_ROLE_REPLY",
394           sizeof(struct nx_role_request), 0 },
395
396         { OFPUTIL_NXT_SET_FLOW_FORMAT,
397           NXT_SET_FLOW_FORMAT, "NXT_SET_FLOW_FORMAT",
398           sizeof(struct nxt_set_flow_format), 0 },
399
400         { OFPUTIL_NXT_FLOW_MOD,
401           NXT_FLOW_MOD, "NXT_FLOW_MOD",
402           sizeof(struct nx_flow_mod), 8 },
403
404         { OFPUTIL_NXT_FLOW_REMOVED,
405           NXT_FLOW_REMOVED, "NXT_FLOW_REMOVED",
406           sizeof(struct nx_flow_removed), 8 },
407     };
408
409     static const struct ofputil_msg_category nxt_category = {
410         "Nicira extension message",
411         nxt_messages, ARRAY_SIZE(nxt_messages),
412         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE)
413     };
414
415     const struct ofp_vendor_header *ovh;
416     const struct nicira_header *nh;
417
418     ovh = (const struct ofp_vendor_header *) oh;
419     if (ovh->vendor != htonl(NX_VENDOR_ID)) {
420         VLOG_WARN_RL(&bad_ofmsg_rl, "received vendor message for unknown "
421                      "vendor %"PRIx32, ntohl(ovh->vendor));
422         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_VENDOR);
423     }
424
425     if (ntohs(ovh->header.length) < sizeof(struct nicira_header)) {
426         VLOG_WARN_RL(&bad_ofmsg_rl, "received Nicira vendor message of "
427                      "length %u (expected at least %zu)",
428                      ntohs(ovh->header.length), sizeof(struct nicira_header));
429         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
430     }
431
432     nh = (const struct nicira_header *) oh;
433     return ofputil_lookup_openflow_message(&nxt_category, ntohl(nh->subtype),
434                                            ntohs(oh->length), typep);
435 }
436
437 static int
438 check_nxstats_msg(const struct ofp_header *oh)
439 {
440     const struct ofp_stats_request *osr;
441     ovs_be32 vendor;
442
443     osr = (const struct ofp_stats_request *) oh;
444
445     memcpy(&vendor, osr->body, sizeof vendor);
446     if (vendor != htonl(NX_VENDOR_ID)) {
447         VLOG_WARN_RL(&bad_ofmsg_rl, "received vendor stats message for "
448                      "unknown vendor %"PRIx32, ntohl(vendor));
449         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_VENDOR);
450     }
451
452     if (ntohs(osr->header.length) < sizeof(struct nicira_stats_msg)) {
453         VLOG_WARN_RL(&bad_ofmsg_rl, "truncated Nicira stats message");
454         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
455     }
456
457     return 0;
458 }
459
460 static int
461 ofputil_decode_nxst_request(const struct ofp_header *oh,
462                             const struct ofputil_msg_type **typep)
463 {
464     static const struct ofputil_msg_type nxst_requests[] = {
465         { OFPUTIL_NXST_FLOW_REQUEST,
466           NXST_FLOW, "NXST_FLOW request",
467           sizeof(struct nx_flow_stats_request), 8 },
468
469         { OFPUTIL_NXST_AGGREGATE_REQUEST,
470           NXST_AGGREGATE, "NXST_AGGREGATE request",
471           sizeof(struct nx_aggregate_stats_request), 8 },
472     };
473
474     static const struct ofputil_msg_category nxst_request_category = {
475         "Nicira extension statistics request",
476         nxst_requests, ARRAY_SIZE(nxst_requests),
477         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE)
478     };
479
480     const struct nicira_stats_msg *nsm;
481     int error;
482
483     error = check_nxstats_msg(oh);
484     if (error) {
485         return error;
486     }
487
488     nsm = (struct nicira_stats_msg *) oh;
489     return ofputil_lookup_openflow_message(&nxst_request_category,
490                                            ntohl(nsm->subtype),
491                                            ntohs(oh->length), typep);
492 }
493
494 static int
495 ofputil_decode_nxst_reply(const struct ofp_header *oh,
496                           const struct ofputil_msg_type **typep)
497 {
498     static const struct ofputil_msg_type nxst_replies[] = {
499         { OFPUTIL_NXST_FLOW_REPLY,
500           NXST_FLOW, "NXST_FLOW reply",
501           sizeof(struct nicira_stats_msg), 8 },
502
503         { OFPUTIL_NXST_AGGREGATE_REPLY,
504           NXST_AGGREGATE, "NXST_AGGREGATE reply",
505           sizeof(struct nx_aggregate_stats_reply), 0 },
506     };
507
508     static const struct ofputil_msg_category nxst_reply_category = {
509         "Nicira extension statistics reply",
510         nxst_replies, ARRAY_SIZE(nxst_replies),
511         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE)
512     };
513
514     const struct nicira_stats_msg *nsm;
515     int error;
516
517     error = check_nxstats_msg(oh);
518     if (error) {
519         return error;
520     }
521
522     nsm = (struct nicira_stats_msg *) oh;
523     return ofputil_lookup_openflow_message(&nxst_reply_category,
524                                            ntohl(nsm->subtype),
525                                            ntohs(oh->length), typep);
526 }
527
528 static int
529 ofputil_decode_ofpst_request(const struct ofp_header *oh,
530                              const struct ofputil_msg_type **typep)
531 {
532     enum { OSR_SIZE = sizeof(struct ofp_stats_request) };
533     static const struct ofputil_msg_type ofpst_requests[] = {
534         { OFPUTIL_OFPST_DESC_REQUEST,
535           OFPST_DESC, "OFPST_DESC request",
536           OSR_SIZE, 0 },
537
538         { OFPUTIL_OFPST_FLOW_REQUEST,
539           OFPST_FLOW, "OFPST_FLOW request",
540           OSR_SIZE + sizeof(struct ofp_flow_stats_request), 0 },
541
542         { OFPUTIL_OFPST_AGGREGATE_REQUEST,
543           OFPST_AGGREGATE, "OFPST_AGGREGATE request",
544           OSR_SIZE + sizeof(struct ofp_aggregate_stats_request), 0 },
545
546         { OFPUTIL_OFPST_TABLE_REQUEST,
547           OFPST_TABLE, "OFPST_TABLE request",
548           OSR_SIZE, 0 },
549
550         { OFPUTIL_OFPST_PORT_REQUEST,
551           OFPST_PORT, "OFPST_PORT request",
552           OSR_SIZE + sizeof(struct ofp_port_stats_request), 0 },
553
554         { OFPUTIL_OFPST_QUEUE_REQUEST,
555           OFPST_QUEUE, "OFPST_QUEUE request",
556           OSR_SIZE + sizeof(struct ofp_queue_stats_request), 0 },
557
558         { 0,
559           OFPST_VENDOR, "OFPST_VENDOR request",
560           OSR_SIZE + sizeof(uint32_t), 1 },
561     };
562
563     static const struct ofputil_msg_category ofpst_request_category = {
564         "OpenFlow statistics",
565         ofpst_requests, ARRAY_SIZE(ofpst_requests),
566         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT)
567     };
568
569     const struct ofp_stats_request *osr;
570     int error;
571
572     osr = (const struct ofp_stats_request *) oh;
573     error = ofputil_lookup_openflow_message(&ofpst_request_category,
574                                             ntohs(osr->type),
575                                             ntohs(oh->length), typep);
576     if (!error && osr->type == htons(OFPST_VENDOR)) {
577         error = ofputil_decode_nxst_request(oh, typep);
578     }
579     return error;
580 }
581
582 static int
583 ofputil_decode_ofpst_reply(const struct ofp_header *oh,
584                            const struct ofputil_msg_type **typep)
585 {
586     enum { OSR_SIZE = sizeof(struct ofp_stats_reply) };
587     static const struct ofputil_msg_type ofpst_replies[] = {
588         { OFPUTIL_OFPST_DESC_REPLY,
589           OFPST_DESC, "OFPST_DESC reply",
590           OSR_SIZE + sizeof(struct ofp_desc_stats), 0 },
591
592         { OFPUTIL_OFPST_FLOW_REPLY,
593           OFPST_FLOW, "OFPST_FLOW reply",
594           OSR_SIZE, 1 },
595
596         { OFPUTIL_OFPST_AGGREGATE_REPLY,
597           OFPST_AGGREGATE, "OFPST_AGGREGATE reply",
598           OSR_SIZE + sizeof(struct ofp_aggregate_stats_reply), 0 },
599
600         { OFPUTIL_OFPST_TABLE_REPLY,
601           OFPST_TABLE, "OFPST_TABLE reply",
602           OSR_SIZE, sizeof(struct ofp_table_stats) },
603
604         { OFPUTIL_OFPST_PORT_REPLY,
605           OFPST_PORT, "OFPST_PORT reply",
606           OSR_SIZE, sizeof(struct ofp_port_stats) },
607
608         { OFPUTIL_OFPST_QUEUE_REPLY,
609           OFPST_QUEUE, "OFPST_QUEUE reply",
610           OSR_SIZE, sizeof(struct ofp_queue_stats) },
611
612         { 0,
613           OFPST_VENDOR, "OFPST_VENDOR reply",
614           OSR_SIZE + sizeof(uint32_t), 1 },
615     };
616
617     static const struct ofputil_msg_category ofpst_reply_category = {
618         "OpenFlow statistics",
619         ofpst_replies, ARRAY_SIZE(ofpst_replies),
620         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT)
621     };
622
623     const struct ofp_stats_reply *osr = (const struct ofp_stats_reply *) oh;
624     int error;
625
626     error = ofputil_lookup_openflow_message(&ofpst_reply_category,
627                                            ntohs(osr->type),
628                                            ntohs(oh->length), typep);
629     if (!error && osr->type == htons(OFPST_VENDOR)) {
630         error = ofputil_decode_nxst_reply(oh, typep);
631     }
632     return error;
633 }
634
635 /* Decodes the message type represented by 'oh'.  Returns 0 if successful or
636  * an OpenFlow error code constructed with ofp_mkerr() on failure.  Either
637  * way, stores in '*typep' a type structure that can be inspected with the
638  * ofputil_msg_type_*() functions.
639  *
640  * oh->length must indicate the correct length of the message (and must be at
641  * least sizeof(struct ofp_header)).
642  *
643  * Success indicates that 'oh' is at least as long as the minimum-length
644  * message of its type. */
645 int
646 ofputil_decode_msg_type(const struct ofp_header *oh,
647                         const struct ofputil_msg_type **typep)
648 {
649     static const struct ofputil_msg_type ofpt_messages[] = {
650         { OFPUTIL_OFPT_HELLO,
651           OFPT_HELLO, "OFPT_HELLO",
652           sizeof(struct ofp_hello), 1 },
653
654         { OFPUTIL_OFPT_ERROR,
655           OFPT_ERROR, "OFPT_ERROR",
656           sizeof(struct ofp_error_msg), 1 },
657
658         { OFPUTIL_OFPT_ECHO_REQUEST,
659           OFPT_ECHO_REQUEST, "OFPT_ECHO_REQUEST",
660           sizeof(struct ofp_header), 1 },
661
662         { OFPUTIL_OFPT_ECHO_REPLY,
663           OFPT_ECHO_REPLY, "OFPT_ECHO_REPLY",
664           sizeof(struct ofp_header), 1 },
665
666         { OFPUTIL_OFPT_FEATURES_REQUEST,
667           OFPT_FEATURES_REQUEST, "OFPT_FEATURES_REQUEST",
668           sizeof(struct ofp_header), 0 },
669
670         { OFPUTIL_OFPT_FEATURES_REPLY,
671           OFPT_FEATURES_REPLY, "OFPT_FEATURES_REPLY",
672           sizeof(struct ofp_switch_features), sizeof(struct ofp_phy_port) },
673
674         { OFPUTIL_OFPT_GET_CONFIG_REQUEST,
675           OFPT_GET_CONFIG_REQUEST, "OFPT_GET_CONFIG_REQUEST",
676           sizeof(struct ofp_header), 0 },
677
678         { OFPUTIL_OFPT_GET_CONFIG_REPLY,
679           OFPT_GET_CONFIG_REPLY, "OFPT_GET_CONFIG_REPLY",
680           sizeof(struct ofp_switch_config), 0 },
681
682         { OFPUTIL_OFPT_SET_CONFIG,
683           OFPT_SET_CONFIG, "OFPT_SET_CONFIG",
684           sizeof(struct ofp_switch_config), 0 },
685
686         { OFPUTIL_OFPT_PACKET_IN,
687           OFPT_PACKET_IN, "OFPT_PACKET_IN",
688           offsetof(struct ofp_packet_in, data), 1 },
689
690         { OFPUTIL_OFPT_FLOW_REMOVED,
691           OFPT_FLOW_REMOVED, "OFPT_FLOW_REMOVED",
692           sizeof(struct ofp_flow_removed), 0 },
693
694         { OFPUTIL_OFPT_PORT_STATUS,
695           OFPT_PORT_STATUS, "OFPT_PORT_STATUS",
696           sizeof(struct ofp_port_status), 0 },
697
698         { OFPUTIL_OFPT_PACKET_OUT,
699           OFPT_PACKET_OUT, "OFPT_PACKET_OUT",
700           sizeof(struct ofp_packet_out), 1 },
701
702         { OFPUTIL_OFPT_FLOW_MOD,
703           OFPT_FLOW_MOD, "OFPT_FLOW_MOD",
704           sizeof(struct ofp_flow_mod), 1 },
705
706         { OFPUTIL_OFPT_PORT_MOD,
707           OFPT_PORT_MOD, "OFPT_PORT_MOD",
708           sizeof(struct ofp_port_mod), 0 },
709
710         { 0,
711           OFPT_STATS_REQUEST, "OFPT_STATS_REQUEST",
712           sizeof(struct ofp_stats_request), 1 },
713
714         { 0,
715           OFPT_STATS_REPLY, "OFPT_STATS_REPLY",
716           sizeof(struct ofp_stats_reply), 1 },
717
718         { OFPUTIL_OFPT_BARRIER_REQUEST,
719           OFPT_BARRIER_REQUEST, "OFPT_BARRIER_REQUEST",
720           sizeof(struct ofp_header), 0 },
721
722         { OFPUTIL_OFPT_BARRIER_REPLY,
723           OFPT_BARRIER_REPLY, "OFPT_BARRIER_REPLY",
724           sizeof(struct ofp_header), 0 },
725
726         { 0,
727           OFPT_VENDOR, "OFPT_VENDOR",
728           sizeof(struct ofp_vendor_header), 1 },
729     };
730
731     static const struct ofputil_msg_category ofpt_category = {
732         "OpenFlow message",
733         ofpt_messages, ARRAY_SIZE(ofpt_messages),
734         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE)
735     };
736
737     int error;
738
739     error = ofputil_lookup_openflow_message(&ofpt_category, oh->type,
740                                             ntohs(oh->length), typep);
741     if (!error) {
742         switch (oh->type) {
743         case OFPT_VENDOR:
744             error = ofputil_decode_vendor(oh, typep);
745             break;
746
747         case OFPT_STATS_REQUEST:
748             error = ofputil_decode_ofpst_request(oh, typep);
749             break;
750
751         case OFPT_STATS_REPLY:
752             error = ofputil_decode_ofpst_reply(oh, typep);
753
754         default:
755             break;
756         }
757     }
758     if (error) {
759         static const struct ofputil_msg_type ofputil_invalid_type = {
760             OFPUTIL_INVALID,
761             0, "OFPUTIL_INVALID",
762             0, 0
763         };
764
765         *typep = &ofputil_invalid_type;
766     }
767     return error;
768 }
769
770 /* Returns an OFPUTIL_* message type code for 'type'. */
771 enum ofputil_msg_code
772 ofputil_msg_type_code(const struct ofputil_msg_type *type)
773 {
774     return type->code;
775 }
776 \f
777 /* Flow formats. */
778
779 bool
780 ofputil_flow_format_is_valid(enum nx_flow_format flow_format)
781 {
782     switch (flow_format) {
783     case NXFF_OPENFLOW10:
784     case NXFF_TUN_ID_FROM_COOKIE:
785     case NXFF_NXM:
786         return true;
787     }
788
789     return false;
790 }
791
792 const char *
793 ofputil_flow_format_to_string(enum nx_flow_format flow_format)
794 {
795     switch (flow_format) {
796     case NXFF_OPENFLOW10:
797         return "openflow10";
798     case NXFF_TUN_ID_FROM_COOKIE:
799         return "tun_id_from_cookie";
800     case NXFF_NXM:
801         return "nxm";
802     default:
803         NOT_REACHED();
804     }
805 }
806
807 int
808 ofputil_flow_format_from_string(const char *s)
809 {
810     return (!strcmp(s, "openflow10") ? NXFF_OPENFLOW10
811             : !strcmp(s, "tun_id_from_cookie") ? NXFF_TUN_ID_FROM_COOKIE
812             : !strcmp(s, "nxm") ? NXFF_NXM
813             : -1);
814 }
815
816 static bool
817 regs_fully_wildcarded(const struct flow_wildcards *wc)
818 {
819     int i;
820
821     for (i = 0; i < FLOW_N_REGS; i++) {
822         if (wc->reg_masks[i] != 0) {
823             return false;
824         }
825     }
826     return true;
827 }
828
829 static inline bool
830 is_nxm_required(const struct cls_rule *rule, bool cookie_support,
831                 ovs_be64 cookie)
832 {
833     const struct flow_wildcards *wc = &rule->wc;
834     ovs_be32 cookie_hi;
835
836     /* Only NXM supports separately wildcards the Ethernet multicast bit. */
837     if (!(wc->wildcards & FWW_DL_DST) != !(wc->wildcards & FWW_ETH_MCAST)) {
838         return true;
839     }
840
841     /* Only NXM supports matching registers. */
842     if (!regs_fully_wildcarded(wc)) {
843         return true;
844     }
845
846     switch (wc->tun_id_mask) {
847     case CONSTANT_HTONLL(0):
848         /* Other formats can fully wildcard tun_id. */
849         break;
850
851     case CONSTANT_HTONLL(UINT64_MAX):
852         /* Only NXM supports matching tunnel ID, unless there is a cookie and
853          * the top 32 bits of the cookie are the desired tunnel ID value. */
854         cookie_hi = htonl(ntohll(cookie) >> 32);
855         if (!cookie_support
856             || (cookie_hi && cookie_hi != ntohll(rule->flow.tun_id))) {
857             return true;
858         }
859         break;
860
861     default:
862         /* Only NXM supports partial matches on tunnel ID. */
863         return true;
864     }
865
866     /* Other formats can express this rule. */
867     return false;
868 }
869
870 /* Returns the minimum nx_flow_format to use for sending 'rule' to a switch
871  * (e.g. to add or remove a flow).  'cookie_support' should be true if the
872  * command to be sent includes a flow cookie (as OFPT_FLOW_MOD does, for
873  * example) or false if the command does not (OFPST_FLOW and OFPST_AGGREGATE do
874  * not, for example).  If 'cookie_support' is true, then 'cookie' should be the
875  * cookie to be sent; otherwise its value is ignored.
876  *
877  * The "best" flow format is chosen on this basis:
878  *
879  *   - It must be capable of expressing the rule.  NXFF_OPENFLOW10 flows can't
880  *     handle tunnel IDs.  NXFF_TUN_ID_FROM_COOKIE flows can't handle registers
881  *     or fixing the Ethernet multicast bit, and can't handle tunnel IDs that
882  *     conflict with the high 32 bits of the cookie or commands that don't
883  *     support cookies.
884  *
885  *   - Otherwise, the chosen format should be as backward compatible as
886  *     possible.  (NXFF_OPENFLOW10 is more backward compatible than
887  *     NXFF_TUN_ID_FROM_COOKIE, which is more backward compatible than
888  *     NXFF_NXM.)
889  */
890 enum nx_flow_format
891 ofputil_min_flow_format(const struct cls_rule *rule, bool cookie_support,
892                         ovs_be64 cookie)
893 {
894     if (is_nxm_required(rule, cookie_support, cookie)) {
895         return NXFF_NXM;
896     } else if (rule->wc.tun_id_mask != htonll(0)) {
897         return NXFF_TUN_ID_FROM_COOKIE;
898     } else {
899         return NXFF_OPENFLOW10;
900     }
901 }
902
903 /* Returns an OpenFlow message that can be used to set the flow format to
904  * 'flow_format'.  */
905 struct ofpbuf *
906 ofputil_make_set_flow_format(enum nx_flow_format flow_format)
907 {
908     struct ofpbuf *msg;
909
910     if (flow_format == NXFF_OPENFLOW10
911         || flow_format == NXFF_TUN_ID_FROM_COOKIE) {
912         struct nxt_tun_id_cookie *tic;
913
914         tic = make_nxmsg(sizeof *tic, NXT_TUN_ID_FROM_COOKIE, &msg);
915         tic->set = flow_format == NXFF_TUN_ID_FROM_COOKIE;
916     } else {
917         struct nxt_set_flow_format *sff;
918
919         sff = make_nxmsg(sizeof *sff, NXT_SET_FLOW_FORMAT, &msg);
920         sff->format = htonl(flow_format);
921     }
922
923     return msg;
924 }
925
926 /* Converts an OFPT_FLOW_MOD or NXT_FLOW_MOD message 'oh' into an abstract
927  * flow_mod in 'fm'.  Returns 0 if successful, otherwise an OpenFlow error
928  * code.
929  *
930  * For OFPT_FLOW_MOD messages, 'flow_format' should be the current flow format
931  * at the time when the message was received.  Otherwise 'flow_format' is
932  * ignored.
933  *
934  * Does not validate the flow_mod actions. */
935 int
936 ofputil_decode_flow_mod(struct flow_mod *fm, const struct ofp_header *oh,
937                         enum nx_flow_format flow_format)
938 {
939     const struct ofputil_msg_type *type;
940     struct ofpbuf b;
941
942     ofpbuf_use_const(&b, oh, ntohs(oh->length));
943
944     ofputil_decode_msg_type(oh, &type);
945     if (ofputil_msg_type_code(type) == OFPUTIL_OFPT_FLOW_MOD) {
946         /* Standard OpenFlow flow_mod. */
947         struct ofp_match match, orig_match;
948         const struct ofp_flow_mod *ofm;
949         int error;
950
951         /* Dissect the message. */
952         ofm = ofpbuf_pull(&b, sizeof *ofm);
953         error = ofputil_pull_actions(&b, b.size, &fm->actions, &fm->n_actions);
954         if (error) {
955             return error;
956         }
957
958         /* Normalize ofm->match.  If normalization actually changes anything,
959          * then log the differences. */
960         match = ofm->match;
961         match.pad1[0] = match.pad2[0] = 0;
962         orig_match = match;
963         normalize_match(&match);
964         if (memcmp(&match, &orig_match, sizeof orig_match)) {
965             if (!VLOG_DROP_INFO(&bad_ofmsg_rl)) {
966                 char *old = ofp_match_to_literal_string(&orig_match);
967                 char *new = ofp_match_to_literal_string(&match);
968                 VLOG_INFO("normalization changed ofp_match, details:");
969                 VLOG_INFO(" pre: %s", old);
970                 VLOG_INFO("post: %s", new);
971                 free(old);
972                 free(new);
973             }
974         }
975
976         /* Translate the message. */
977         ofputil_cls_rule_from_match(&match, ntohs(ofm->priority), flow_format,
978                                     ofm->cookie, &fm->cr);
979         fm->cookie = ofm->cookie;
980         fm->command = ntohs(ofm->command);
981         fm->idle_timeout = ntohs(ofm->idle_timeout);
982         fm->hard_timeout = ntohs(ofm->hard_timeout);
983         fm->buffer_id = ntohl(ofm->buffer_id);
984         fm->out_port = ntohs(ofm->out_port);
985         fm->flags = ntohs(ofm->flags);
986     } else if (ofputil_msg_type_code(type) == OFPUTIL_NXT_FLOW_MOD) {
987         /* Nicira extended flow_mod. */
988         const struct nx_flow_mod *nfm;
989         int error;
990
991         /* Dissect the message. */
992         nfm = ofpbuf_pull(&b, sizeof *nfm);
993         error = nx_pull_match(&b, ntohs(nfm->match_len), ntohs(nfm->priority),
994                               &fm->cr);
995         if (error) {
996             return error;
997         }
998         error = ofputil_pull_actions(&b, b.size, &fm->actions, &fm->n_actions);
999         if (error) {
1000             return error;
1001         }
1002
1003         /* Translate the message. */
1004         fm->cookie = nfm->cookie;
1005         fm->command = ntohs(nfm->command);
1006         fm->idle_timeout = ntohs(nfm->idle_timeout);
1007         fm->hard_timeout = ntohs(nfm->hard_timeout);
1008         fm->buffer_id = ntohl(nfm->buffer_id);
1009         fm->out_port = ntohs(nfm->out_port);
1010         fm->flags = ntohs(nfm->flags);
1011     } else {
1012         NOT_REACHED();
1013     }
1014
1015     return 0;
1016 }
1017
1018 /* Converts 'fm' into an OFPT_FLOW_MOD or NXT_FLOW_MOD message according to
1019  * 'flow_format' and returns the message. */
1020 struct ofpbuf *
1021 ofputil_encode_flow_mod(const struct flow_mod *fm,
1022                         enum nx_flow_format flow_format)
1023 {
1024     size_t actions_len = fm->n_actions * sizeof *fm->actions;
1025     struct ofpbuf *msg;
1026
1027     if (flow_format == NXFF_OPENFLOW10
1028         || flow_format == NXFF_TUN_ID_FROM_COOKIE) {
1029         struct ofp_flow_mod *ofm;
1030
1031         msg = ofpbuf_new(sizeof *ofm + actions_len);
1032         ofm = put_openflow(sizeof *ofm, OFPT_FLOW_MOD, msg);
1033         ofputil_cls_rule_to_match(&fm->cr, flow_format, &ofm->match,
1034                                   fm->cookie, &ofm->cookie);
1035         ofm->command = htons(fm->command);
1036         ofm->idle_timeout = htons(fm->idle_timeout);
1037         ofm->hard_timeout = htons(fm->hard_timeout);
1038         ofm->priority = htons(fm->cr.priority);
1039         ofm->buffer_id = htonl(fm->buffer_id);
1040         ofm->out_port = htons(fm->out_port);
1041         ofm->flags = htons(fm->flags);
1042     } else if (flow_format == NXFF_NXM) {
1043         struct nx_flow_mod *nfm;
1044         int match_len;
1045
1046         msg = ofpbuf_new(sizeof *nfm + NXM_TYPICAL_LEN + actions_len);
1047         put_nxmsg(sizeof *nfm, NXT_FLOW_MOD, msg);
1048         match_len = nx_put_match(msg, &fm->cr);
1049
1050         nfm = msg->data;
1051         nfm->cookie = fm->cookie;
1052         nfm->command = htons(fm->command);
1053         nfm->idle_timeout = htons(fm->idle_timeout);
1054         nfm->hard_timeout = htons(fm->hard_timeout);
1055         nfm->priority = htons(fm->cr.priority);
1056         nfm->buffer_id = htonl(fm->buffer_id);
1057         nfm->out_port = htons(fm->out_port);
1058         nfm->flags = htons(fm->flags);
1059         nfm->match_len = htons(match_len);
1060     } else {
1061         NOT_REACHED();
1062     }
1063
1064     ofpbuf_put(msg, fm->actions, actions_len);
1065     update_openflow_length(msg);
1066     return msg;
1067 }
1068
1069 static int
1070 ofputil_decode_ofpst_flow_request(struct flow_stats_request *fsr,
1071                                   const struct ofp_header *oh,
1072                                   enum nx_flow_format flow_format,
1073                                   bool aggregate)
1074 {
1075     const struct ofp_flow_stats_request *ofsr = ofputil_stats_body(oh);
1076
1077     fsr->aggregate = aggregate;
1078     ofputil_cls_rule_from_match(&ofsr->match, 0, flow_format, 0, &fsr->match);
1079     fsr->out_port = ntohs(ofsr->out_port);
1080     fsr->table_id = ofsr->table_id;
1081
1082     return 0;
1083 }
1084
1085 static int
1086 ofputil_decode_nxst_flow_request(struct flow_stats_request *fsr,
1087                                  const struct ofp_header *oh,
1088                                  bool aggregate)
1089 {
1090     const struct nx_flow_stats_request *nfsr;
1091     struct ofpbuf b;
1092     int error;
1093
1094     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1095
1096     nfsr = ofpbuf_pull(&b, sizeof *nfsr);
1097     error = nx_pull_match(&b, ntohs(nfsr->match_len), 0, &fsr->match);
1098     if (error) {
1099         return error;
1100     }
1101     if (b.size) {
1102         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1103     }
1104
1105     fsr->aggregate = aggregate;
1106     fsr->out_port = ntohs(nfsr->out_port);
1107     fsr->table_id = nfsr->table_id;
1108
1109     return 0;
1110 }
1111
1112 /* Converts an OFPST_FLOW, OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE
1113  * message 'oh', received when the current flow format was 'flow_format', into
1114  * an abstract flow_stats_request in 'fsr'.  Returns 0 if successful, otherwise
1115  * an OpenFlow error code.
1116  *
1117  * For OFPST_FLOW and OFPST_AGGREGATE messages, 'flow_format' should be the
1118  * current flow format at the time when the message was received.  Otherwise
1119  * 'flow_format' is ignored. */
1120 int
1121 ofputil_decode_flow_stats_request(struct flow_stats_request *fsr,
1122                                   const struct ofp_header *oh,
1123                                   enum nx_flow_format flow_format)
1124 {
1125     const struct ofputil_msg_type *type;
1126     struct ofpbuf b;
1127     int code;
1128
1129     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1130
1131     ofputil_decode_msg_type(oh, &type);
1132     code = ofputil_msg_type_code(type);
1133     switch (code) {
1134     case OFPUTIL_OFPST_FLOW_REQUEST:
1135         return ofputil_decode_ofpst_flow_request(fsr, oh, flow_format, false);
1136
1137     case OFPUTIL_OFPST_AGGREGATE_REQUEST:
1138         return ofputil_decode_ofpst_flow_request(fsr, oh, flow_format, true);
1139
1140     case OFPUTIL_NXST_FLOW_REQUEST:
1141         return ofputil_decode_nxst_flow_request(fsr, oh, false);
1142
1143     case OFPUTIL_NXST_AGGREGATE_REQUEST:
1144         return ofputil_decode_nxst_flow_request(fsr, oh, true);
1145
1146     default:
1147         /* Hey, the caller lied. */
1148         NOT_REACHED();
1149     }
1150 }
1151
1152 /* Converts abstract flow_stats_request 'fsr' into an OFPST_FLOW,
1153  * OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE message 'oh' according to
1154  * 'flow_format', and returns the message. */
1155 struct ofpbuf *
1156 ofputil_encode_flow_stats_request(const struct flow_stats_request *fsr,
1157                                   enum nx_flow_format flow_format)
1158 {
1159     struct ofpbuf *msg;
1160
1161     if (flow_format == NXFF_OPENFLOW10
1162         || flow_format == NXFF_TUN_ID_FROM_COOKIE) {
1163         struct ofp_flow_stats_request *ofsr;
1164         int type;
1165
1166         BUILD_ASSERT_DECL(sizeof(struct ofp_flow_stats_request)
1167                           == sizeof(struct ofp_aggregate_stats_request));
1168
1169         type = fsr->aggregate ? OFPST_AGGREGATE : OFPST_FLOW;
1170         ofsr = ofputil_make_stats_request(sizeof *ofsr, type, &msg);
1171         ofputil_cls_rule_to_match(&fsr->match, flow_format, &ofsr->match,
1172                                   0, NULL);
1173         ofsr->table_id = fsr->table_id;
1174         ofsr->out_port = htons(fsr->out_port);
1175     } else if (flow_format == NXFF_NXM) {
1176         struct nx_flow_stats_request *nfsr;
1177         int match_len;
1178         int subtype;
1179
1180         subtype = fsr->aggregate ? NXST_AGGREGATE : NXST_FLOW;
1181         ofputil_make_nxstats_request(sizeof *nfsr, subtype, &msg);
1182         match_len = nx_put_match(msg, &fsr->match);
1183
1184         nfsr = msg->data;
1185         nfsr->out_port = htons(fsr->out_port);
1186         nfsr->match_len = htons(match_len);
1187         nfsr->table_id = fsr->table_id;
1188     } else {
1189         NOT_REACHED();
1190     }
1191
1192     return msg;
1193 }
1194
1195 /* Converts an OFPT_FLOW_REMOVED or NXT_FLOW_REMOVED message 'oh', received
1196  * when the current flow format was 'flow_format', into an abstract
1197  * ofputil_flow_removed in 'fr'.  Returns 0 if successful, otherwise an
1198  * OpenFlow error code.
1199  *
1200  * For OFPT_FLOW_REMOVED messages, 'flow_format' should be the current flow
1201  * format at the time when the message was received.  Otherwise 'flow_format'
1202  * is ignored. */
1203 int
1204 ofputil_decode_flow_removed(struct ofputil_flow_removed *fr,
1205                             const struct ofp_header *oh,
1206                             enum nx_flow_format flow_format)
1207 {
1208     const struct ofputil_msg_type *type;
1209     enum ofputil_msg_code code;
1210
1211     ofputil_decode_msg_type(oh, &type);
1212     code = ofputil_msg_type_code(type);
1213     if (code == OFPUTIL_OFPT_FLOW_REMOVED) {
1214         const struct ofp_flow_removed *ofr;
1215
1216         ofr = (const struct ofp_flow_removed *) oh;
1217         ofputil_cls_rule_from_match(&ofr->match, ntohs(ofr->priority),
1218                                     flow_format, ofr->cookie, &fr->rule);
1219         fr->cookie = ofr->cookie;
1220         fr->reason = ofr->reason;
1221         fr->duration_sec = ntohl(ofr->duration_sec);
1222         fr->duration_nsec = ntohl(ofr->duration_nsec);
1223         fr->idle_timeout = ntohs(ofr->idle_timeout);
1224         fr->packet_count = ntohll(ofr->packet_count);
1225         fr->byte_count = ntohll(ofr->byte_count);
1226     } else if (code == OFPUTIL_NXT_FLOW_REMOVED) {
1227         struct nx_flow_removed *nfr;
1228         struct ofpbuf b;
1229         int error;
1230
1231         ofpbuf_use_const(&b, oh, ntohs(oh->length));
1232
1233         nfr = ofpbuf_pull(&b, sizeof *nfr);
1234         error = nx_pull_match(&b, ntohs(nfr->match_len), ntohs(nfr->priority),
1235                               &fr->rule);
1236         if (error) {
1237             return error;
1238         }
1239         if (b.size) {
1240             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1241         }
1242
1243         fr->cookie = nfr->cookie;
1244         fr->reason = nfr->reason;
1245         fr->duration_sec = ntohl(nfr->duration_sec);
1246         fr->duration_nsec = ntohl(nfr->duration_nsec);
1247         fr->idle_timeout = ntohs(nfr->idle_timeout);
1248         fr->packet_count = ntohll(nfr->packet_count);
1249         fr->byte_count = ntohll(nfr->byte_count);
1250     } else {
1251         NOT_REACHED();
1252     }
1253
1254     return 0;
1255 }
1256
1257 /* Returns a string representing the message type of 'type'.  The string is the
1258  * enumeration constant for the type, e.g. "OFPT_HELLO".  For statistics
1259  * messages, the constant is followed by "request" or "reply",
1260  * e.g. "OFPST_AGGREGATE reply". */
1261 const char *
1262 ofputil_msg_type_name(const struct ofputil_msg_type *type)
1263 {
1264     return type->name;
1265 }
1266 \f
1267 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
1268  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
1269  * an arbitrary transaction id.  Allocated bytes beyond the header, if any, are
1270  * zeroed.
1271  *
1272  * The caller is responsible for freeing '*bufferp' when it is no longer
1273  * needed.
1274  *
1275  * The OpenFlow header length is initially set to 'openflow_len'; if the
1276  * message is later extended, the length should be updated with
1277  * update_openflow_length() before sending.
1278  *
1279  * Returns the header. */
1280 void *
1281 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp)
1282 {
1283     *bufferp = ofpbuf_new(openflow_len);
1284     return put_openflow_xid(openflow_len, type, alloc_xid(), *bufferp);
1285 }
1286
1287 /* Similar to make_openflow() but creates a Nicira vendor extension message
1288  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1289 void *
1290 make_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf **bufferp)
1291 {
1292     return make_nxmsg_xid(openflow_len, subtype, alloc_xid(), bufferp);
1293 }
1294
1295 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
1296  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
1297  * transaction id 'xid'.  Allocated bytes beyond the header, if any, are
1298  * zeroed.
1299  *
1300  * The caller is responsible for freeing '*bufferp' when it is no longer
1301  * needed.
1302  *
1303  * The OpenFlow header length is initially set to 'openflow_len'; if the
1304  * message is later extended, the length should be updated with
1305  * update_openflow_length() before sending.
1306  *
1307  * Returns the header. */
1308 void *
1309 make_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
1310                   struct ofpbuf **bufferp)
1311 {
1312     *bufferp = ofpbuf_new(openflow_len);
1313     return put_openflow_xid(openflow_len, type, xid, *bufferp);
1314 }
1315
1316 /* Similar to make_openflow_xid() but creates a Nicira vendor extension message
1317  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1318 void *
1319 make_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
1320                struct ofpbuf **bufferp)
1321 {
1322     *bufferp = ofpbuf_new(openflow_len);
1323     return put_nxmsg_xid(openflow_len, subtype, xid, *bufferp);
1324 }
1325
1326 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
1327  * with the given 'type' and an arbitrary transaction id.  Allocated bytes
1328  * beyond the header, if any, are zeroed.
1329  *
1330  * The OpenFlow header length is initially set to 'openflow_len'; if the
1331  * message is later extended, the length should be updated with
1332  * update_openflow_length() before sending.
1333  *
1334  * Returns the header. */
1335 void *
1336 put_openflow(size_t openflow_len, uint8_t type, struct ofpbuf *buffer)
1337 {
1338     return put_openflow_xid(openflow_len, type, alloc_xid(), buffer);
1339 }
1340
1341 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
1342  * with the given 'type' and an transaction id 'xid'.  Allocated bytes beyond
1343  * the header, if any, are zeroed.
1344  *
1345  * The OpenFlow header length is initially set to 'openflow_len'; if the
1346  * message is later extended, the length should be updated with
1347  * update_openflow_length() before sending.
1348  *
1349  * Returns the header. */
1350 void *
1351 put_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
1352                  struct ofpbuf *buffer)
1353 {
1354     struct ofp_header *oh;
1355
1356     assert(openflow_len >= sizeof *oh);
1357     assert(openflow_len <= UINT16_MAX);
1358
1359     oh = ofpbuf_put_uninit(buffer, openflow_len);
1360     oh->version = OFP_VERSION;
1361     oh->type = type;
1362     oh->length = htons(openflow_len);
1363     oh->xid = xid;
1364     memset(oh + 1, 0, openflow_len - sizeof *oh);
1365     return oh;
1366 }
1367
1368 /* Similar to put_openflow() but append a Nicira vendor extension message with
1369  * the specific 'subtype'.  'subtype' should be in host byte order. */
1370 void *
1371 put_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf *buffer)
1372 {
1373     return put_nxmsg_xid(openflow_len, subtype, alloc_xid(), buffer);
1374 }
1375
1376 /* Similar to put_openflow_xid() but append a Nicira vendor extension message
1377  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1378 void *
1379 put_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
1380               struct ofpbuf *buffer)
1381 {
1382     struct nicira_header *nxh;
1383
1384     nxh = put_openflow_xid(openflow_len, OFPT_VENDOR, xid, buffer);
1385     nxh->vendor = htonl(NX_VENDOR_ID);
1386     nxh->subtype = htonl(subtype);
1387     return nxh;
1388 }
1389
1390 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
1391  * 'buffer->size'. */
1392 void
1393 update_openflow_length(struct ofpbuf *buffer)
1394 {
1395     struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
1396     oh->length = htons(buffer->size);
1397 }
1398
1399 /* Creates an ofp_stats_request with the given 'type' and 'body_len' bytes of
1400  * space allocated for the 'body' member.  Returns the first byte of the 'body'
1401  * member. */
1402 void *
1403 ofputil_make_stats_request(size_t body_len, uint16_t type,
1404                            struct ofpbuf **bufferp)
1405 {
1406     struct ofp_stats_request *osr;
1407     osr = make_openflow((offsetof(struct ofp_stats_request, body)
1408                         + body_len), OFPT_STATS_REQUEST, bufferp);
1409     osr->type = htons(type);
1410     osr->flags = htons(0);
1411     return osr->body;
1412 }
1413
1414 /* Creates a stats request message with Nicira as vendor and the given
1415  * 'subtype', of total length 'openflow_len'.  Returns the message. */
1416 void *
1417 ofputil_make_nxstats_request(size_t openflow_len, uint32_t subtype,
1418                              struct ofpbuf **bufferp)
1419 {
1420     struct nicira_stats_msg *nsm;
1421
1422     nsm = make_openflow(openflow_len, OFPT_STATS_REQUEST, bufferp);
1423     nsm->type = htons(OFPST_VENDOR);
1424     nsm->flags = htons(0);
1425     nsm->vendor = htonl(NX_VENDOR_ID);
1426     nsm->subtype = htonl(subtype);
1427     return nsm;
1428 }
1429
1430 /* Returns the first byte of the 'body' member of the ofp_stats_request or
1431  * ofp_stats_reply in 'oh'. */
1432 const void *
1433 ofputil_stats_body(const struct ofp_header *oh)
1434 {
1435     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1436     return ((const struct ofp_stats_request *) oh)->body;
1437 }
1438
1439 /* Returns the length of the 'body' member of the ofp_stats_request or
1440  * ofp_stats_reply in 'oh'. */
1441 size_t
1442 ofputil_stats_body_len(const struct ofp_header *oh)
1443 {
1444     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1445     return ntohs(oh->length) - sizeof(struct ofp_stats_request);
1446 }
1447
1448 /* Returns the first byte of the body of the nicira_stats_msg in 'oh'. */
1449 const void *
1450 ofputil_nxstats_body(const struct ofp_header *oh)
1451 {
1452     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1453     return ((const struct nicira_stats_msg *) oh) + 1;
1454 }
1455
1456 /* Returns the length of the body of the nicira_stats_msg in 'oh'. */
1457 size_t
1458 ofputil_nxstats_body_len(const struct ofp_header *oh)
1459 {
1460     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1461     return ntohs(oh->length) - sizeof(struct nicira_stats_msg);
1462 }
1463
1464 struct ofpbuf *
1465 make_flow_mod(uint16_t command, const struct cls_rule *rule,
1466               size_t actions_len)
1467 {
1468     struct ofp_flow_mod *ofm;
1469     size_t size = sizeof *ofm + actions_len;
1470     struct ofpbuf *out = ofpbuf_new(size);
1471     ofm = ofpbuf_put_zeros(out, sizeof *ofm);
1472     ofm->header.version = OFP_VERSION;
1473     ofm->header.type = OFPT_FLOW_MOD;
1474     ofm->header.length = htons(size);
1475     ofm->cookie = 0;
1476     ofm->priority = htons(MIN(rule->priority, UINT16_MAX));
1477     ofputil_cls_rule_to_match(rule, NXFF_OPENFLOW10, &ofm->match, 0, NULL);
1478     ofm->command = htons(command);
1479     return out;
1480 }
1481
1482 struct ofpbuf *
1483 make_add_flow(const struct cls_rule *rule, uint32_t buffer_id,
1484               uint16_t idle_timeout, size_t actions_len)
1485 {
1486     struct ofpbuf *out = make_flow_mod(OFPFC_ADD, rule, actions_len);
1487     struct ofp_flow_mod *ofm = out->data;
1488     ofm->idle_timeout = htons(idle_timeout);
1489     ofm->hard_timeout = htons(OFP_FLOW_PERMANENT);
1490     ofm->buffer_id = htonl(buffer_id);
1491     return out;
1492 }
1493
1494 struct ofpbuf *
1495 make_del_flow(const struct cls_rule *rule)
1496 {
1497     struct ofpbuf *out = make_flow_mod(OFPFC_DELETE_STRICT, rule, 0);
1498     struct ofp_flow_mod *ofm = out->data;
1499     ofm->out_port = htons(OFPP_NONE);
1500     return out;
1501 }
1502
1503 struct ofpbuf *
1504 make_add_simple_flow(const struct cls_rule *rule,
1505                      uint32_t buffer_id, uint16_t out_port,
1506                      uint16_t idle_timeout)
1507 {
1508     if (out_port != OFPP_NONE) {
1509         struct ofp_action_output *oao;
1510         struct ofpbuf *buffer;
1511
1512         buffer = make_add_flow(rule, buffer_id, idle_timeout, sizeof *oao);
1513         oao = ofpbuf_put_zeros(buffer, sizeof *oao);
1514         oao->type = htons(OFPAT_OUTPUT);
1515         oao->len = htons(sizeof *oao);
1516         oao->port = htons(out_port);
1517         return buffer;
1518     } else {
1519         return make_add_flow(rule, buffer_id, idle_timeout, 0);
1520     }
1521 }
1522
1523 struct ofpbuf *
1524 make_packet_in(uint32_t buffer_id, uint16_t in_port, uint8_t reason,
1525                const struct ofpbuf *payload, int max_send_len)
1526 {
1527     struct ofp_packet_in *opi;
1528     struct ofpbuf *buf;
1529     int send_len;
1530
1531     send_len = MIN(max_send_len, payload->size);
1532     buf = ofpbuf_new(sizeof *opi + send_len);
1533     opi = put_openflow_xid(offsetof(struct ofp_packet_in, data),
1534                            OFPT_PACKET_IN, 0, buf);
1535     opi->buffer_id = htonl(buffer_id);
1536     opi->total_len = htons(payload->size);
1537     opi->in_port = htons(in_port);
1538     opi->reason = reason;
1539     ofpbuf_put(buf, payload->data, send_len);
1540     update_openflow_length(buf);
1541
1542     return buf;
1543 }
1544
1545 struct ofpbuf *
1546 make_packet_out(const struct ofpbuf *packet, uint32_t buffer_id,
1547                 uint16_t in_port,
1548                 const struct ofp_action_header *actions, size_t n_actions)
1549 {
1550     size_t actions_len = n_actions * sizeof *actions;
1551     struct ofp_packet_out *opo;
1552     size_t size = sizeof *opo + actions_len + (packet ? packet->size : 0);
1553     struct ofpbuf *out = ofpbuf_new(size);
1554
1555     opo = ofpbuf_put_uninit(out, sizeof *opo);
1556     opo->header.version = OFP_VERSION;
1557     opo->header.type = OFPT_PACKET_OUT;
1558     opo->header.length = htons(size);
1559     opo->header.xid = htonl(0);
1560     opo->buffer_id = htonl(buffer_id);
1561     opo->in_port = htons(in_port == ODPP_LOCAL ? OFPP_LOCAL : in_port);
1562     opo->actions_len = htons(actions_len);
1563     ofpbuf_put(out, actions, actions_len);
1564     if (packet) {
1565         ofpbuf_put(out, packet->data, packet->size);
1566     }
1567     return out;
1568 }
1569
1570 struct ofpbuf *
1571 make_unbuffered_packet_out(const struct ofpbuf *packet,
1572                            uint16_t in_port, uint16_t out_port)
1573 {
1574     struct ofp_action_output action;
1575     action.type = htons(OFPAT_OUTPUT);
1576     action.len = htons(sizeof action);
1577     action.port = htons(out_port);
1578     return make_packet_out(packet, UINT32_MAX, in_port,
1579                            (struct ofp_action_header *) &action, 1);
1580 }
1581
1582 struct ofpbuf *
1583 make_buffered_packet_out(uint32_t buffer_id,
1584                          uint16_t in_port, uint16_t out_port)
1585 {
1586     if (out_port != OFPP_NONE) {
1587         struct ofp_action_output action;
1588         action.type = htons(OFPAT_OUTPUT);
1589         action.len = htons(sizeof action);
1590         action.port = htons(out_port);
1591         return make_packet_out(NULL, buffer_id, in_port,
1592                                (struct ofp_action_header *) &action, 1);
1593     } else {
1594         return make_packet_out(NULL, buffer_id, in_port, NULL, 0);
1595     }
1596 }
1597
1598 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
1599 struct ofpbuf *
1600 make_echo_request(void)
1601 {
1602     struct ofp_header *rq;
1603     struct ofpbuf *out = ofpbuf_new(sizeof *rq);
1604     rq = ofpbuf_put_uninit(out, sizeof *rq);
1605     rq->version = OFP_VERSION;
1606     rq->type = OFPT_ECHO_REQUEST;
1607     rq->length = htons(sizeof *rq);
1608     rq->xid = htonl(0);
1609     return out;
1610 }
1611
1612 /* Creates and returns an OFPT_ECHO_REPLY message matching the
1613  * OFPT_ECHO_REQUEST message in 'rq'. */
1614 struct ofpbuf *
1615 make_echo_reply(const struct ofp_header *rq)
1616 {
1617     size_t size = ntohs(rq->length);
1618     struct ofpbuf *out = ofpbuf_new(size);
1619     struct ofp_header *reply = ofpbuf_put(out, rq, size);
1620     reply->type = OFPT_ECHO_REPLY;
1621     return out;
1622 }
1623
1624 const struct ofp_flow_stats *
1625 flow_stats_first(struct flow_stats_iterator *iter,
1626                  const struct ofp_stats_reply *osr)
1627 {
1628     iter->pos = osr->body;
1629     iter->end = osr->body + (ntohs(osr->header.length)
1630                              - offsetof(struct ofp_stats_reply, body));
1631     return flow_stats_next(iter);
1632 }
1633
1634 const struct ofp_flow_stats *
1635 flow_stats_next(struct flow_stats_iterator *iter)
1636 {
1637     ptrdiff_t bytes_left = iter->end - iter->pos;
1638     const struct ofp_flow_stats *fs;
1639     size_t length;
1640
1641     if (bytes_left < sizeof *fs) {
1642         if (bytes_left != 0) {
1643             VLOG_WARN_RL(&bad_ofmsg_rl,
1644                          "%td leftover bytes in flow stats reply", bytes_left);
1645         }
1646         return NULL;
1647     }
1648
1649     fs = (const void *) iter->pos;
1650     length = ntohs(fs->length);
1651     if (length < sizeof *fs) {
1652         VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu is shorter than "
1653                      "min %zu", length, sizeof *fs);
1654         return NULL;
1655     } else if (length > bytes_left) {
1656         VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu but only %td "
1657                      "bytes left", length, bytes_left);
1658         return NULL;
1659     } else if ((length - sizeof *fs) % sizeof fs->actions[0]) {
1660         VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu has %zu bytes "
1661                      "left over in final action", length,
1662                      (length - sizeof *fs) % sizeof fs->actions[0]);
1663         return NULL;
1664     }
1665     iter->pos += length;
1666     return fs;
1667 }
1668
1669 static int
1670 check_action_exact_len(const union ofp_action *a, unsigned int len,
1671                        unsigned int required_len)
1672 {
1673     if (len != required_len) {
1674         VLOG_WARN_RL(&bad_ofmsg_rl, "action %"PRIu16" has invalid length "
1675                      "%"PRIu16" (must be %u)\n",
1676                      ntohs(a->type), ntohs(a->header.len), required_len);
1677         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1678     }
1679     return 0;
1680 }
1681
1682 static int
1683 check_nx_action_exact_len(const struct nx_action_header *a,
1684                           unsigned int len, unsigned int required_len)
1685 {
1686     if (len != required_len) {
1687         VLOG_WARN_RL(&bad_ofmsg_rl,
1688                      "Nicira action %"PRIu16" has invalid length %"PRIu16" "
1689                      "(must be %u)\n",
1690                      ntohs(a->subtype), ntohs(a->len), required_len);
1691         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1692     }
1693     return 0;
1694 }
1695
1696 /* Checks that 'port' is a valid output port for the OFPAT_OUTPUT action, given
1697  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
1698  * 'port' is valid, otherwise an ofp_mkerr() return code. */
1699 static int
1700 check_output_port(uint16_t port, int max_ports)
1701 {
1702     switch (port) {
1703     case OFPP_IN_PORT:
1704     case OFPP_TABLE:
1705     case OFPP_NORMAL:
1706     case OFPP_FLOOD:
1707     case OFPP_ALL:
1708     case OFPP_CONTROLLER:
1709     case OFPP_LOCAL:
1710         return 0;
1711
1712     default:
1713         if (port < max_ports) {
1714             return 0;
1715         }
1716         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown output port %x", port);
1717         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
1718     }
1719 }
1720
1721 /* Checks that 'action' is a valid OFPAT_ENQUEUE action, given that the switch
1722  * will never have more than 'max_ports' ports.  Returns 0 if 'port' is valid,
1723  * otherwise an ofp_mkerr() return code. */
1724 static int
1725 check_enqueue_action(const union ofp_action *a, unsigned int len,
1726                      int max_ports)
1727 {
1728     const struct ofp_action_enqueue *oae;
1729     uint16_t port;
1730     int error;
1731
1732     error = check_action_exact_len(a, len, 16);
1733     if (error) {
1734         return error;
1735     }
1736
1737     oae = (const struct ofp_action_enqueue *) a;
1738     port = ntohs(oae->port);
1739     if (port < max_ports || port == OFPP_IN_PORT) {
1740         return 0;
1741     }
1742     VLOG_WARN_RL(&bad_ofmsg_rl, "unknown enqueue port %x", port);
1743     return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
1744 }
1745
1746 static int
1747 check_nicira_action(const union ofp_action *a, unsigned int len,
1748                     const struct flow *flow)
1749 {
1750     const struct nx_action_header *nah;
1751     uint16_t subtype;
1752     int error;
1753
1754     if (len < 16) {
1755         VLOG_WARN_RL(&bad_ofmsg_rl,
1756                      "Nicira vendor action only %u bytes", len);
1757         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1758     }
1759     nah = (const struct nx_action_header *) a;
1760
1761     subtype = ntohs(nah->subtype);
1762     if (subtype > TYPE_MAXIMUM(enum nx_action_subtype)) {
1763         /* This is necessary because enum nx_action_subtype is probably an
1764          * 8-bit type, so the cast below throws away the top 8 bits. */
1765         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR_TYPE);
1766     }
1767
1768     switch ((enum nx_action_subtype) subtype) {
1769     case NXAST_RESUBMIT:
1770     case NXAST_SET_TUNNEL:
1771     case NXAST_DROP_SPOOFED_ARP:
1772     case NXAST_SET_QUEUE:
1773     case NXAST_POP_QUEUE:
1774         return check_nx_action_exact_len(nah, len, 16);
1775
1776     case NXAST_REG_MOVE:
1777         error = check_nx_action_exact_len(nah, len,
1778                                           sizeof(struct nx_action_reg_move));
1779         if (error) {
1780             return error;
1781         }
1782         return nxm_check_reg_move((const struct nx_action_reg_move *) a, flow);
1783
1784     case NXAST_REG_LOAD:
1785         error = check_nx_action_exact_len(nah, len,
1786                                           sizeof(struct nx_action_reg_load));
1787         if (error) {
1788             return error;
1789         }
1790         return nxm_check_reg_load((const struct nx_action_reg_load *) a, flow);
1791
1792     case NXAST_NOTE:
1793         return 0;
1794
1795     case NXAST_SET_TUNNEL64:
1796         return check_nx_action_exact_len(
1797             nah, len, sizeof(struct nx_action_set_tunnel64));
1798
1799     case NXAST_MULTIPATH:
1800         error = check_nx_action_exact_len(
1801             nah, len, sizeof(struct nx_action_multipath));
1802         if (error) {
1803             return error;
1804         }
1805         return multipath_check((const struct nx_action_multipath *) a);
1806
1807     case NXAST_SNAT__OBSOLETE:
1808     default:
1809         VLOG_WARN_RL(&bad_ofmsg_rl,
1810                      "unknown Nicira vendor action subtype %"PRIu16,
1811                      ntohs(nah->subtype));
1812         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR_TYPE);
1813     }
1814 }
1815
1816 static int
1817 check_action(const union ofp_action *a, unsigned int len,
1818              const struct flow *flow, int max_ports)
1819 {
1820     enum ofp_action_type type = ntohs(a->type);
1821     int error;
1822
1823     switch (type) {
1824     case OFPAT_OUTPUT:
1825         error = check_action_exact_len(a, len, 8);
1826         if (error) {
1827             return error;
1828         }
1829         return check_output_port(ntohs(a->output.port), max_ports);
1830
1831     case OFPAT_SET_VLAN_VID:
1832         error = check_action_exact_len(a, len, 8);
1833         if (error) {
1834             return error;
1835         }
1836         if (a->vlan_vid.vlan_vid & ~htons(0xfff)) {
1837             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
1838         }
1839         return 0;
1840
1841     case OFPAT_SET_VLAN_PCP:
1842         error = check_action_exact_len(a, len, 8);
1843         if (error) {
1844             return error;
1845         }
1846         if (a->vlan_vid.vlan_vid & ~7) {
1847             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
1848         }
1849         return 0;
1850
1851     case OFPAT_STRIP_VLAN:
1852     case OFPAT_SET_NW_SRC:
1853     case OFPAT_SET_NW_DST:
1854     case OFPAT_SET_NW_TOS:
1855     case OFPAT_SET_TP_SRC:
1856     case OFPAT_SET_TP_DST:
1857         return check_action_exact_len(a, len, 8);
1858
1859     case OFPAT_SET_DL_SRC:
1860     case OFPAT_SET_DL_DST:
1861         return check_action_exact_len(a, len, 16);
1862
1863     case OFPAT_VENDOR:
1864         return (a->vendor.vendor == htonl(NX_VENDOR_ID)
1865                 ? check_nicira_action(a, len, flow)
1866                 : ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR));
1867
1868     case OFPAT_ENQUEUE:
1869         return check_enqueue_action(a, len, max_ports);
1870
1871     default:
1872         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown action type %d", (int) type);
1873         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_TYPE);
1874     }
1875 }
1876
1877 int
1878 validate_actions(const union ofp_action *actions, size_t n_actions,
1879                  const struct flow *flow, int max_ports)
1880 {
1881     size_t i;
1882
1883     for (i = 0; i < n_actions; ) {
1884         const union ofp_action *a = &actions[i];
1885         unsigned int len = ntohs(a->header.len);
1886         unsigned int n_slots = len / OFP_ACTION_ALIGN;
1887         unsigned int slots_left = &actions[n_actions] - a;
1888         int error;
1889
1890         if (n_slots > slots_left) {
1891             VLOG_WARN_RL(&bad_ofmsg_rl,
1892                          "action requires %u slots but only %u remain",
1893                          n_slots, slots_left);
1894             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1895         } else if (!len) {
1896             VLOG_WARN_RL(&bad_ofmsg_rl, "action has invalid length 0");
1897             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1898         } else if (len % OFP_ACTION_ALIGN) {
1899             VLOG_WARN_RL(&bad_ofmsg_rl, "action length %u is not a multiple "
1900                          "of %d", len, OFP_ACTION_ALIGN);
1901             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1902         }
1903
1904         error = check_action(a, len, flow, max_ports);
1905         if (error) {
1906             return error;
1907         }
1908         i += n_slots;
1909     }
1910     return 0;
1911 }
1912
1913 /* Returns true if 'action' outputs to 'port' (which must be in network byte
1914  * order), false otherwise. */
1915 bool
1916 action_outputs_to_port(const union ofp_action *action, uint16_t port)
1917 {
1918     switch (ntohs(action->type)) {
1919     case OFPAT_OUTPUT:
1920         return action->output.port == port;
1921     case OFPAT_ENQUEUE:
1922         return ((const struct ofp_action_enqueue *) action)->port == port;
1923     default:
1924         return false;
1925     }
1926 }
1927
1928 /* The set of actions must either come from a trusted source or have been
1929  * previously validated with validate_actions(). */
1930 const union ofp_action *
1931 actions_first(struct actions_iterator *iter,
1932               const union ofp_action *oa, size_t n_actions)
1933 {
1934     iter->pos = oa;
1935     iter->end = oa + n_actions;
1936     return actions_next(iter);
1937 }
1938
1939 const union ofp_action *
1940 actions_next(struct actions_iterator *iter)
1941 {
1942     if (iter->pos != iter->end) {
1943         const union ofp_action *a = iter->pos;
1944         unsigned int len = ntohs(a->header.len);
1945         iter->pos += len / OFP_ACTION_ALIGN;
1946         return a;
1947     } else {
1948         return NULL;
1949     }
1950 }
1951
1952 void
1953 normalize_match(struct ofp_match *m)
1954 {
1955     enum { OFPFW_NW = (OFPFW_NW_SRC_MASK | OFPFW_NW_DST_MASK | OFPFW_NW_PROTO
1956                        | OFPFW_NW_TOS) };
1957     enum { OFPFW_TP = OFPFW_TP_SRC | OFPFW_TP_DST };
1958     uint32_t wc;
1959
1960     wc = ntohl(m->wildcards) & OVSFW_ALL;
1961     if (wc & OFPFW_DL_TYPE) {
1962         m->dl_type = 0;
1963
1964         /* Can't sensibly match on network or transport headers if the
1965          * data link type is unknown. */
1966         wc |= OFPFW_NW | OFPFW_TP;
1967         m->nw_src = m->nw_dst = m->nw_proto = m->nw_tos = 0;
1968         m->tp_src = m->tp_dst = 0;
1969     } else if (m->dl_type == htons(ETH_TYPE_IP)) {
1970         if (wc & OFPFW_NW_PROTO) {
1971             m->nw_proto = 0;
1972
1973             /* Can't sensibly match on transport headers if the network
1974              * protocol is unknown. */
1975             wc |= OFPFW_TP;
1976             m->tp_src = m->tp_dst = 0;
1977         } else if (m->nw_proto == IPPROTO_TCP ||
1978                    m->nw_proto == IPPROTO_UDP ||
1979                    m->nw_proto == IPPROTO_ICMP) {
1980             if (wc & OFPFW_TP_SRC) {
1981                 m->tp_src = 0;
1982             }
1983             if (wc & OFPFW_TP_DST) {
1984                 m->tp_dst = 0;
1985             }
1986         } else {
1987             /* Transport layer fields will always be extracted as zeros, so we
1988              * can do an exact-match on those values.  */
1989             wc &= ~OFPFW_TP;
1990             m->tp_src = m->tp_dst = 0;
1991         }
1992         if (wc & OFPFW_NW_SRC_MASK) {
1993             m->nw_src &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_SRC_SHIFT);
1994         }
1995         if (wc & OFPFW_NW_DST_MASK) {
1996             m->nw_dst &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_DST_SHIFT);
1997         }
1998         if (wc & OFPFW_NW_TOS) {
1999             m->nw_tos = 0;
2000         } else {
2001             m->nw_tos &= IP_DSCP_MASK;
2002         }
2003     } else if (m->dl_type == htons(ETH_TYPE_ARP)) {
2004         if (wc & OFPFW_NW_PROTO) {
2005             m->nw_proto = 0;
2006         }
2007         if (wc & OFPFW_NW_SRC_MASK) {
2008             m->nw_src &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_SRC_SHIFT);
2009         }
2010         if (wc & OFPFW_NW_DST_MASK) {
2011             m->nw_dst &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_DST_SHIFT);
2012         }
2013         m->tp_src = m->tp_dst = m->nw_tos = 0;
2014     } else {
2015         /* Network and transport layer fields will always be extracted as
2016          * zeros, so we can do an exact-match on those values. */
2017         wc &= ~(OFPFW_NW | OFPFW_TP);
2018         m->nw_proto = m->nw_src = m->nw_dst = m->nw_tos = 0;
2019         m->tp_src = m->tp_dst = 0;
2020     }
2021     if (wc & OFPFW_DL_SRC) {
2022         memset(m->dl_src, 0, sizeof m->dl_src);
2023     }
2024     if (wc & OFPFW_DL_DST) {
2025         memset(m->dl_dst, 0, sizeof m->dl_dst);
2026     }
2027     m->wildcards = htonl(wc);
2028 }
2029
2030 /* Returns a string that describes 'match' in a very literal way, without
2031  * interpreting its contents except in a very basic fashion.  The returned
2032  * string is intended to be fixed-length, so that it is easy to see differences
2033  * between two such strings if one is put above another.  This is useful for
2034  * describing changes made by normalize_match().
2035  *
2036  * The caller must free the returned string (with free()). */
2037 char *
2038 ofp_match_to_literal_string(const struct ofp_match *match)
2039 {
2040     return xasprintf("wildcards=%#10"PRIx32" "
2041                      " in_port=%5"PRId16" "
2042                      " dl_src="ETH_ADDR_FMT" "
2043                      " dl_dst="ETH_ADDR_FMT" "
2044                      " dl_vlan=%5"PRId16" "
2045                      " dl_vlan_pcp=%3"PRId8" "
2046                      " dl_type=%#6"PRIx16" "
2047                      " nw_tos=%#4"PRIx8" "
2048                      " nw_proto=%#4"PRIx16" "
2049                      " nw_src=%#10"PRIx32" "
2050                      " nw_dst=%#10"PRIx32" "
2051                      " tp_src=%5"PRId16" "
2052                      " tp_dst=%5"PRId16,
2053                      ntohl(match->wildcards),
2054                      ntohs(match->in_port),
2055                      ETH_ADDR_ARGS(match->dl_src),
2056                      ETH_ADDR_ARGS(match->dl_dst),
2057                      ntohs(match->dl_vlan),
2058                      match->dl_vlan_pcp,
2059                      ntohs(match->dl_type),
2060                      match->nw_tos,
2061                      match->nw_proto,
2062                      ntohl(match->nw_src),
2063                      ntohl(match->nw_dst),
2064                      ntohs(match->tp_src),
2065                      ntohs(match->tp_dst));
2066 }
2067
2068 static uint32_t
2069 vendor_code_to_id(uint8_t code)
2070 {
2071     switch (code) {
2072 #define OFPUTIL_VENDOR(NAME, VENDOR_ID) case NAME: return VENDOR_ID;
2073         OFPUTIL_VENDORS
2074 #undef OFPUTIL_VENDOR
2075     default:
2076         return UINT32_MAX;
2077     }
2078 }
2079
2080 static int
2081 vendor_id_to_code(uint32_t id)
2082 {
2083     switch (id) {
2084 #define OFPUTIL_VENDOR(NAME, VENDOR_ID) case VENDOR_ID: return NAME;
2085         OFPUTIL_VENDORS
2086 #undef OFPUTIL_VENDOR
2087     default:
2088         return -1;
2089     }
2090 }
2091
2092 /* Creates and returns an OpenFlow message of type OFPT_ERROR with the error
2093  * information taken from 'error', whose encoding must be as described in the
2094  * large comment in ofp-util.h.  If 'oh' is nonnull, then the error will use
2095  * oh->xid as its transaction ID, and it will include up to the first 64 bytes
2096  * of 'oh'.
2097  *
2098  * Returns NULL if 'error' is not an OpenFlow error code. */
2099 struct ofpbuf *
2100 ofputil_encode_error_msg(int error, const struct ofp_header *oh)
2101 {
2102     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2103
2104     struct ofpbuf *buf;
2105     const void *data;
2106     size_t len;
2107     uint8_t vendor;
2108     uint16_t type;
2109     uint16_t code;
2110     ovs_be32 xid;
2111
2112     if (!is_ofp_error(error)) {
2113         /* We format 'error' with strerror() here since it seems likely to be
2114          * a system errno value. */
2115         VLOG_WARN_RL(&rl, "invalid OpenFlow error code %d (%s)",
2116                      error, strerror(error));
2117         return NULL;
2118     }
2119
2120     if (oh) {
2121         xid = oh->xid;
2122         data = oh;
2123         len = ntohs(oh->length);
2124         if (len > 64) {
2125             len = 64;
2126         }
2127     } else {
2128         xid = 0;
2129         data = NULL;
2130         len = 0;
2131     }
2132
2133     vendor = get_ofp_err_vendor(error);
2134     type = get_ofp_err_type(error);
2135     code = get_ofp_err_code(error);
2136     if (vendor == OFPUTIL_VENDOR_OPENFLOW) {
2137         struct ofp_error_msg *oem;
2138
2139         oem = make_openflow_xid(len + sizeof *oem, OFPT_ERROR, xid, &buf);
2140         oem->type = htons(type);
2141         oem->code = htons(code);
2142     } else {
2143         struct ofp_error_msg *oem;
2144         struct nx_vendor_error *nve;
2145         uint32_t vendor_id;
2146
2147         vendor_id = vendor_code_to_id(vendor);
2148         if (vendor_id == UINT32_MAX) {
2149             VLOG_WARN_RL(&rl, "error %x contains invalid vendor code %d",
2150                          error, vendor);
2151             return NULL;
2152         }
2153
2154         oem = make_openflow_xid(len + sizeof *oem + sizeof *nve,
2155                                 OFPT_ERROR, xid, &buf);
2156         oem->type = htons(NXET_VENDOR);
2157         oem->code = htons(NXVC_VENDOR_ERROR);
2158
2159         nve = (struct nx_vendor_error *)oem->data;
2160         nve->vendor = htonl(vendor_id);
2161         nve->type = htons(type);
2162         nve->code = htons(code);
2163     }
2164
2165     if (len) {
2166         buf->size -= len;
2167         ofpbuf_put(buf, data, len);
2168     }
2169
2170     return buf;
2171 }
2172
2173 /* Decodes 'oh', which should be an OpenFlow OFPT_ERROR message, and returns an
2174  * Open vSwitch internal error code in the format described in the large
2175  * comment in ofp-util.h.
2176  *
2177  * If 'payload_ofs' is nonnull, on success '*payload_ofs' is set to the offset
2178  * to the payload starting from 'oh' and on failure it is set to 0. */
2179 int
2180 ofputil_decode_error_msg(const struct ofp_header *oh, size_t *payload_ofs)
2181 {
2182     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2183
2184     const struct ofp_error_msg *oem;
2185     uint16_t type, code;
2186     struct ofpbuf b;
2187     int vendor;
2188
2189     if (payload_ofs) {
2190         *payload_ofs = 0;
2191     }
2192     if (oh->type != OFPT_ERROR) {
2193         return EPROTO;
2194     }
2195
2196     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2197     oem = ofpbuf_try_pull(&b, sizeof *oem);
2198     if (!oem) {
2199         return EPROTO;
2200     }
2201
2202     type = ntohs(oem->type);
2203     code = ntohs(oem->code);
2204     if (type == NXET_VENDOR && code == NXVC_VENDOR_ERROR) {
2205         const struct nx_vendor_error *nve = ofpbuf_try_pull(&b, sizeof *nve);
2206         if (!nve) {
2207             return EPROTO;
2208         }
2209
2210         vendor = vendor_id_to_code(ntohl(nve->vendor));
2211         if (vendor < 0) {
2212             VLOG_WARN_RL(&rl, "error contains unknown vendor ID %#"PRIx32,
2213                          ntohl(nve->vendor));
2214             return EPROTO;
2215         }
2216         type = ntohs(nve->type);
2217         code = ntohs(nve->code);
2218     } else {
2219         vendor = OFPUTIL_VENDOR_OPENFLOW;
2220     }
2221
2222     if (type >= 1024) {
2223         VLOG_WARN_RL(&rl, "error contains type %"PRIu16" greater than "
2224                      "supported maximum value 1023", type);
2225         return EPROTO;
2226     }
2227
2228     if (payload_ofs) {
2229         *payload_ofs = (uint8_t *) b.data - (uint8_t *) oh;
2230     }
2231     return ofp_mkerr_vendor(vendor, type, code);
2232 }
2233
2234 void
2235 ofputil_format_error(struct ds *s, int error)
2236 {
2237     if (is_errno(error)) {
2238         ds_put_cstr(s, strerror(error));
2239     } else {
2240         uint16_t type = get_ofp_err_type(error);
2241         uint16_t code = get_ofp_err_code(error);
2242         const char *type_s = ofp_error_type_to_string(type);
2243         const char *code_s = ofp_error_code_to_string(type, code);
2244
2245         ds_put_format(s, "type ");
2246         if (type_s) {
2247             ds_put_cstr(s, type_s);
2248         } else {
2249             ds_put_format(s, "%"PRIu16, type);
2250         }
2251
2252         ds_put_cstr(s, ", code ");
2253         if (code_s) {
2254             ds_put_cstr(s, code_s);
2255         } else {
2256             ds_put_format(s, "%"PRIu16, code);
2257         }
2258     }
2259 }
2260
2261 char *
2262 ofputil_error_to_string(int error)
2263 {
2264     struct ds s = DS_EMPTY_INITIALIZER;
2265     ofputil_format_error(&s, error);
2266     return ds_steal_cstr(&s);
2267 }
2268
2269 /* Attempts to pull 'actions_len' bytes from the front of 'b'.  Returns 0 if
2270  * successful, otherwise an OpenFlow error.
2271  *
2272  * If successful, the first action is stored in '*actionsp' and the number of
2273  * "union ofp_action" size elements into '*n_actionsp'.  Otherwise NULL and 0
2274  * are stored, respectively.
2275  *
2276  * This function does not check that the actions are valid (the caller should
2277  * do so, with validate_actions()).  The caller is also responsible for making
2278  * sure that 'b->data' is initially aligned appropriately for "union
2279  * ofp_action". */
2280 int
2281 ofputil_pull_actions(struct ofpbuf *b, unsigned int actions_len,
2282                      union ofp_action **actionsp, size_t *n_actionsp)
2283 {
2284     if (actions_len % OFP_ACTION_ALIGN != 0) {
2285         VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
2286                      "is not a multiple of %d", actions_len, OFP_ACTION_ALIGN);
2287         goto error;
2288     }
2289
2290     *actionsp = ofpbuf_try_pull(b, actions_len);
2291     if (*actionsp == NULL) {
2292         VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
2293                      "exceeds remaining message length (%zu)",
2294                      actions_len, b->size);
2295         goto error;
2296     }
2297
2298     *n_actionsp = actions_len / OFP_ACTION_ALIGN;
2299     return 0;
2300
2301 error:
2302     *actionsp = NULL;
2303     *n_actionsp = 0;
2304     return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
2305 }