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