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