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