ofproto: Implement OpenFlow extension to allow control over async messages.
[sliver-openvswitch.git] / lib / ofp-util.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012 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 <sys/types.h>
22 #include <netinet/in.h>
23 #include <netinet/icmp6.h>
24 #include <stdlib.h>
25 #include "autopath.h"
26 #include "bundle.h"
27 #include "byte-order.h"
28 #include "classifier.h"
29 #include "dynamic-string.h"
30 #include "learn.h"
31 #include "multipath.h"
32 #include "meta-flow.h"
33 #include "nx-match.h"
34 #include "ofp-errors.h"
35 #include "ofp-util.h"
36 #include "ofpbuf.h"
37 #include "packets.h"
38 #include "random.h"
39 #include "unaligned.h"
40 #include "type-props.h"
41 #include "vlog.h"
42
43 VLOG_DEFINE_THIS_MODULE(ofp_util);
44
45 /* Rate limit for OpenFlow message parse errors.  These always indicate a bug
46  * in the peer and so there's not much point in showing a lot of them. */
47 static struct vlog_rate_limit bad_ofmsg_rl = VLOG_RATE_LIMIT_INIT(1, 5);
48
49 /* Given the wildcard bit count in the least-significant 6 of 'wcbits', returns
50  * an IP netmask with a 1 in each bit that must match and a 0 in each bit that
51  * is wildcarded.
52  *
53  * The bits in 'wcbits' are in the format used in enum ofp_flow_wildcards: 0
54  * is exact match, 1 ignores the LSB, 2 ignores the 2 least-significant bits,
55  * ..., 32 and higher wildcard the entire field.  This is the *opposite* of the
56  * usual convention where e.g. /24 indicates that 8 bits (not 24 bits) are
57  * wildcarded. */
58 ovs_be32
59 ofputil_wcbits_to_netmask(int wcbits)
60 {
61     wcbits &= 0x3f;
62     return wcbits < 32 ? htonl(~((1u << wcbits) - 1)) : 0;
63 }
64
65 /* Given the IP netmask 'netmask', returns the number of bits of the IP address
66  * that it wildcards, that is, the number of 0-bits in 'netmask'.  'netmask'
67  * must be a CIDR netmask (see ip_is_cidr()). */
68 int
69 ofputil_netmask_to_wcbits(ovs_be32 netmask)
70 {
71     return 32 - ip_count_cidr_bits(netmask);
72 }
73
74 /* A list of the FWW_* and OFPFW_ bits that have the same value, meaning, and
75  * name. */
76 #define WC_INVARIANT_LIST \
77     WC_INVARIANT_BIT(IN_PORT) \
78     WC_INVARIANT_BIT(DL_SRC) \
79     WC_INVARIANT_BIT(DL_DST) \
80     WC_INVARIANT_BIT(DL_TYPE) \
81     WC_INVARIANT_BIT(NW_PROTO)
82
83 /* Verify that all of the invariant bits (as defined on WC_INVARIANT_LIST)
84  * actually have the same names and values. */
85 #define WC_INVARIANT_BIT(NAME) BUILD_ASSERT_DECL(FWW_##NAME == OFPFW_##NAME);
86     WC_INVARIANT_LIST
87 #undef WC_INVARIANT_BIT
88
89 /* WC_INVARIANTS is the invariant bits (as defined on WC_INVARIANT_LIST) all
90  * OR'd together. */
91 static const flow_wildcards_t WC_INVARIANTS = 0
92 #define WC_INVARIANT_BIT(NAME) | FWW_##NAME
93     WC_INVARIANT_LIST
94 #undef WC_INVARIANT_BIT
95 ;
96
97 /* Converts the wildcard in 'ofpfw' into a flow_wildcards in 'wc' for use in
98  * struct cls_rule.  It is the caller's responsibility to handle the special
99  * case where the flow match's dl_vlan is set to OFP_VLAN_NONE. */
100 void
101 ofputil_wildcard_from_openflow(uint32_t ofpfw, struct flow_wildcards *wc)
102 {
103     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 8);
104
105     /* Initialize most of rule->wc. */
106     flow_wildcards_init_catchall(wc);
107     wc->wildcards = (OVS_FORCE flow_wildcards_t) ofpfw & WC_INVARIANTS;
108
109     /* Wildcard fields that aren't defined by ofp_match or tun_id. */
110     wc->wildcards |= (FWW_ARP_SHA | FWW_ARP_THA | FWW_NW_ECN | FWW_NW_TTL
111                       | FWW_ND_TARGET | FWW_IPV6_LABEL);
112
113     if (ofpfw & OFPFW_NW_TOS) {
114         /* OpenFlow 1.0 defines a TOS wildcard, but it's much later in
115          * the enum than we can use. */
116         wc->wildcards |= FWW_NW_DSCP;
117     }
118
119     wc->nw_src_mask = ofputil_wcbits_to_netmask(ofpfw >> OFPFW_NW_SRC_SHIFT);
120     wc->nw_dst_mask = ofputil_wcbits_to_netmask(ofpfw >> OFPFW_NW_DST_SHIFT);
121
122     if (!(ofpfw & OFPFW_TP_SRC)) {
123         wc->tp_src_mask = htons(UINT16_MAX);
124     }
125     if (!(ofpfw & OFPFW_TP_DST)) {
126         wc->tp_dst_mask = htons(UINT16_MAX);
127     }
128
129     if (ofpfw & OFPFW_DL_DST) {
130         /* OpenFlow 1.0 OFPFW_DL_DST covers the whole Ethernet destination, but
131          * Open vSwitch breaks the Ethernet destination into bits as FWW_DL_DST
132          * and FWW_ETH_MCAST. */
133         wc->wildcards |= FWW_ETH_MCAST;
134     }
135
136     /* VLAN TCI mask. */
137     if (!(ofpfw & OFPFW_DL_VLAN_PCP)) {
138         wc->vlan_tci_mask |= htons(VLAN_PCP_MASK | VLAN_CFI);
139     }
140     if (!(ofpfw & OFPFW_DL_VLAN)) {
141         wc->vlan_tci_mask |= htons(VLAN_VID_MASK | VLAN_CFI);
142     }
143 }
144
145 /* Converts the ofp_match in 'match' into a cls_rule in 'rule', with the given
146  * 'priority'. */
147 void
148 ofputil_cls_rule_from_match(const struct ofp_match *match,
149                             unsigned int priority, struct cls_rule *rule)
150 {
151     uint32_t ofpfw = ntohl(match->wildcards) & OFPFW_ALL;
152
153     /* Initialize rule->priority, rule->wc. */
154     rule->priority = !ofpfw ? UINT16_MAX : priority;
155     ofputil_wildcard_from_openflow(ofpfw, &rule->wc);
156
157     /* Initialize most of rule->flow. */
158     rule->flow.nw_src = match->nw_src;
159     rule->flow.nw_dst = match->nw_dst;
160     rule->flow.in_port = ntohs(match->in_port);
161     rule->flow.dl_type = ofputil_dl_type_from_openflow(match->dl_type);
162     rule->flow.tp_src = match->tp_src;
163     rule->flow.tp_dst = match->tp_dst;
164     memcpy(rule->flow.dl_src, match->dl_src, ETH_ADDR_LEN);
165     memcpy(rule->flow.dl_dst, match->dl_dst, ETH_ADDR_LEN);
166     rule->flow.nw_tos = match->nw_tos & IP_DSCP_MASK;
167     rule->flow.nw_proto = match->nw_proto;
168
169     /* Translate VLANs. */
170     if (!(ofpfw & OFPFW_DL_VLAN) && match->dl_vlan == htons(OFP_VLAN_NONE)) {
171         /* Match only packets without 802.1Q header.
172          *
173          * When OFPFW_DL_VLAN_PCP is wildcarded, this is obviously correct.
174          *
175          * If OFPFW_DL_VLAN_PCP is matched, the flow match is contradictory,
176          * because we can't have a specific PCP without an 802.1Q header.
177          * However, older versions of OVS treated this as matching packets
178          * withut an 802.1Q header, so we do here too. */
179         rule->flow.vlan_tci = htons(0);
180         rule->wc.vlan_tci_mask = htons(0xffff);
181     } else {
182         ovs_be16 vid, pcp, tci;
183
184         vid = match->dl_vlan & htons(VLAN_VID_MASK);
185         pcp = htons((match->dl_vlan_pcp << VLAN_PCP_SHIFT) & VLAN_PCP_MASK);
186         tci = vid | pcp | htons(VLAN_CFI);
187         rule->flow.vlan_tci = tci & rule->wc.vlan_tci_mask;
188     }
189
190     /* Clean up. */
191     cls_rule_zero_wildcarded_fields(rule);
192 }
193
194 /* Convert 'rule' into the OpenFlow match structure 'match'. */
195 void
196 ofputil_cls_rule_to_match(const struct cls_rule *rule, struct ofp_match *match)
197 {
198     const struct flow_wildcards *wc = &rule->wc;
199     uint32_t ofpfw;
200
201     /* Figure out most OpenFlow wildcards. */
202     ofpfw = (OVS_FORCE uint32_t) (wc->wildcards & WC_INVARIANTS);
203     ofpfw |= ofputil_netmask_to_wcbits(wc->nw_src_mask) << OFPFW_NW_SRC_SHIFT;
204     ofpfw |= ofputil_netmask_to_wcbits(wc->nw_dst_mask) << OFPFW_NW_DST_SHIFT;
205     if (wc->wildcards & FWW_NW_DSCP) {
206         ofpfw |= OFPFW_NW_TOS;
207     }
208     if (!wc->tp_src_mask) {
209         ofpfw |= OFPFW_TP_SRC;
210     }
211     if (!wc->tp_dst_mask) {
212         ofpfw |= OFPFW_TP_DST;
213     }
214
215     /* Translate VLANs. */
216     match->dl_vlan = htons(0);
217     match->dl_vlan_pcp = 0;
218     if (rule->wc.vlan_tci_mask == htons(0)) {
219         ofpfw |= OFPFW_DL_VLAN | OFPFW_DL_VLAN_PCP;
220     } else if (rule->wc.vlan_tci_mask & htons(VLAN_CFI)
221                && !(rule->flow.vlan_tci & htons(VLAN_CFI))) {
222         match->dl_vlan = htons(OFP_VLAN_NONE);
223     } else {
224         if (!(rule->wc.vlan_tci_mask & htons(VLAN_VID_MASK))) {
225             ofpfw |= OFPFW_DL_VLAN;
226         } else {
227             match->dl_vlan = htons(vlan_tci_to_vid(rule->flow.vlan_tci));
228         }
229
230         if (!(rule->wc.vlan_tci_mask & htons(VLAN_PCP_MASK))) {
231             ofpfw |= OFPFW_DL_VLAN_PCP;
232         } else {
233             match->dl_vlan_pcp = vlan_tci_to_pcp(rule->flow.vlan_tci);
234         }
235     }
236
237     /* Compose most of the match structure. */
238     match->wildcards = htonl(ofpfw);
239     match->in_port = htons(rule->flow.in_port);
240     memcpy(match->dl_src, rule->flow.dl_src, ETH_ADDR_LEN);
241     memcpy(match->dl_dst, rule->flow.dl_dst, ETH_ADDR_LEN);
242     match->dl_type = ofputil_dl_type_to_openflow(rule->flow.dl_type);
243     match->nw_src = rule->flow.nw_src;
244     match->nw_dst = rule->flow.nw_dst;
245     match->nw_tos = rule->flow.nw_tos & IP_DSCP_MASK;
246     match->nw_proto = rule->flow.nw_proto;
247     match->tp_src = rule->flow.tp_src;
248     match->tp_dst = rule->flow.tp_dst;
249     memset(match->pad1, '\0', sizeof match->pad1);
250     memset(match->pad2, '\0', sizeof match->pad2);
251 }
252
253 /* Given a 'dl_type' value in the format used in struct flow, returns the
254  * corresponding 'dl_type' value for use in an OpenFlow ofp_match structure. */
255 ovs_be16
256 ofputil_dl_type_to_openflow(ovs_be16 flow_dl_type)
257 {
258     return (flow_dl_type == htons(FLOW_DL_TYPE_NONE)
259             ? htons(OFP_DL_TYPE_NOT_ETH_TYPE)
260             : flow_dl_type);
261 }
262
263 /* Given a 'dl_type' value in the format used in an OpenFlow ofp_match
264  * structure, returns the corresponding 'dl_type' value for use in struct
265  * flow. */
266 ovs_be16
267 ofputil_dl_type_from_openflow(ovs_be16 ofp_dl_type)
268 {
269     return (ofp_dl_type == htons(OFP_DL_TYPE_NOT_ETH_TYPE)
270             ? htons(FLOW_DL_TYPE_NONE)
271             : ofp_dl_type);
272 }
273
274 /* Returns a transaction ID to use for an outgoing OpenFlow message. */
275 static ovs_be32
276 alloc_xid(void)
277 {
278     static uint32_t next_xid = 1;
279     return htonl(next_xid++);
280 }
281 \f
282 /* Basic parsing of OpenFlow messages. */
283
284 struct ofputil_msg_type {
285     enum ofputil_msg_code code; /* OFPUTIL_*. */
286     uint8_t ofp_version;        /* An OpenFlow version or 0 for "any". */
287     uint32_t value;             /* OFPT_*, OFPST_*, NXT_*, or NXST_*. */
288     const char *name;           /* e.g. "OFPT_FLOW_REMOVED". */
289     unsigned int min_size;      /* Minimum total message size in bytes. */
290     /* 0 if 'min_size' is the exact size that the message must be.  Otherwise,
291      * the message may exceed 'min_size' by an even multiple of this value. */
292     unsigned int extra_multiple;
293 };
294
295 /* Represents a malformed OpenFlow message. */
296 static const struct ofputil_msg_type ofputil_invalid_type = {
297     OFPUTIL_MSG_INVALID, 0, 0, "OFPUTIL_MSG_INVALID", 0, 0
298 };
299
300 struct ofputil_msg_category {
301     const char *name;           /* e.g. "OpenFlow message" */
302     const struct ofputil_msg_type *types;
303     size_t n_types;
304     enum ofperr missing_error;  /* Error value for missing type. */
305 };
306
307 static enum ofperr
308 ofputil_check_length(const struct ofputil_msg_type *type, unsigned int size)
309 {
310     switch (type->extra_multiple) {
311     case 0:
312         if (size != type->min_size) {
313             VLOG_WARN_RL(&bad_ofmsg_rl, "received %s with incorrect "
314                          "length %u (expected length %u)",
315                          type->name, size, type->min_size);
316             return OFPERR_OFPBRC_BAD_LEN;
317         }
318         return 0;
319
320     case 1:
321         if (size < type->min_size) {
322             VLOG_WARN_RL(&bad_ofmsg_rl, "received %s with incorrect "
323                          "length %u (expected length at least %u bytes)",
324                          type->name, size, type->min_size);
325             return OFPERR_OFPBRC_BAD_LEN;
326         }
327         return 0;
328
329     default:
330         if (size < type->min_size
331             || (size - type->min_size) % type->extra_multiple) {
332             VLOG_WARN_RL(&bad_ofmsg_rl, "received %s with incorrect "
333                          "length %u (must be exactly %u bytes or longer "
334                          "by an integer multiple of %u bytes)",
335                          type->name, size,
336                          type->min_size, type->extra_multiple);
337             return OFPERR_OFPBRC_BAD_LEN;
338         }
339         return 0;
340     }
341 }
342
343 static enum ofperr
344 ofputil_lookup_openflow_message(const struct ofputil_msg_category *cat,
345                                 uint8_t version, uint32_t value,
346                                 const struct ofputil_msg_type **typep)
347 {
348     const struct ofputil_msg_type *type;
349
350     for (type = cat->types; type < &cat->types[cat->n_types]; type++) {
351         if (type->value == value
352             && (!type->ofp_version || version == type->ofp_version)) {
353             *typep = type;
354             return 0;
355         }
356     }
357
358     VLOG_WARN_RL(&bad_ofmsg_rl, "received %s of unknown type %"PRIu32,
359                  cat->name, value);
360     return cat->missing_error;
361 }
362
363 static enum ofperr
364 ofputil_decode_vendor(const struct ofp_header *oh, size_t length,
365                       const struct ofputil_msg_type **typep)
366 {
367     static const struct ofputil_msg_type nxt_messages[] = {
368         { OFPUTIL_NXT_ROLE_REQUEST, OFP10_VERSION,
369           NXT_ROLE_REQUEST, "NXT_ROLE_REQUEST",
370           sizeof(struct nx_role_request), 0 },
371
372         { OFPUTIL_NXT_ROLE_REPLY, OFP10_VERSION,
373           NXT_ROLE_REPLY, "NXT_ROLE_REPLY",
374           sizeof(struct nx_role_request), 0 },
375
376         { OFPUTIL_NXT_SET_FLOW_FORMAT, OFP10_VERSION,
377           NXT_SET_FLOW_FORMAT, "NXT_SET_FLOW_FORMAT",
378           sizeof(struct nx_set_flow_format), 0 },
379
380         { OFPUTIL_NXT_SET_PACKET_IN_FORMAT, OFP10_VERSION,
381           NXT_SET_PACKET_IN_FORMAT, "NXT_SET_PACKET_IN_FORMAT",
382           sizeof(struct nx_set_packet_in_format), 0 },
383
384         { OFPUTIL_NXT_PACKET_IN, OFP10_VERSION,
385           NXT_PACKET_IN, "NXT_PACKET_IN",
386           sizeof(struct nx_packet_in), 1 },
387
388         { OFPUTIL_NXT_FLOW_MOD, OFP10_VERSION,
389           NXT_FLOW_MOD, "NXT_FLOW_MOD",
390           sizeof(struct nx_flow_mod), 8 },
391
392         { OFPUTIL_NXT_FLOW_REMOVED, OFP10_VERSION,
393           NXT_FLOW_REMOVED, "NXT_FLOW_REMOVED",
394           sizeof(struct nx_flow_removed), 8 },
395
396         { OFPUTIL_NXT_FLOW_MOD_TABLE_ID, OFP10_VERSION,
397           NXT_FLOW_MOD_TABLE_ID, "NXT_FLOW_MOD_TABLE_ID",
398           sizeof(struct nx_flow_mod_table_id), 0 },
399
400         { OFPUTIL_NXT_FLOW_AGE, OFP10_VERSION,
401           NXT_FLOW_AGE, "NXT_FLOW_AGE",
402           sizeof(struct nicira_header), 0 },
403
404         { OFPUTIL_NXT_SET_ASYNC_CONFIG, OFP10_VERSION,
405           NXT_SET_ASYNC_CONFIG, "NXT_SET_ASYNC_CONFIG",
406           sizeof(struct nx_async_config), 0 },
407     };
408
409     static const struct ofputil_msg_category nxt_category = {
410         "Nicira extension message",
411         nxt_messages, ARRAY_SIZE(nxt_messages),
412         OFPERR_OFPBRC_BAD_SUBTYPE
413     };
414
415     const struct ofp_vendor_header *ovh;
416     const struct nicira_header *nh;
417
418     if (length < sizeof(struct ofp_vendor_header)) {
419         if (length == ntohs(oh->length)) {
420             VLOG_WARN_RL(&bad_ofmsg_rl, "truncated vendor message");
421         }
422         return OFPERR_OFPBRC_BAD_LEN;
423     }
424
425     ovh = (const struct ofp_vendor_header *) oh;
426     if (ovh->vendor != htonl(NX_VENDOR_ID)) {
427         VLOG_WARN_RL(&bad_ofmsg_rl, "received vendor message for unknown "
428                      "vendor %"PRIx32, ntohl(ovh->vendor));
429         return OFPERR_OFPBRC_BAD_VENDOR;
430     }
431
432     if (length < sizeof(struct nicira_header)) {
433         if (length == ntohs(oh->length)) {
434             VLOG_WARN_RL(&bad_ofmsg_rl, "received Nicira vendor message of "
435                          "length %u (expected at least %zu)",
436                          ntohs(ovh->header.length),
437                          sizeof(struct nicira_header));
438         }
439         return OFPERR_OFPBRC_BAD_LEN;
440     }
441
442     nh = (const struct nicira_header *) oh;
443     return ofputil_lookup_openflow_message(&nxt_category, oh->version,
444                                            ntohl(nh->subtype), typep);
445 }
446
447 static enum ofperr
448 check_nxstats_msg(const struct ofp_header *oh, size_t length)
449 {
450     const struct ofp_stats_msg *osm = (const struct ofp_stats_msg *) oh;
451     ovs_be32 vendor;
452
453     if (length < sizeof(struct ofp_vendor_stats_msg)) {
454         if (length == ntohs(oh->length)) {
455             VLOG_WARN_RL(&bad_ofmsg_rl, "truncated vendor stats message");
456         }
457         return OFPERR_OFPBRC_BAD_LEN;
458     }
459
460     memcpy(&vendor, osm + 1, sizeof vendor);
461     if (vendor != htonl(NX_VENDOR_ID)) {
462         VLOG_WARN_RL(&bad_ofmsg_rl, "received vendor stats message for "
463                      "unknown vendor %"PRIx32, ntohl(vendor));
464         return OFPERR_OFPBRC_BAD_VENDOR;
465     }
466
467     if (length < sizeof(struct nicira_stats_msg)) {
468         if (length == ntohs(osm->header.length)) {
469             VLOG_WARN_RL(&bad_ofmsg_rl, "truncated Nicira stats message");
470         }
471         return OFPERR_OFPBRC_BAD_LEN;
472     }
473
474     return 0;
475 }
476
477 static enum ofperr
478 ofputil_decode_nxst_request(const struct ofp_header *oh, size_t length,
479                             const struct ofputil_msg_type **typep)
480 {
481     static const struct ofputil_msg_type nxst_requests[] = {
482         { OFPUTIL_NXST_FLOW_REQUEST, OFP10_VERSION,
483           NXST_FLOW, "NXST_FLOW request",
484           sizeof(struct nx_flow_stats_request), 8 },
485
486         { OFPUTIL_NXST_AGGREGATE_REQUEST, OFP10_VERSION,
487           NXST_AGGREGATE, "NXST_AGGREGATE request",
488           sizeof(struct nx_aggregate_stats_request), 8 },
489     };
490
491     static const struct ofputil_msg_category nxst_request_category = {
492         "Nicira extension statistics request",
493         nxst_requests, ARRAY_SIZE(nxst_requests),
494         OFPERR_OFPBRC_BAD_SUBTYPE
495     };
496
497     const struct nicira_stats_msg *nsm;
498     enum ofperr error;
499
500     error = check_nxstats_msg(oh, length);
501     if (error) {
502         return error;
503     }
504
505     nsm = (struct nicira_stats_msg *) oh;
506     return ofputil_lookup_openflow_message(&nxst_request_category, oh->version,
507                                            ntohl(nsm->subtype), typep);
508 }
509
510 static enum ofperr
511 ofputil_decode_nxst_reply(const struct ofp_header *oh, size_t length,
512                           const struct ofputil_msg_type **typep)
513 {
514     static const struct ofputil_msg_type nxst_replies[] = {
515         { OFPUTIL_NXST_FLOW_REPLY, OFP10_VERSION,
516           NXST_FLOW, "NXST_FLOW reply",
517           sizeof(struct nicira_stats_msg), 8 },
518
519         { OFPUTIL_NXST_AGGREGATE_REPLY, OFP10_VERSION,
520           NXST_AGGREGATE, "NXST_AGGREGATE reply",
521           sizeof(struct nx_aggregate_stats_reply), 0 },
522     };
523
524     static const struct ofputil_msg_category nxst_reply_category = {
525         "Nicira extension statistics reply",
526         nxst_replies, ARRAY_SIZE(nxst_replies),
527         OFPERR_OFPBRC_BAD_SUBTYPE
528     };
529
530     const struct nicira_stats_msg *nsm;
531     enum ofperr error;
532
533     error = check_nxstats_msg(oh, length);
534     if (error) {
535         return error;
536     }
537
538     nsm = (struct nicira_stats_msg *) oh;
539     return ofputil_lookup_openflow_message(&nxst_reply_category, oh->version,
540                                            ntohl(nsm->subtype), typep);
541 }
542
543 static enum ofperr
544 check_stats_msg(const struct ofp_header *oh, size_t length)
545 {
546     if (length < sizeof(struct ofp_stats_msg)) {
547         if (length == ntohs(oh->length)) {
548             VLOG_WARN_RL(&bad_ofmsg_rl, "truncated stats message");
549         }
550         return OFPERR_OFPBRC_BAD_LEN;
551     }
552
553     return 0;
554 }
555
556 static enum ofperr
557 ofputil_decode_ofpst_request(const struct ofp_header *oh, size_t length,
558                              const struct ofputil_msg_type **typep)
559 {
560     static const struct ofputil_msg_type ofpst_requests[] = {
561         { OFPUTIL_OFPST_DESC_REQUEST, OFP10_VERSION,
562           OFPST_DESC, "OFPST_DESC request",
563           sizeof(struct ofp_stats_msg), 0 },
564
565         { OFPUTIL_OFPST_FLOW_REQUEST, OFP10_VERSION,
566           OFPST_FLOW, "OFPST_FLOW request",
567           sizeof(struct ofp_flow_stats_request), 0 },
568
569         { OFPUTIL_OFPST_AGGREGATE_REQUEST, OFP10_VERSION,
570           OFPST_AGGREGATE, "OFPST_AGGREGATE request",
571           sizeof(struct ofp_flow_stats_request), 0 },
572
573         { OFPUTIL_OFPST_TABLE_REQUEST, OFP10_VERSION,
574           OFPST_TABLE, "OFPST_TABLE request",
575           sizeof(struct ofp_stats_msg), 0 },
576
577         { OFPUTIL_OFPST_PORT_REQUEST, OFP10_VERSION,
578           OFPST_PORT, "OFPST_PORT request",
579           sizeof(struct ofp_port_stats_request), 0 },
580
581         { OFPUTIL_OFPST_QUEUE_REQUEST, OFP10_VERSION,
582           OFPST_QUEUE, "OFPST_QUEUE request",
583           sizeof(struct ofp_queue_stats_request), 0 },
584
585         { 0, 0,
586           OFPST_VENDOR, "OFPST_VENDOR request",
587           sizeof(struct ofp_vendor_stats_msg), 1 },
588     };
589
590     static const struct ofputil_msg_category ofpst_request_category = {
591         "OpenFlow statistics",
592         ofpst_requests, ARRAY_SIZE(ofpst_requests),
593         OFPERR_OFPBRC_BAD_STAT
594     };
595
596     const struct ofp_stats_msg *request = (const struct ofp_stats_msg *) oh;
597     enum ofperr error;
598
599     error = check_stats_msg(oh, length);
600     if (error) {
601         return error;
602     }
603
604     error = ofputil_lookup_openflow_message(&ofpst_request_category,
605                                             oh->version, ntohs(request->type),
606                                             typep);
607     if (!error && request->type == htons(OFPST_VENDOR)) {
608         error = ofputil_decode_nxst_request(oh, length, typep);
609     }
610     return error;
611 }
612
613 static enum ofperr
614 ofputil_decode_ofpst_reply(const struct ofp_header *oh, size_t length,
615                            const struct ofputil_msg_type **typep)
616 {
617     static const struct ofputil_msg_type ofpst_replies[] = {
618         { OFPUTIL_OFPST_DESC_REPLY, OFP10_VERSION,
619           OFPST_DESC, "OFPST_DESC reply",
620           sizeof(struct ofp_desc_stats), 0 },
621
622         { OFPUTIL_OFPST_FLOW_REPLY, OFP10_VERSION,
623           OFPST_FLOW, "OFPST_FLOW reply",
624           sizeof(struct ofp_stats_msg), 1 },
625
626         { OFPUTIL_OFPST_AGGREGATE_REPLY, OFP10_VERSION,
627           OFPST_AGGREGATE, "OFPST_AGGREGATE reply",
628           sizeof(struct ofp_aggregate_stats_reply), 0 },
629
630         { OFPUTIL_OFPST_TABLE_REPLY, OFP10_VERSION,
631           OFPST_TABLE, "OFPST_TABLE reply",
632           sizeof(struct ofp_stats_msg), sizeof(struct ofp_table_stats) },
633
634         { OFPUTIL_OFPST_PORT_REPLY, OFP10_VERSION,
635           OFPST_PORT, "OFPST_PORT reply",
636           sizeof(struct ofp_stats_msg), sizeof(struct ofp_port_stats) },
637
638         { OFPUTIL_OFPST_QUEUE_REPLY, OFP10_VERSION,
639           OFPST_QUEUE, "OFPST_QUEUE reply",
640           sizeof(struct ofp_stats_msg), sizeof(struct ofp_queue_stats) },
641
642         { 0, 0,
643           OFPST_VENDOR, "OFPST_VENDOR reply",
644           sizeof(struct ofp_vendor_stats_msg), 1 },
645     };
646
647     static const struct ofputil_msg_category ofpst_reply_category = {
648         "OpenFlow statistics",
649         ofpst_replies, ARRAY_SIZE(ofpst_replies),
650         OFPERR_OFPBRC_BAD_STAT
651     };
652
653     const struct ofp_stats_msg *reply = (const struct ofp_stats_msg *) oh;
654     enum ofperr error;
655
656     error = check_stats_msg(oh, length);
657     if (error) {
658         return error;
659     }
660
661     error = ofputil_lookup_openflow_message(&ofpst_reply_category, oh->version,
662                                            ntohs(reply->type), typep);
663     if (!error && reply->type == htons(OFPST_VENDOR)) {
664         error = ofputil_decode_nxst_reply(oh, length, typep);
665     }
666     return error;
667 }
668
669 static enum ofperr
670 ofputil_decode_msg_type__(const struct ofp_header *oh, size_t length,
671                           const struct ofputil_msg_type **typep)
672 {
673     static const struct ofputil_msg_type ofpt_messages[] = {
674         { OFPUTIL_OFPT_HELLO, OFP10_VERSION,
675           OFPT_HELLO, "OFPT_HELLO",
676           sizeof(struct ofp_hello), 1 },
677
678         { OFPUTIL_OFPT_ERROR, 0,
679           OFPT_ERROR, "OFPT_ERROR",
680           sizeof(struct ofp_error_msg), 1 },
681
682         { OFPUTIL_OFPT_ECHO_REQUEST, OFP10_VERSION,
683           OFPT_ECHO_REQUEST, "OFPT_ECHO_REQUEST",
684           sizeof(struct ofp_header), 1 },
685
686         { OFPUTIL_OFPT_ECHO_REPLY, OFP10_VERSION,
687           OFPT_ECHO_REPLY, "OFPT_ECHO_REPLY",
688           sizeof(struct ofp_header), 1 },
689
690         { OFPUTIL_OFPT_FEATURES_REQUEST, OFP10_VERSION,
691           OFPT_FEATURES_REQUEST, "OFPT_FEATURES_REQUEST",
692           sizeof(struct ofp_header), 0 },
693
694         { OFPUTIL_OFPT_FEATURES_REPLY, OFP10_VERSION,
695           OFPT_FEATURES_REPLY, "OFPT_FEATURES_REPLY",
696           sizeof(struct ofp_switch_features), sizeof(struct ofp_phy_port) },
697
698         { OFPUTIL_OFPT_GET_CONFIG_REQUEST, OFP10_VERSION,
699           OFPT_GET_CONFIG_REQUEST, "OFPT_GET_CONFIG_REQUEST",
700           sizeof(struct ofp_header), 0 },
701
702         { OFPUTIL_OFPT_GET_CONFIG_REPLY, OFP10_VERSION,
703           OFPT_GET_CONFIG_REPLY, "OFPT_GET_CONFIG_REPLY",
704           sizeof(struct ofp_switch_config), 0 },
705
706         { OFPUTIL_OFPT_SET_CONFIG, OFP10_VERSION,
707           OFPT_SET_CONFIG, "OFPT_SET_CONFIG",
708           sizeof(struct ofp_switch_config), 0 },
709
710         { OFPUTIL_OFPT_PACKET_IN, OFP10_VERSION,
711           OFPT_PACKET_IN, "OFPT_PACKET_IN",
712           offsetof(struct ofp_packet_in, data), 1 },
713
714         { OFPUTIL_OFPT_FLOW_REMOVED, OFP10_VERSION,
715           OFPT_FLOW_REMOVED, "OFPT_FLOW_REMOVED",
716           sizeof(struct ofp_flow_removed), 0 },
717
718         { OFPUTIL_OFPT_PORT_STATUS, OFP10_VERSION,
719           OFPT_PORT_STATUS, "OFPT_PORT_STATUS",
720           sizeof(struct ofp_port_status), 0 },
721
722         { OFPUTIL_OFPT_PACKET_OUT, OFP10_VERSION,
723           OFPT_PACKET_OUT, "OFPT_PACKET_OUT",
724           sizeof(struct ofp_packet_out), 1 },
725
726         { OFPUTIL_OFPT_FLOW_MOD, OFP10_VERSION,
727           OFPT_FLOW_MOD, "OFPT_FLOW_MOD",
728           sizeof(struct ofp_flow_mod), 1 },
729
730         { OFPUTIL_OFPT_PORT_MOD, OFP10_VERSION,
731           OFPT_PORT_MOD, "OFPT_PORT_MOD",
732           sizeof(struct ofp_port_mod), 0 },
733
734         { 0, OFP10_VERSION,
735           OFPT_STATS_REQUEST, "OFPT_STATS_REQUEST",
736           sizeof(struct ofp_stats_msg), 1 },
737
738         { 0, OFP10_VERSION,
739           OFPT_STATS_REPLY, "OFPT_STATS_REPLY",
740           sizeof(struct ofp_stats_msg), 1 },
741
742         { OFPUTIL_OFPT_BARRIER_REQUEST, OFP10_VERSION,
743           OFPT_BARRIER_REQUEST, "OFPT_BARRIER_REQUEST",
744           sizeof(struct ofp_header), 0 },
745
746         { OFPUTIL_OFPT_BARRIER_REPLY, OFP10_VERSION,
747           OFPT_BARRIER_REPLY, "OFPT_BARRIER_REPLY",
748           sizeof(struct ofp_header), 0 },
749
750         { 0, 0,
751           OFPT_VENDOR, "OFPT_VENDOR",
752           sizeof(struct ofp_vendor_header), 1 },
753     };
754
755     static const struct ofputil_msg_category ofpt_category = {
756         "OpenFlow message",
757         ofpt_messages, ARRAY_SIZE(ofpt_messages),
758         OFPERR_OFPBRC_BAD_TYPE
759     };
760
761     enum ofperr error;
762
763     error = ofputil_lookup_openflow_message(&ofpt_category, oh->version,
764                                             oh->type, typep);
765     if (!error) {
766         switch (oh->type) {
767         case OFPT_VENDOR:
768             error = ofputil_decode_vendor(oh, length, typep);
769             break;
770
771         case OFPT_STATS_REQUEST:
772             error = ofputil_decode_ofpst_request(oh, length, typep);
773             break;
774
775         case OFPT_STATS_REPLY:
776             error = ofputil_decode_ofpst_reply(oh, length, typep);
777
778         default:
779             break;
780         }
781     }
782     return error;
783 }
784
785 /* Decodes the message type represented by 'oh'.  Returns 0 if successful or an
786  * OpenFlow error code on failure.  Either way, stores in '*typep' a type
787  * structure that can be inspected with the ofputil_msg_type_*() functions.
788  *
789  * oh->length must indicate the correct length of the message (and must be at
790  * least sizeof(struct ofp_header)).
791  *
792  * Success indicates that 'oh' is at least as long as the minimum-length
793  * message of its type. */
794 enum ofperr
795 ofputil_decode_msg_type(const struct ofp_header *oh,
796                         const struct ofputil_msg_type **typep)
797 {
798     size_t length = ntohs(oh->length);
799     enum ofperr error;
800
801     error = ofputil_decode_msg_type__(oh, length, typep);
802     if (!error) {
803         error = ofputil_check_length(*typep, length);
804     }
805     if (error) {
806         *typep = &ofputil_invalid_type;
807     }
808     return error;
809 }
810
811 /* Decodes the message type represented by 'oh', of which only the first
812  * 'length' bytes are available.  Returns 0 if successful or an OpenFlow error
813  * code on failure.  Either way, stores in '*typep' a type structure that can
814  * be inspected with the ofputil_msg_type_*() functions.  */
815 enum ofperr
816 ofputil_decode_msg_type_partial(const struct ofp_header *oh, size_t length,
817                                 const struct ofputil_msg_type **typep)
818 {
819     enum ofperr error;
820
821     error = (length >= sizeof *oh
822              ? ofputil_decode_msg_type__(oh, length, typep)
823              : OFPERR_OFPBRC_BAD_LEN);
824     if (error) {
825         *typep = &ofputil_invalid_type;
826     }
827     return error;
828 }
829
830 /* Returns an OFPUTIL_* message type code for 'type'. */
831 enum ofputil_msg_code
832 ofputil_msg_type_code(const struct ofputil_msg_type *type)
833 {
834     return type->code;
835 }
836 \f
837 /* Flow formats. */
838
839 bool
840 ofputil_flow_format_is_valid(enum nx_flow_format flow_format)
841 {
842     switch (flow_format) {
843     case NXFF_OPENFLOW10:
844     case NXFF_NXM:
845         return true;
846     }
847
848     return false;
849 }
850
851 const char *
852 ofputil_flow_format_to_string(enum nx_flow_format flow_format)
853 {
854     switch (flow_format) {
855     case NXFF_OPENFLOW10:
856         return "openflow10";
857     case NXFF_NXM:
858         return "nxm";
859     default:
860         NOT_REACHED();
861     }
862 }
863
864 int
865 ofputil_flow_format_from_string(const char *s)
866 {
867     return (!strcmp(s, "openflow10") ? NXFF_OPENFLOW10
868             : !strcmp(s, "nxm") ? NXFF_NXM
869             : -1);
870 }
871
872 bool
873 ofputil_packet_in_format_is_valid(enum nx_packet_in_format packet_in_format)
874 {
875     switch (packet_in_format) {
876     case NXPIF_OPENFLOW10:
877     case NXPIF_NXM:
878         return true;
879     }
880
881     return false;
882 }
883
884 const char *
885 ofputil_packet_in_format_to_string(enum nx_packet_in_format packet_in_format)
886 {
887     switch (packet_in_format) {
888     case NXPIF_OPENFLOW10:
889         return "openflow10";
890     case NXPIF_NXM:
891         return "nxm";
892     default:
893         NOT_REACHED();
894     }
895 }
896
897 int
898 ofputil_packet_in_format_from_string(const char *s)
899 {
900     return (!strcmp(s, "openflow10") ? NXPIF_OPENFLOW10
901             : !strcmp(s, "nxm") ? NXPIF_NXM
902             : -1);
903 }
904
905 static bool
906 regs_fully_wildcarded(const struct flow_wildcards *wc)
907 {
908     int i;
909
910     for (i = 0; i < FLOW_N_REGS; i++) {
911         if (wc->reg_masks[i] != 0) {
912             return false;
913         }
914     }
915     return true;
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).  Only NXM can handle tunnel IDs, registers,
920  * or fixing the Ethernet multicast bit.  Otherwise, it's better to use
921  * NXFF_OPENFLOW10 for backward compatibility. */
922 enum nx_flow_format
923 ofputil_min_flow_format(const struct cls_rule *rule)
924 {
925     const struct flow_wildcards *wc = &rule->wc;
926
927     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 8);
928
929     /* Only NXM supports separately wildcards the Ethernet multicast bit. */
930     if (!(wc->wildcards & FWW_DL_DST) != !(wc->wildcards & FWW_ETH_MCAST)) {
931         return NXFF_NXM;
932     }
933
934     /* Only NXM supports matching ARP hardware addresses. */
935     if (!(wc->wildcards & FWW_ARP_SHA) || !(wc->wildcards & FWW_ARP_THA)) {
936         return NXFF_NXM;
937     }
938
939     /* Only NXM supports matching IPv6 traffic. */
940     if (!(wc->wildcards & FWW_DL_TYPE)
941             && (rule->flow.dl_type == htons(ETH_TYPE_IPV6))) {
942         return NXFF_NXM;
943     }
944
945     /* Only NXM supports matching registers. */
946     if (!regs_fully_wildcarded(wc)) {
947         return NXFF_NXM;
948     }
949
950     /* Only NXM supports matching tun_id. */
951     if (wc->tun_id_mask != htonll(0)) {
952         return NXFF_NXM;
953     }
954
955     /* Only NXM supports matching fragments. */
956     if (wc->nw_frag_mask) {
957         return NXFF_NXM;
958     }
959
960     /* Only NXM supports matching IPv6 flow label. */
961     if (!(wc->wildcards & FWW_IPV6_LABEL)) {
962         return NXFF_NXM;
963     }
964
965     /* Only NXM supports matching IP ECN bits. */
966     if (!(wc->wildcards & FWW_NW_ECN)) {
967         return NXFF_NXM;
968     }
969
970     /* Only NXM supports matching IP TTL/hop limit. */
971     if (!(wc->wildcards & FWW_NW_TTL)) {
972         return NXFF_NXM;
973     }
974
975     /* Only NXM supports bitwise matching on transport port. */
976     if ((wc->tp_src_mask && wc->tp_src_mask != htons(UINT16_MAX)) ||
977         (wc->tp_dst_mask && wc->tp_dst_mask != htons(UINT16_MAX))) {
978         return NXFF_NXM;
979     }
980
981     /* Other formats can express this rule. */
982     return NXFF_OPENFLOW10;
983 }
984
985 /* Returns an OpenFlow message that can be used to set the flow format to
986  * 'flow_format'.  */
987 struct ofpbuf *
988 ofputil_make_set_flow_format(enum nx_flow_format flow_format)
989 {
990     struct nx_set_flow_format *sff;
991     struct ofpbuf *msg;
992
993     sff = make_nxmsg(sizeof *sff, NXT_SET_FLOW_FORMAT, &msg);
994     sff->format = htonl(flow_format);
995
996     return msg;
997 }
998
999 struct ofpbuf *
1000 ofputil_make_set_packet_in_format(enum nx_packet_in_format packet_in_format)
1001 {
1002     struct nx_set_packet_in_format *spif;
1003     struct ofpbuf *msg;
1004
1005     spif = make_nxmsg(sizeof *spif, NXT_SET_PACKET_IN_FORMAT, &msg);
1006     spif->format = htonl(packet_in_format);
1007
1008     return msg;
1009 }
1010
1011 /* Returns an OpenFlow message that can be used to turn the flow_mod_table_id
1012  * extension on or off (according to 'flow_mod_table_id'). */
1013 struct ofpbuf *
1014 ofputil_make_flow_mod_table_id(bool flow_mod_table_id)
1015 {
1016     struct nx_flow_mod_table_id *nfmti;
1017     struct ofpbuf *msg;
1018
1019     nfmti = make_nxmsg(sizeof *nfmti, NXT_FLOW_MOD_TABLE_ID, &msg);
1020     nfmti->set = flow_mod_table_id;
1021     return msg;
1022 }
1023
1024 /* Converts an OFPT_FLOW_MOD or NXT_FLOW_MOD message 'oh' into an abstract
1025  * flow_mod in 'fm'.  Returns 0 if successful, otherwise an OpenFlow error
1026  * code.
1027  *
1028  * 'flow_mod_table_id' should be true if the NXT_FLOW_MOD_TABLE_ID extension is
1029  * enabled, false otherwise.
1030  *
1031  * Does not validate the flow_mod actions. */
1032 enum ofperr
1033 ofputil_decode_flow_mod(struct ofputil_flow_mod *fm,
1034                         const struct ofp_header *oh, bool flow_mod_table_id)
1035 {
1036     const struct ofputil_msg_type *type;
1037     uint16_t command;
1038     struct ofpbuf b;
1039
1040     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1041
1042     ofputil_decode_msg_type(oh, &type);
1043     if (ofputil_msg_type_code(type) == OFPUTIL_OFPT_FLOW_MOD) {
1044         /* Standard OpenFlow flow_mod. */
1045         const struct ofp_flow_mod *ofm;
1046         uint16_t priority;
1047         enum ofperr error;
1048
1049         /* Dissect the message. */
1050         ofm = ofpbuf_pull(&b, sizeof *ofm);
1051         error = ofputil_pull_actions(&b, b.size, &fm->actions, &fm->n_actions);
1052         if (error) {
1053             return error;
1054         }
1055
1056         /* Set priority based on original wildcards.  Normally we'd allow
1057          * ofputil_cls_rule_from_match() to do this for us, but
1058          * ofputil_normalize_rule() can put wildcards where the original flow
1059          * didn't have them. */
1060         priority = ntohs(ofm->priority);
1061         if (!(ofm->match.wildcards & htonl(OFPFW_ALL))) {
1062             priority = UINT16_MAX;
1063         }
1064
1065         /* Translate the rule. */
1066         ofputil_cls_rule_from_match(&ofm->match, priority, &fm->cr);
1067         ofputil_normalize_rule(&fm->cr, NXFF_OPENFLOW10);
1068
1069         /* Translate the message. */
1070         fm->cookie = ofm->cookie;
1071         fm->cookie_mask = htonll(UINT64_MAX);
1072         command = ntohs(ofm->command);
1073         fm->idle_timeout = ntohs(ofm->idle_timeout);
1074         fm->hard_timeout = ntohs(ofm->hard_timeout);
1075         fm->buffer_id = ntohl(ofm->buffer_id);
1076         fm->out_port = ntohs(ofm->out_port);
1077         fm->flags = ntohs(ofm->flags);
1078     } else if (ofputil_msg_type_code(type) == OFPUTIL_NXT_FLOW_MOD) {
1079         /* Nicira extended flow_mod. */
1080         const struct nx_flow_mod *nfm;
1081         enum ofperr error;
1082
1083         /* Dissect the message. */
1084         nfm = ofpbuf_pull(&b, sizeof *nfm);
1085         error = nx_pull_match(&b, ntohs(nfm->match_len), ntohs(nfm->priority),
1086                               &fm->cr, &fm->cookie, &fm->cookie_mask);
1087         if (error) {
1088             return error;
1089         }
1090         error = ofputil_pull_actions(&b, b.size, &fm->actions, &fm->n_actions);
1091         if (error) {
1092             return error;
1093         }
1094
1095         /* Translate the message. */
1096         command = ntohs(nfm->command);
1097         if (command == OFPFC_ADD) {
1098             if (fm->cookie_mask) {
1099                 /* The "NXM_NX_COOKIE*" matches are not valid for flow
1100                  * additions.  Additions must use the "cookie" field of
1101                  * the "nx_flow_mod" structure. */
1102                 return OFPERR_NXBRC_NXM_INVALID;
1103             } else {
1104                 fm->cookie = nfm->cookie;
1105                 fm->cookie_mask = htonll(UINT64_MAX);
1106             }
1107         }
1108         fm->idle_timeout = ntohs(nfm->idle_timeout);
1109         fm->hard_timeout = ntohs(nfm->hard_timeout);
1110         fm->buffer_id = ntohl(nfm->buffer_id);
1111         fm->out_port = ntohs(nfm->out_port);
1112         fm->flags = ntohs(nfm->flags);
1113     } else {
1114         NOT_REACHED();
1115     }
1116
1117     if (flow_mod_table_id) {
1118         fm->command = command & 0xff;
1119         fm->table_id = command >> 8;
1120     } else {
1121         fm->command = command;
1122         fm->table_id = 0xff;
1123     }
1124
1125     return 0;
1126 }
1127
1128 /* Converts 'fm' into an OFPT_FLOW_MOD or NXT_FLOW_MOD message according to
1129  * 'flow_format' and returns the message.
1130  *
1131  * 'flow_mod_table_id' should be true if the NXT_FLOW_MOD_TABLE_ID extension is
1132  * enabled, false otherwise. */
1133 struct ofpbuf *
1134 ofputil_encode_flow_mod(const struct ofputil_flow_mod *fm,
1135                         enum nx_flow_format flow_format,
1136                         bool flow_mod_table_id)
1137 {
1138     size_t actions_len = fm->n_actions * sizeof *fm->actions;
1139     struct ofpbuf *msg;
1140     uint16_t command;
1141
1142     command = (flow_mod_table_id
1143                ? (fm->command & 0xff) | (fm->table_id << 8)
1144                : fm->command);
1145
1146     if (flow_format == NXFF_OPENFLOW10) {
1147         struct ofp_flow_mod *ofm;
1148
1149         msg = ofpbuf_new(sizeof *ofm + actions_len);
1150         ofm = put_openflow(sizeof *ofm, OFPT_FLOW_MOD, msg);
1151         ofputil_cls_rule_to_match(&fm->cr, &ofm->match);
1152         ofm->cookie = fm->cookie;
1153         ofm->command = htons(command);
1154         ofm->idle_timeout = htons(fm->idle_timeout);
1155         ofm->hard_timeout = htons(fm->hard_timeout);
1156         ofm->priority = htons(fm->cr.priority);
1157         ofm->buffer_id = htonl(fm->buffer_id);
1158         ofm->out_port = htons(fm->out_port);
1159         ofm->flags = htons(fm->flags);
1160     } else if (flow_format == NXFF_NXM) {
1161         struct nx_flow_mod *nfm;
1162         int match_len;
1163
1164         msg = ofpbuf_new(sizeof *nfm + NXM_TYPICAL_LEN + actions_len);
1165         put_nxmsg(sizeof *nfm, NXT_FLOW_MOD, msg);
1166         nfm = msg->data;
1167         nfm->command = htons(command);
1168         if (command == OFPFC_ADD) {
1169             nfm->cookie = fm->cookie;
1170             match_len = nx_put_match(msg, &fm->cr, 0, 0);
1171         } else {
1172             nfm->cookie = 0;
1173             match_len = nx_put_match(msg, &fm->cr,
1174                                      fm->cookie, fm->cookie_mask);
1175         }
1176         nfm->idle_timeout = htons(fm->idle_timeout);
1177         nfm->hard_timeout = htons(fm->hard_timeout);
1178         nfm->priority = htons(fm->cr.priority);
1179         nfm->buffer_id = htonl(fm->buffer_id);
1180         nfm->out_port = htons(fm->out_port);
1181         nfm->flags = htons(fm->flags);
1182         nfm->match_len = htons(match_len);
1183     } else {
1184         NOT_REACHED();
1185     }
1186
1187     ofpbuf_put(msg, fm->actions, actions_len);
1188     update_openflow_length(msg);
1189     return msg;
1190 }
1191
1192 static enum ofperr
1193 ofputil_decode_ofpst_flow_request(struct ofputil_flow_stats_request *fsr,
1194                                   const struct ofp_header *oh,
1195                                   bool aggregate)
1196 {
1197     const struct ofp_flow_stats_request *ofsr =
1198         (const struct ofp_flow_stats_request *) oh;
1199
1200     fsr->aggregate = aggregate;
1201     ofputil_cls_rule_from_match(&ofsr->match, 0, &fsr->match);
1202     fsr->out_port = ntohs(ofsr->out_port);
1203     fsr->table_id = ofsr->table_id;
1204     fsr->cookie = fsr->cookie_mask = htonll(0);
1205
1206     return 0;
1207 }
1208
1209 static enum ofperr
1210 ofputil_decode_nxst_flow_request(struct ofputil_flow_stats_request *fsr,
1211                                  const struct ofp_header *oh,
1212                                  bool aggregate)
1213 {
1214     const struct nx_flow_stats_request *nfsr;
1215     struct ofpbuf b;
1216     enum ofperr error;
1217
1218     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1219
1220     nfsr = ofpbuf_pull(&b, sizeof *nfsr);
1221     error = nx_pull_match(&b, ntohs(nfsr->match_len), 0, &fsr->match,
1222                           &fsr->cookie, &fsr->cookie_mask);
1223     if (error) {
1224         return error;
1225     }
1226     if (b.size) {
1227         return OFPERR_OFPBRC_BAD_LEN;
1228     }
1229
1230     fsr->aggregate = aggregate;
1231     fsr->out_port = ntohs(nfsr->out_port);
1232     fsr->table_id = nfsr->table_id;
1233
1234     return 0;
1235 }
1236
1237 /* Converts an OFPST_FLOW, OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE
1238  * request 'oh', into an abstract flow_stats_request in 'fsr'.  Returns 0 if
1239  * successful, otherwise an OpenFlow error code. */
1240 enum ofperr
1241 ofputil_decode_flow_stats_request(struct ofputil_flow_stats_request *fsr,
1242                                   const struct ofp_header *oh)
1243 {
1244     const struct ofputil_msg_type *type;
1245     struct ofpbuf b;
1246     int code;
1247
1248     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1249
1250     ofputil_decode_msg_type(oh, &type);
1251     code = ofputil_msg_type_code(type);
1252     switch (code) {
1253     case OFPUTIL_OFPST_FLOW_REQUEST:
1254         return ofputil_decode_ofpst_flow_request(fsr, oh, false);
1255
1256     case OFPUTIL_OFPST_AGGREGATE_REQUEST:
1257         return ofputil_decode_ofpst_flow_request(fsr, oh, true);
1258
1259     case OFPUTIL_NXST_FLOW_REQUEST:
1260         return ofputil_decode_nxst_flow_request(fsr, oh, false);
1261
1262     case OFPUTIL_NXST_AGGREGATE_REQUEST:
1263         return ofputil_decode_nxst_flow_request(fsr, oh, true);
1264
1265     default:
1266         /* Hey, the caller lied. */
1267         NOT_REACHED();
1268     }
1269 }
1270
1271 /* Converts abstract flow_stats_request 'fsr' into an OFPST_FLOW,
1272  * OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE request 'oh' according to
1273  * 'flow_format', and returns the message. */
1274 struct ofpbuf *
1275 ofputil_encode_flow_stats_request(const struct ofputil_flow_stats_request *fsr,
1276                                   enum nx_flow_format flow_format)
1277 {
1278     struct ofpbuf *msg;
1279
1280     if (flow_format == NXFF_OPENFLOW10) {
1281         struct ofp_flow_stats_request *ofsr;
1282         int type;
1283
1284         type = fsr->aggregate ? OFPST_AGGREGATE : OFPST_FLOW;
1285         ofsr = ofputil_make_stats_request(sizeof *ofsr, type, 0, &msg);
1286         ofputil_cls_rule_to_match(&fsr->match, &ofsr->match);
1287         ofsr->table_id = fsr->table_id;
1288         ofsr->out_port = htons(fsr->out_port);
1289     } else if (flow_format == NXFF_NXM) {
1290         struct nx_flow_stats_request *nfsr;
1291         int match_len;
1292         int subtype;
1293
1294         subtype = fsr->aggregate ? NXST_AGGREGATE : NXST_FLOW;
1295         ofputil_make_stats_request(sizeof *nfsr, OFPST_VENDOR, subtype, &msg);
1296         match_len = nx_put_match(msg, &fsr->match,
1297                                  fsr->cookie, fsr->cookie_mask);
1298
1299         nfsr = msg->data;
1300         nfsr->out_port = htons(fsr->out_port);
1301         nfsr->match_len = htons(match_len);
1302         nfsr->table_id = fsr->table_id;
1303     } else {
1304         NOT_REACHED();
1305     }
1306
1307     return msg;
1308 }
1309
1310 /* Converts an OFPST_FLOW or NXST_FLOW reply in 'msg' into an abstract
1311  * ofputil_flow_stats in 'fs'.
1312  *
1313  * Multiple OFPST_FLOW or NXST_FLOW replies can be packed into a single
1314  * OpenFlow message.  Calling this function multiple times for a single 'msg'
1315  * iterates through the replies.  The caller must initially leave 'msg''s layer
1316  * pointers null and not modify them between calls.
1317  *
1318  * Most switches don't send the values needed to populate fs->idle_age and
1319  * fs->hard_age, so those members will usually be set to 0.  If the switch from
1320  * which 'msg' originated is known to implement NXT_FLOW_AGE, then pass
1321  * 'flow_age_extension' as true so that the contents of 'msg' determine the
1322  * 'idle_age' and 'hard_age' members in 'fs'.
1323  *
1324  * Returns 0 if successful, EOF if no replies were left in this 'msg',
1325  * otherwise a positive errno value. */
1326 int
1327 ofputil_decode_flow_stats_reply(struct ofputil_flow_stats *fs,
1328                                 struct ofpbuf *msg,
1329                                 bool flow_age_extension)
1330 {
1331     const struct ofputil_msg_type *type;
1332     int code;
1333
1334     ofputil_decode_msg_type(msg->l2 ? msg->l2 : msg->data, &type);
1335     code = ofputil_msg_type_code(type);
1336     if (!msg->l2) {
1337         msg->l2 = msg->data;
1338         if (code == OFPUTIL_OFPST_FLOW_REPLY) {
1339             ofpbuf_pull(msg, sizeof(struct ofp_stats_msg));
1340         } else if (code == OFPUTIL_NXST_FLOW_REPLY) {
1341             ofpbuf_pull(msg, sizeof(struct nicira_stats_msg));
1342         } else {
1343             NOT_REACHED();
1344         }
1345     }
1346
1347     if (!msg->size) {
1348         return EOF;
1349     } else if (code == OFPUTIL_OFPST_FLOW_REPLY) {
1350         const struct ofp_flow_stats *ofs;
1351         size_t length;
1352
1353         ofs = ofpbuf_try_pull(msg, sizeof *ofs);
1354         if (!ofs) {
1355             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply has %zu leftover "
1356                          "bytes at end", msg->size);
1357             return EINVAL;
1358         }
1359
1360         length = ntohs(ofs->length);
1361         if (length < sizeof *ofs) {
1362             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply claims invalid "
1363                          "length %zu", length);
1364             return EINVAL;
1365         }
1366
1367         if (ofputil_pull_actions(msg, length - sizeof *ofs,
1368                                  &fs->actions, &fs->n_actions)) {
1369             return EINVAL;
1370         }
1371
1372         fs->cookie = get_32aligned_be64(&ofs->cookie);
1373         ofputil_cls_rule_from_match(&ofs->match, ntohs(ofs->priority),
1374                                     &fs->rule);
1375         fs->table_id = ofs->table_id;
1376         fs->duration_sec = ntohl(ofs->duration_sec);
1377         fs->duration_nsec = ntohl(ofs->duration_nsec);
1378         fs->idle_timeout = ntohs(ofs->idle_timeout);
1379         fs->hard_timeout = ntohs(ofs->hard_timeout);
1380         fs->idle_age = -1;
1381         fs->hard_age = -1;
1382         fs->packet_count = ntohll(get_32aligned_be64(&ofs->packet_count));
1383         fs->byte_count = ntohll(get_32aligned_be64(&ofs->byte_count));
1384     } else if (code == OFPUTIL_NXST_FLOW_REPLY) {
1385         const struct nx_flow_stats *nfs;
1386         size_t match_len, length;
1387
1388         nfs = ofpbuf_try_pull(msg, sizeof *nfs);
1389         if (!nfs) {
1390             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply has %zu leftover "
1391                          "bytes at end", msg->size);
1392             return EINVAL;
1393         }
1394
1395         length = ntohs(nfs->length);
1396         match_len = ntohs(nfs->match_len);
1397         if (length < sizeof *nfs + ROUND_UP(match_len, 8)) {
1398             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply with match_len=%zu "
1399                          "claims invalid length %zu", match_len, length);
1400             return EINVAL;
1401         }
1402         if (nx_pull_match(msg, match_len, ntohs(nfs->priority), &fs->rule,
1403                           NULL, NULL)) {
1404             return EINVAL;
1405         }
1406
1407         if (ofputil_pull_actions(msg,
1408                                  length - sizeof *nfs - ROUND_UP(match_len, 8),
1409                                  &fs->actions, &fs->n_actions)) {
1410             return EINVAL;
1411         }
1412
1413         fs->cookie = nfs->cookie;
1414         fs->table_id = nfs->table_id;
1415         fs->duration_sec = ntohl(nfs->duration_sec);
1416         fs->duration_nsec = ntohl(nfs->duration_nsec);
1417         fs->idle_timeout = ntohs(nfs->idle_timeout);
1418         fs->hard_timeout = ntohs(nfs->hard_timeout);
1419         fs->idle_age = -1;
1420         fs->hard_age = -1;
1421         if (flow_age_extension) {
1422             if (nfs->idle_age) {
1423                 fs->idle_age = ntohs(nfs->idle_age) - 1;
1424             }
1425             if (nfs->hard_age) {
1426                 fs->hard_age = ntohs(nfs->hard_age) - 1;
1427             }
1428         }
1429         fs->packet_count = ntohll(nfs->packet_count);
1430         fs->byte_count = ntohll(nfs->byte_count);
1431     } else {
1432         NOT_REACHED();
1433     }
1434
1435     return 0;
1436 }
1437
1438 /* Returns 'count' unchanged except that UINT64_MAX becomes 0.
1439  *
1440  * We use this in situations where OVS internally uses UINT64_MAX to mean
1441  * "value unknown" but OpenFlow 1.0 does not define any unknown value. */
1442 static uint64_t
1443 unknown_to_zero(uint64_t count)
1444 {
1445     return count != UINT64_MAX ? count : 0;
1446 }
1447
1448 /* Appends an OFPST_FLOW or NXST_FLOW reply that contains the data in 'fs' to
1449  * those already present in the list of ofpbufs in 'replies'.  'replies' should
1450  * have been initialized with ofputil_start_stats_reply(). */
1451 void
1452 ofputil_append_flow_stats_reply(const struct ofputil_flow_stats *fs,
1453                                 struct list *replies)
1454 {
1455     size_t act_len = fs->n_actions * sizeof *fs->actions;
1456     const struct ofp_stats_msg *osm;
1457
1458     osm = ofpbuf_from_list(list_back(replies))->data;
1459     if (osm->type == htons(OFPST_FLOW)) {
1460         size_t len = offsetof(struct ofp_flow_stats, actions) + act_len;
1461         struct ofp_flow_stats *ofs;
1462
1463         ofs = ofputil_append_stats_reply(len, replies);
1464         ofs->length = htons(len);
1465         ofs->table_id = fs->table_id;
1466         ofs->pad = 0;
1467         ofputil_cls_rule_to_match(&fs->rule, &ofs->match);
1468         ofs->duration_sec = htonl(fs->duration_sec);
1469         ofs->duration_nsec = htonl(fs->duration_nsec);
1470         ofs->priority = htons(fs->rule.priority);
1471         ofs->idle_timeout = htons(fs->idle_timeout);
1472         ofs->hard_timeout = htons(fs->hard_timeout);
1473         memset(ofs->pad2, 0, sizeof ofs->pad2);
1474         put_32aligned_be64(&ofs->cookie, fs->cookie);
1475         put_32aligned_be64(&ofs->packet_count,
1476                            htonll(unknown_to_zero(fs->packet_count)));
1477         put_32aligned_be64(&ofs->byte_count,
1478                            htonll(unknown_to_zero(fs->byte_count)));
1479         memcpy(ofs->actions, fs->actions, act_len);
1480     } else if (osm->type == htons(OFPST_VENDOR)) {
1481         struct nx_flow_stats *nfs;
1482         struct ofpbuf *msg;
1483         size_t start_len;
1484
1485         msg = ofputil_reserve_stats_reply(
1486             sizeof *nfs + NXM_MAX_LEN + act_len, replies);
1487         start_len = msg->size;
1488
1489         nfs = ofpbuf_put_uninit(msg, sizeof *nfs);
1490         nfs->table_id = fs->table_id;
1491         nfs->pad = 0;
1492         nfs->duration_sec = htonl(fs->duration_sec);
1493         nfs->duration_nsec = htonl(fs->duration_nsec);
1494         nfs->priority = htons(fs->rule.priority);
1495         nfs->idle_timeout = htons(fs->idle_timeout);
1496         nfs->hard_timeout = htons(fs->hard_timeout);
1497         nfs->idle_age = htons(fs->idle_age < 0 ? 0
1498                               : fs->idle_age < UINT16_MAX ? fs->idle_age + 1
1499                               : UINT16_MAX);
1500         nfs->hard_age = htons(fs->hard_age < 0 ? 0
1501                               : fs->hard_age < UINT16_MAX ? fs->hard_age + 1
1502                               : UINT16_MAX);
1503         nfs->match_len = htons(nx_put_match(msg, &fs->rule, 0, 0));
1504         nfs->cookie = fs->cookie;
1505         nfs->packet_count = htonll(fs->packet_count);
1506         nfs->byte_count = htonll(fs->byte_count);
1507         ofpbuf_put(msg, fs->actions, act_len);
1508         nfs->length = htons(msg->size - start_len);
1509     } else {
1510         NOT_REACHED();
1511     }
1512 }
1513
1514 /* Converts abstract ofputil_aggregate_stats 'stats' into an OFPST_AGGREGATE or
1515  * NXST_AGGREGATE reply according to 'flow_format', and returns the message. */
1516 struct ofpbuf *
1517 ofputil_encode_aggregate_stats_reply(
1518     const struct ofputil_aggregate_stats *stats,
1519     const struct ofp_stats_msg *request)
1520 {
1521     struct ofpbuf *msg;
1522
1523     if (request->type == htons(OFPST_AGGREGATE)) {
1524         struct ofp_aggregate_stats_reply *asr;
1525
1526         asr = ofputil_make_stats_reply(sizeof *asr, request, &msg);
1527         put_32aligned_be64(&asr->packet_count,
1528                            htonll(unknown_to_zero(stats->packet_count)));
1529         put_32aligned_be64(&asr->byte_count,
1530                            htonll(unknown_to_zero(stats->byte_count)));
1531         asr->flow_count = htonl(stats->flow_count);
1532     } else if (request->type == htons(OFPST_VENDOR)) {
1533         struct nx_aggregate_stats_reply *nasr;
1534
1535         nasr = ofputil_make_stats_reply(sizeof *nasr, request, &msg);
1536         assert(nasr->nsm.subtype == htonl(NXST_AGGREGATE));
1537         nasr->packet_count = htonll(stats->packet_count);
1538         nasr->byte_count = htonll(stats->byte_count);
1539         nasr->flow_count = htonl(stats->flow_count);
1540     } else {
1541         NOT_REACHED();
1542     }
1543
1544     return msg;
1545 }
1546
1547 /* Converts an OFPT_FLOW_REMOVED or NXT_FLOW_REMOVED message 'oh' into an
1548  * abstract ofputil_flow_removed in 'fr'.  Returns 0 if successful, otherwise
1549  * an OpenFlow error code. */
1550 enum ofperr
1551 ofputil_decode_flow_removed(struct ofputil_flow_removed *fr,
1552                             const struct ofp_header *oh)
1553 {
1554     const struct ofputil_msg_type *type;
1555     enum ofputil_msg_code code;
1556
1557     ofputil_decode_msg_type(oh, &type);
1558     code = ofputil_msg_type_code(type);
1559     if (code == OFPUTIL_OFPT_FLOW_REMOVED) {
1560         const struct ofp_flow_removed *ofr;
1561
1562         ofr = (const struct ofp_flow_removed *) oh;
1563         ofputil_cls_rule_from_match(&ofr->match, ntohs(ofr->priority),
1564                                     &fr->rule);
1565         fr->cookie = ofr->cookie;
1566         fr->reason = ofr->reason;
1567         fr->duration_sec = ntohl(ofr->duration_sec);
1568         fr->duration_nsec = ntohl(ofr->duration_nsec);
1569         fr->idle_timeout = ntohs(ofr->idle_timeout);
1570         fr->packet_count = ntohll(ofr->packet_count);
1571         fr->byte_count = ntohll(ofr->byte_count);
1572     } else if (code == OFPUTIL_NXT_FLOW_REMOVED) {
1573         struct nx_flow_removed *nfr;
1574         struct ofpbuf b;
1575         int error;
1576
1577         ofpbuf_use_const(&b, oh, ntohs(oh->length));
1578
1579         nfr = ofpbuf_pull(&b, sizeof *nfr);
1580         error = nx_pull_match(&b, ntohs(nfr->match_len), ntohs(nfr->priority),
1581                               &fr->rule, NULL, NULL);
1582         if (error) {
1583             return error;
1584         }
1585         if (b.size) {
1586             return OFPERR_OFPBRC_BAD_LEN;
1587         }
1588
1589         fr->cookie = nfr->cookie;
1590         fr->reason = nfr->reason;
1591         fr->duration_sec = ntohl(nfr->duration_sec);
1592         fr->duration_nsec = ntohl(nfr->duration_nsec);
1593         fr->idle_timeout = ntohs(nfr->idle_timeout);
1594         fr->packet_count = ntohll(nfr->packet_count);
1595         fr->byte_count = ntohll(nfr->byte_count);
1596     } else {
1597         NOT_REACHED();
1598     }
1599
1600     return 0;
1601 }
1602
1603 /* Converts abstract ofputil_flow_removed 'fr' into an OFPT_FLOW_REMOVED or
1604  * NXT_FLOW_REMOVED message 'oh' according to 'flow_format', and returns the
1605  * message. */
1606 struct ofpbuf *
1607 ofputil_encode_flow_removed(const struct ofputil_flow_removed *fr,
1608                             enum nx_flow_format flow_format)
1609 {
1610     struct ofpbuf *msg;
1611
1612     if (flow_format == NXFF_OPENFLOW10) {
1613         struct ofp_flow_removed *ofr;
1614
1615         ofr = make_openflow_xid(sizeof *ofr, OFPT_FLOW_REMOVED, htonl(0),
1616                                 &msg);
1617         ofputil_cls_rule_to_match(&fr->rule, &ofr->match);
1618         ofr->cookie = fr->cookie;
1619         ofr->priority = htons(fr->rule.priority);
1620         ofr->reason = fr->reason;
1621         ofr->duration_sec = htonl(fr->duration_sec);
1622         ofr->duration_nsec = htonl(fr->duration_nsec);
1623         ofr->idle_timeout = htons(fr->idle_timeout);
1624         ofr->packet_count = htonll(unknown_to_zero(fr->packet_count));
1625         ofr->byte_count = htonll(unknown_to_zero(fr->byte_count));
1626     } else if (flow_format == NXFF_NXM) {
1627         struct nx_flow_removed *nfr;
1628         int match_len;
1629
1630         make_nxmsg_xid(sizeof *nfr, NXT_FLOW_REMOVED, htonl(0), &msg);
1631         match_len = nx_put_match(msg, &fr->rule, 0, 0);
1632
1633         nfr = msg->data;
1634         nfr->cookie = fr->cookie;
1635         nfr->priority = htons(fr->rule.priority);
1636         nfr->reason = fr->reason;
1637         nfr->duration_sec = htonl(fr->duration_sec);
1638         nfr->duration_nsec = htonl(fr->duration_nsec);
1639         nfr->idle_timeout = htons(fr->idle_timeout);
1640         nfr->match_len = htons(match_len);
1641         nfr->packet_count = htonll(fr->packet_count);
1642         nfr->byte_count = htonll(fr->byte_count);
1643     } else {
1644         NOT_REACHED();
1645     }
1646
1647     return msg;
1648 }
1649
1650 int
1651 ofputil_decode_packet_in(struct ofputil_packet_in *pin,
1652                          const struct ofp_header *oh)
1653 {
1654     const struct ofputil_msg_type *type;
1655     enum ofputil_msg_code code;
1656
1657     ofputil_decode_msg_type(oh, &type);
1658     code = ofputil_msg_type_code(type);
1659     memset(pin, 0, sizeof *pin);
1660
1661     if (code == OFPUTIL_OFPT_PACKET_IN) {
1662         const struct ofp_packet_in *opi = (const struct ofp_packet_in *) oh;
1663
1664         pin->packet = opi->data;
1665         pin->packet_len = ntohs(opi->header.length)
1666             - offsetof(struct ofp_packet_in, data);
1667
1668         pin->fmd.in_port = ntohs(opi->in_port);
1669         pin->reason = opi->reason;
1670         pin->buffer_id = ntohl(opi->buffer_id);
1671         pin->total_len = ntohs(opi->total_len);
1672     } else if (code == OFPUTIL_NXT_PACKET_IN) {
1673         const struct nx_packet_in *npi;
1674         struct cls_rule rule;
1675         struct ofpbuf b;
1676         int error;
1677
1678         ofpbuf_use_const(&b, oh, ntohs(oh->length));
1679
1680         npi = ofpbuf_pull(&b, sizeof *npi);
1681         error = nx_pull_match_loose(&b, ntohs(npi->match_len), 0, &rule, NULL,
1682                               NULL);
1683         if (error) {
1684             return error;
1685         }
1686
1687         if (!ofpbuf_try_pull(&b, 2)) {
1688             return OFPERR_OFPBRC_BAD_LEN;
1689         }
1690
1691         pin->packet = b.data;
1692         pin->packet_len = b.size;
1693         pin->reason = npi->reason;
1694         pin->table_id = npi->table_id;
1695         pin->cookie = npi->cookie;
1696
1697         pin->fmd.in_port = rule.flow.in_port;
1698
1699         pin->fmd.tun_id = rule.flow.tun_id;
1700         pin->fmd.tun_id_mask = rule.wc.tun_id_mask;
1701
1702         memcpy(pin->fmd.regs, rule.flow.regs, sizeof pin->fmd.regs);
1703         memcpy(pin->fmd.reg_masks, rule.wc.reg_masks,
1704                sizeof pin->fmd.reg_masks);
1705
1706         pin->buffer_id = ntohl(npi->buffer_id);
1707         pin->total_len = ntohs(npi->total_len);
1708     } else {
1709         NOT_REACHED();
1710     }
1711
1712     return 0;
1713 }
1714
1715 /* Converts abstract ofputil_packet_in 'pin' into a PACKET_IN message
1716  * in the format specified by 'packet_in_format'.  */
1717 struct ofpbuf *
1718 ofputil_encode_packet_in(const struct ofputil_packet_in *pin,
1719                          enum nx_packet_in_format packet_in_format)
1720 {
1721     size_t send_len = MIN(pin->send_len, pin->packet_len);
1722     struct ofpbuf *packet;
1723
1724     /* Add OFPT_PACKET_IN. */
1725     if (packet_in_format == NXPIF_OPENFLOW10) {
1726         size_t header_len = offsetof(struct ofp_packet_in, data);
1727         struct ofp_packet_in *opi;
1728
1729         packet = ofpbuf_new(send_len + header_len);
1730         opi = ofpbuf_put_zeros(packet, header_len);
1731         opi->header.version = OFP_VERSION;
1732         opi->header.type = OFPT_PACKET_IN;
1733         opi->total_len = htons(pin->total_len);
1734         opi->in_port = htons(pin->fmd.in_port);
1735         opi->reason = pin->reason;
1736         opi->buffer_id = htonl(pin->buffer_id);
1737
1738         ofpbuf_put(packet, pin->packet, send_len);
1739     } else if (packet_in_format == NXPIF_NXM) {
1740         struct nx_packet_in *npi;
1741         struct cls_rule rule;
1742         size_t match_len;
1743         size_t i;
1744
1745         /* Estimate of required PACKET_IN length includes the NPI header, space
1746          * for the match (2 times sizeof the metadata seems like enough), 2
1747          * bytes for padding, and the packet length. */
1748         packet = ofpbuf_new(sizeof *npi + sizeof(struct flow_metadata) * 2
1749                             + 2 + send_len);
1750
1751         cls_rule_init_catchall(&rule, 0);
1752         cls_rule_set_tun_id_masked(&rule, pin->fmd.tun_id,
1753                                    pin->fmd.tun_id_mask);
1754
1755         for (i = 0; i < FLOW_N_REGS; i++) {
1756             cls_rule_set_reg_masked(&rule, i, pin->fmd.regs[i],
1757                                     pin->fmd.reg_masks[i]);
1758         }
1759
1760         cls_rule_set_in_port(&rule, pin->fmd.in_port);
1761
1762         ofpbuf_put_zeros(packet, sizeof *npi);
1763         match_len = nx_put_match(packet, &rule, 0, 0);
1764         ofpbuf_put_zeros(packet, 2);
1765         ofpbuf_put(packet, pin->packet, send_len);
1766
1767         npi = packet->data;
1768         npi->nxh.header.version = OFP_VERSION;
1769         npi->nxh.header.type = OFPT_VENDOR;
1770         npi->nxh.vendor = htonl(NX_VENDOR_ID);
1771         npi->nxh.subtype = htonl(NXT_PACKET_IN);
1772
1773         npi->buffer_id = htonl(pin->buffer_id);
1774         npi->total_len = htons(pin->total_len);
1775         npi->reason = pin->reason;
1776         npi->table_id = pin->table_id;
1777         npi->cookie = pin->cookie;
1778         npi->match_len = htons(match_len);
1779     } else {
1780         NOT_REACHED();
1781     }
1782     update_openflow_length(packet);
1783
1784     return packet;
1785 }
1786
1787 enum ofperr
1788 ofputil_decode_packet_out(struct ofputil_packet_out *po,
1789                           const struct ofp_packet_out *opo)
1790 {
1791     enum ofperr error;
1792     struct ofpbuf b;
1793
1794     po->buffer_id = ntohl(opo->buffer_id);
1795     po->in_port = ntohs(opo->in_port);
1796     if (po->in_port >= OFPP_MAX && po->in_port != OFPP_LOCAL
1797         && po->in_port != OFPP_NONE) {
1798         VLOG_WARN_RL(&bad_ofmsg_rl, "packet-out has bad input port %#"PRIx16,
1799                      po->in_port);
1800         return OFPERR_NXBRC_BAD_IN_PORT;
1801     }
1802
1803     ofpbuf_use_const(&b, opo, ntohs(opo->header.length));
1804     ofpbuf_pull(&b, sizeof *opo);
1805
1806     error = ofputil_pull_actions(&b, ntohs(opo->actions_len),
1807                                  &po->actions, &po->n_actions);
1808     if (error) {
1809         return error;
1810     }
1811
1812     if (po->buffer_id == UINT32_MAX) {
1813         po->packet = b.data;
1814         po->packet_len = b.size;
1815     } else {
1816         po->packet = NULL;
1817         po->packet_len = 0;
1818     }
1819
1820     return 0;
1821 }
1822
1823 struct ofpbuf *
1824 ofputil_encode_packet_out(const struct ofputil_packet_out *po)
1825 {
1826     struct ofp_packet_out *opo;
1827     size_t actions_len;
1828     struct ofpbuf *msg;
1829     size_t size;
1830
1831     actions_len = po->n_actions * sizeof *po->actions;
1832     size = sizeof *opo + actions_len;
1833     if (po->buffer_id == UINT32_MAX) {
1834         size += po->packet_len;
1835     }
1836
1837     msg = ofpbuf_new(size);
1838     opo = put_openflow(sizeof *opo, OFPT_PACKET_OUT, msg);
1839     opo->buffer_id = htonl(po->buffer_id);
1840     opo->in_port = htons(po->in_port);
1841     opo->actions_len = htons(actions_len);
1842     ofpbuf_put(msg, po->actions, actions_len);
1843     if (po->buffer_id == UINT32_MAX) {
1844         ofpbuf_put(msg, po->packet, po->packet_len);
1845     }
1846     update_openflow_length(msg);
1847
1848     return msg;
1849 }
1850
1851 /* Returns a string representing the message type of 'type'.  The string is the
1852  * enumeration constant for the type, e.g. "OFPT_HELLO".  For statistics
1853  * messages, the constant is followed by "request" or "reply",
1854  * e.g. "OFPST_AGGREGATE reply". */
1855 const char *
1856 ofputil_msg_type_name(const struct ofputil_msg_type *type)
1857 {
1858     return type->name;
1859 }
1860 \f
1861 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
1862  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
1863  * an arbitrary transaction id.  Allocated bytes beyond the header, if any, are
1864  * zeroed.
1865  *
1866  * The caller is responsible for freeing '*bufferp' when it is no longer
1867  * needed.
1868  *
1869  * The OpenFlow header length is initially set to 'openflow_len'; if the
1870  * message is later extended, the length should be updated with
1871  * update_openflow_length() before sending.
1872  *
1873  * Returns the header. */
1874 void *
1875 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp)
1876 {
1877     *bufferp = ofpbuf_new(openflow_len);
1878     return put_openflow_xid(openflow_len, type, alloc_xid(), *bufferp);
1879 }
1880
1881 /* Similar to make_openflow() but creates a Nicira vendor extension message
1882  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1883 void *
1884 make_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf **bufferp)
1885 {
1886     return make_nxmsg_xid(openflow_len, subtype, alloc_xid(), bufferp);
1887 }
1888
1889 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
1890  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
1891  * transaction id 'xid'.  Allocated bytes beyond the header, if any, are
1892  * zeroed.
1893  *
1894  * The caller is responsible for freeing '*bufferp' when it is no longer
1895  * needed.
1896  *
1897  * The OpenFlow header length is initially set to 'openflow_len'; if the
1898  * message is later extended, the length should be updated with
1899  * update_openflow_length() before sending.
1900  *
1901  * Returns the header. */
1902 void *
1903 make_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
1904                   struct ofpbuf **bufferp)
1905 {
1906     *bufferp = ofpbuf_new(openflow_len);
1907     return put_openflow_xid(openflow_len, type, xid, *bufferp);
1908 }
1909
1910 /* Similar to make_openflow_xid() but creates a Nicira vendor extension message
1911  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1912 void *
1913 make_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
1914                struct ofpbuf **bufferp)
1915 {
1916     *bufferp = ofpbuf_new(openflow_len);
1917     return put_nxmsg_xid(openflow_len, subtype, xid, *bufferp);
1918 }
1919
1920 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
1921  * with the given 'type' and an arbitrary transaction id.  Allocated bytes
1922  * beyond the header, if any, are zeroed.
1923  *
1924  * The OpenFlow header length is initially set to 'openflow_len'; if the
1925  * message is later extended, the length should be updated with
1926  * update_openflow_length() before sending.
1927  *
1928  * Returns the header. */
1929 void *
1930 put_openflow(size_t openflow_len, uint8_t type, struct ofpbuf *buffer)
1931 {
1932     return put_openflow_xid(openflow_len, type, alloc_xid(), buffer);
1933 }
1934
1935 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
1936  * with the given 'type' and an transaction id 'xid'.  Allocated bytes beyond
1937  * the header, if any, are zeroed.
1938  *
1939  * The OpenFlow header length is initially set to 'openflow_len'; if the
1940  * message is later extended, the length should be updated with
1941  * update_openflow_length() before sending.
1942  *
1943  * Returns the header. */
1944 void *
1945 put_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
1946                  struct ofpbuf *buffer)
1947 {
1948     struct ofp_header *oh;
1949
1950     assert(openflow_len >= sizeof *oh);
1951     assert(openflow_len <= UINT16_MAX);
1952
1953     oh = ofpbuf_put_uninit(buffer, openflow_len);
1954     oh->version = OFP_VERSION;
1955     oh->type = type;
1956     oh->length = htons(openflow_len);
1957     oh->xid = xid;
1958     memset(oh + 1, 0, openflow_len - sizeof *oh);
1959     return oh;
1960 }
1961
1962 /* Similar to put_openflow() but append a Nicira vendor extension message with
1963  * the specific 'subtype'.  'subtype' should be in host byte order. */
1964 void *
1965 put_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf *buffer)
1966 {
1967     return put_nxmsg_xid(openflow_len, subtype, alloc_xid(), buffer);
1968 }
1969
1970 /* Similar to put_openflow_xid() but append a Nicira vendor extension message
1971  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1972 void *
1973 put_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
1974               struct ofpbuf *buffer)
1975 {
1976     struct nicira_header *nxh;
1977
1978     nxh = put_openflow_xid(openflow_len, OFPT_VENDOR, xid, buffer);
1979     nxh->vendor = htonl(NX_VENDOR_ID);
1980     nxh->subtype = htonl(subtype);
1981     return nxh;
1982 }
1983
1984 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
1985  * 'buffer->size'. */
1986 void
1987 update_openflow_length(struct ofpbuf *buffer)
1988 {
1989     struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
1990     oh->length = htons(buffer->size);
1991 }
1992
1993 static void
1994 put_stats__(ovs_be32 xid, uint8_t ofp_type,
1995             ovs_be16 ofpst_type, ovs_be32 nxst_subtype,
1996             struct ofpbuf *msg)
1997 {
1998     if (ofpst_type == htons(OFPST_VENDOR)) {
1999         struct nicira_stats_msg *nsm;
2000
2001         nsm = put_openflow_xid(sizeof *nsm, ofp_type, xid, msg);
2002         nsm->vsm.osm.type = ofpst_type;
2003         nsm->vsm.vendor = htonl(NX_VENDOR_ID);
2004         nsm->subtype = nxst_subtype;
2005     } else {
2006         struct ofp_stats_msg *osm;
2007
2008         osm = put_openflow_xid(sizeof *osm, ofp_type, xid, msg);
2009         osm->type = ofpst_type;
2010     }
2011 }
2012
2013 /* Creates a statistics request message with total length 'openflow_len'
2014  * (including all headers) and the given 'ofpst_type', and stores the buffer
2015  * containing the new message in '*bufferp'.  If 'ofpst_type' is OFPST_VENDOR
2016  * then 'nxst_subtype' is used as the Nicira vendor extension statistics
2017  * subtype (otherwise 'nxst_subtype' is ignored).
2018  *
2019  * Initializes bytes following the headers to all-bits-zero.
2020  *
2021  * Returns the first byte of the new message. */
2022 void *
2023 ofputil_make_stats_request(size_t openflow_len, uint16_t ofpst_type,
2024                            uint32_t nxst_subtype, struct ofpbuf **bufferp)
2025 {
2026     struct ofpbuf *msg;
2027
2028     msg = *bufferp = ofpbuf_new(openflow_len);
2029     put_stats__(alloc_xid(), OFPT_STATS_REQUEST,
2030                 htons(ofpst_type), htonl(nxst_subtype), msg);
2031     ofpbuf_padto(msg, openflow_len);
2032
2033     return msg->data;
2034 }
2035
2036 static void
2037 put_stats_reply__(const struct ofp_stats_msg *request, struct ofpbuf *msg)
2038 {
2039     assert(request->header.type == OFPT_STATS_REQUEST ||
2040            request->header.type == OFPT_STATS_REPLY);
2041     put_stats__(request->header.xid, OFPT_STATS_REPLY, request->type,
2042                 (request->type != htons(OFPST_VENDOR)
2043                  ? htonl(0)
2044                  : ((const struct nicira_stats_msg *) request)->subtype),
2045                 msg);
2046 }
2047
2048 /* Creates a statistics reply message with total length 'openflow_len'
2049  * (including all headers) and the same type (either a standard OpenFlow
2050  * statistics type or a Nicira extension type and subtype) as 'request', and
2051  * stores the buffer containing the new message in '*bufferp'.
2052  *
2053  * Initializes bytes following the headers to all-bits-zero.
2054  *
2055  * Returns the first byte of the new message. */
2056 void *
2057 ofputil_make_stats_reply(size_t openflow_len,
2058                          const struct ofp_stats_msg *request,
2059                          struct ofpbuf **bufferp)
2060 {
2061     struct ofpbuf *msg;
2062
2063     msg = *bufferp = ofpbuf_new(openflow_len);
2064     put_stats_reply__(request, msg);
2065     ofpbuf_padto(msg, openflow_len);
2066
2067     return msg->data;
2068 }
2069
2070 /* Initializes 'replies' as a list of ofpbufs that will contain a series of
2071  * replies to 'request', which should be an OpenFlow or Nicira extension
2072  * statistics request.  Initially 'replies' will have a single reply message
2073  * that has only a header.  The functions ofputil_reserve_stats_reply() and
2074  * ofputil_append_stats_reply() may be used to add to the reply. */
2075 void
2076 ofputil_start_stats_reply(const struct ofp_stats_msg *request,
2077                           struct list *replies)
2078 {
2079     struct ofpbuf *msg;
2080
2081     msg = ofpbuf_new(1024);
2082     put_stats_reply__(request, msg);
2083
2084     list_init(replies);
2085     list_push_back(replies, &msg->list_node);
2086 }
2087
2088 /* Prepares to append up to 'len' bytes to the series of statistics replies in
2089  * 'replies', which should have been initialized with
2090  * ofputil_start_stats_reply().  Returns an ofpbuf with at least 'len' bytes of
2091  * tailroom.  (The 'len' bytes have not actually be allocated; the caller must
2092  * do so with e.g. ofpbuf_put_uninit().) */
2093 struct ofpbuf *
2094 ofputil_reserve_stats_reply(size_t len, struct list *replies)
2095 {
2096     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
2097     struct ofp_stats_msg *osm = msg->data;
2098
2099     if (msg->size + len <= UINT16_MAX) {
2100         ofpbuf_prealloc_tailroom(msg, len);
2101     } else {
2102         osm->flags |= htons(OFPSF_REPLY_MORE);
2103
2104         msg = ofpbuf_new(MAX(1024, sizeof(struct nicira_stats_msg) + len));
2105         put_stats_reply__(osm, msg);
2106         list_push_back(replies, &msg->list_node);
2107     }
2108     return msg;
2109 }
2110
2111 /* Appends 'len' bytes to the series of statistics replies in 'replies', and
2112  * returns the first byte. */
2113 void *
2114 ofputil_append_stats_reply(size_t len, struct list *replies)
2115 {
2116     return ofpbuf_put_uninit(ofputil_reserve_stats_reply(len, replies), len);
2117 }
2118
2119 /* Returns the first byte past the ofp_stats_msg header in 'oh'. */
2120 const void *
2121 ofputil_stats_body(const struct ofp_header *oh)
2122 {
2123     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
2124     return (const struct ofp_stats_msg *) oh + 1;
2125 }
2126
2127 /* Returns the number of bytes past the ofp_stats_msg header in 'oh'. */
2128 size_t
2129 ofputil_stats_body_len(const struct ofp_header *oh)
2130 {
2131     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
2132     return ntohs(oh->length) - sizeof(struct ofp_stats_msg);
2133 }
2134
2135 /* Returns the first byte past the nicira_stats_msg header in 'oh'. */
2136 const void *
2137 ofputil_nxstats_body(const struct ofp_header *oh)
2138 {
2139     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
2140     return ((const struct nicira_stats_msg *) oh) + 1;
2141 }
2142
2143 /* Returns the number of bytes past the nicira_stats_msg header in 'oh'. */
2144 size_t
2145 ofputil_nxstats_body_len(const struct ofp_header *oh)
2146 {
2147     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
2148     return ntohs(oh->length) - sizeof(struct nicira_stats_msg);
2149 }
2150
2151 struct ofpbuf *
2152 make_flow_mod(uint16_t command, const struct cls_rule *rule,
2153               size_t actions_len)
2154 {
2155     struct ofp_flow_mod *ofm;
2156     size_t size = sizeof *ofm + actions_len;
2157     struct ofpbuf *out = ofpbuf_new(size);
2158     ofm = ofpbuf_put_zeros(out, sizeof *ofm);
2159     ofm->header.version = OFP_VERSION;
2160     ofm->header.type = OFPT_FLOW_MOD;
2161     ofm->header.length = htons(size);
2162     ofm->cookie = 0;
2163     ofm->priority = htons(MIN(rule->priority, UINT16_MAX));
2164     ofputil_cls_rule_to_match(rule, &ofm->match);
2165     ofm->command = htons(command);
2166     return out;
2167 }
2168
2169 struct ofpbuf *
2170 make_add_flow(const struct cls_rule *rule, uint32_t buffer_id,
2171               uint16_t idle_timeout, size_t actions_len)
2172 {
2173     struct ofpbuf *out = make_flow_mod(OFPFC_ADD, rule, actions_len);
2174     struct ofp_flow_mod *ofm = out->data;
2175     ofm->idle_timeout = htons(idle_timeout);
2176     ofm->hard_timeout = htons(OFP_FLOW_PERMANENT);
2177     ofm->buffer_id = htonl(buffer_id);
2178     return out;
2179 }
2180
2181 struct ofpbuf *
2182 make_del_flow(const struct cls_rule *rule)
2183 {
2184     struct ofpbuf *out = make_flow_mod(OFPFC_DELETE_STRICT, rule, 0);
2185     struct ofp_flow_mod *ofm = out->data;
2186     ofm->out_port = htons(OFPP_NONE);
2187     return out;
2188 }
2189
2190 struct ofpbuf *
2191 make_add_simple_flow(const struct cls_rule *rule,
2192                      uint32_t buffer_id, uint16_t out_port,
2193                      uint16_t idle_timeout)
2194 {
2195     if (out_port != OFPP_NONE) {
2196         struct ofp_action_output *oao;
2197         struct ofpbuf *buffer;
2198
2199         buffer = make_add_flow(rule, buffer_id, idle_timeout, sizeof *oao);
2200         ofputil_put_OFPAT_OUTPUT(buffer)->port = htons(out_port);
2201         return buffer;
2202     } else {
2203         return make_add_flow(rule, buffer_id, idle_timeout, 0);
2204     }
2205 }
2206
2207 struct ofpbuf *
2208 make_packet_in(uint32_t buffer_id, uint16_t in_port, uint8_t reason,
2209                const struct ofpbuf *payload, int max_send_len)
2210 {
2211     struct ofp_packet_in *opi;
2212     struct ofpbuf *buf;
2213     int send_len;
2214
2215     send_len = MIN(max_send_len, payload->size);
2216     buf = ofpbuf_new(sizeof *opi + send_len);
2217     opi = put_openflow_xid(offsetof(struct ofp_packet_in, data),
2218                            OFPT_PACKET_IN, 0, buf);
2219     opi->buffer_id = htonl(buffer_id);
2220     opi->total_len = htons(payload->size);
2221     opi->in_port = htons(in_port);
2222     opi->reason = reason;
2223     ofpbuf_put(buf, payload->data, send_len);
2224     update_openflow_length(buf);
2225
2226     return buf;
2227 }
2228
2229 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
2230 struct ofpbuf *
2231 make_echo_request(void)
2232 {
2233     struct ofp_header *rq;
2234     struct ofpbuf *out = ofpbuf_new(sizeof *rq);
2235     rq = ofpbuf_put_uninit(out, sizeof *rq);
2236     rq->version = OFP_VERSION;
2237     rq->type = OFPT_ECHO_REQUEST;
2238     rq->length = htons(sizeof *rq);
2239     rq->xid = htonl(0);
2240     return out;
2241 }
2242
2243 /* Creates and returns an OFPT_ECHO_REPLY message matching the
2244  * OFPT_ECHO_REQUEST message in 'rq'. */
2245 struct ofpbuf *
2246 make_echo_reply(const struct ofp_header *rq)
2247 {
2248     size_t size = ntohs(rq->length);
2249     struct ofpbuf *out = ofpbuf_new(size);
2250     struct ofp_header *reply = ofpbuf_put(out, rq, size);
2251     reply->type = OFPT_ECHO_REPLY;
2252     return out;
2253 }
2254
2255 struct ofpbuf *
2256 ofputil_encode_barrier_request(void)
2257 {
2258     struct ofpbuf *msg;
2259
2260     make_openflow(sizeof(struct ofp_header), OFPT_BARRIER_REQUEST, &msg);
2261     return msg;
2262 }
2263
2264 const char *
2265 ofputil_frag_handling_to_string(enum ofp_config_flags flags)
2266 {
2267     switch (flags & OFPC_FRAG_MASK) {
2268     case OFPC_FRAG_NORMAL:   return "normal";
2269     case OFPC_FRAG_DROP:     return "drop";
2270     case OFPC_FRAG_REASM:    return "reassemble";
2271     case OFPC_FRAG_NX_MATCH: return "nx-match";
2272     }
2273
2274     NOT_REACHED();
2275 }
2276
2277 bool
2278 ofputil_frag_handling_from_string(const char *s, enum ofp_config_flags *flags)
2279 {
2280     if (!strcasecmp(s, "normal")) {
2281         *flags = OFPC_FRAG_NORMAL;
2282     } else if (!strcasecmp(s, "drop")) {
2283         *flags = OFPC_FRAG_DROP;
2284     } else if (!strcasecmp(s, "reassemble")) {
2285         *flags = OFPC_FRAG_REASM;
2286     } else if (!strcasecmp(s, "nx-match")) {
2287         *flags = OFPC_FRAG_NX_MATCH;
2288     } else {
2289         return false;
2290     }
2291     return true;
2292 }
2293
2294 /* Checks that 'port' is a valid output port for the OFPAT_OUTPUT action, given
2295  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
2296  * 'port' is valid, otherwise an OpenFlow return code. */
2297 enum ofperr
2298 ofputil_check_output_port(uint16_t port, int max_ports)
2299 {
2300     switch (port) {
2301     case OFPP_IN_PORT:
2302     case OFPP_TABLE:
2303     case OFPP_NORMAL:
2304     case OFPP_FLOOD:
2305     case OFPP_ALL:
2306     case OFPP_CONTROLLER:
2307     case OFPP_LOCAL:
2308         return 0;
2309
2310     default:
2311         if (port < max_ports) {
2312             return 0;
2313         }
2314         return OFPERR_OFPBAC_BAD_OUT_PORT;
2315     }
2316 }
2317
2318 #define OFPUTIL_NAMED_PORTS                     \
2319         OFPUTIL_NAMED_PORT(IN_PORT)             \
2320         OFPUTIL_NAMED_PORT(TABLE)               \
2321         OFPUTIL_NAMED_PORT(NORMAL)              \
2322         OFPUTIL_NAMED_PORT(FLOOD)               \
2323         OFPUTIL_NAMED_PORT(ALL)                 \
2324         OFPUTIL_NAMED_PORT(CONTROLLER)          \
2325         OFPUTIL_NAMED_PORT(LOCAL)               \
2326         OFPUTIL_NAMED_PORT(NONE)
2327
2328 /* Checks whether 's' is the string representation of an OpenFlow port number,
2329  * either as an integer or a string name (e.g. "LOCAL").  If it is, stores the
2330  * number in '*port' and returns true.  Otherwise, returns false. */
2331 bool
2332 ofputil_port_from_string(const char *name, uint16_t *port)
2333 {
2334     struct pair {
2335         const char *name;
2336         uint16_t value;
2337     };
2338     static const struct pair pairs[] = {
2339 #define OFPUTIL_NAMED_PORT(NAME) {#NAME, OFPP_##NAME},
2340         OFPUTIL_NAMED_PORTS
2341 #undef OFPUTIL_NAMED_PORT
2342     };
2343     static const int n_pairs = ARRAY_SIZE(pairs);
2344     int i;
2345
2346     if (str_to_int(name, 0, &i) && i >= 0 && i < UINT16_MAX) {
2347         *port = i;
2348         return true;
2349     }
2350
2351     for (i = 0; i < n_pairs; i++) {
2352         if (!strcasecmp(name, pairs[i].name)) {
2353             *port = pairs[i].value;
2354             return true;
2355         }
2356     }
2357     return false;
2358 }
2359
2360 /* Appends to 's' a string representation of the OpenFlow port number 'port'.
2361  * Most ports' string representation is just the port number, but for special
2362  * ports, e.g. OFPP_LOCAL, it is the name, e.g. "LOCAL". */
2363 void
2364 ofputil_format_port(uint16_t port, struct ds *s)
2365 {
2366     const char *name;
2367
2368     switch (port) {
2369 #define OFPUTIL_NAMED_PORT(NAME) case OFPP_##NAME: name = #NAME; break;
2370         OFPUTIL_NAMED_PORTS
2371 #undef OFPUTIL_NAMED_PORT
2372
2373     default:
2374         ds_put_format(s, "%"PRIu16, port);
2375         return;
2376     }
2377     ds_put_cstr(s, name);
2378 }
2379
2380 static enum ofperr
2381 check_resubmit_table(const struct nx_action_resubmit *nar)
2382 {
2383     if (nar->pad[0] || nar->pad[1] || nar->pad[2]) {
2384         return OFPERR_OFPBAC_BAD_ARGUMENT;
2385     }
2386     return 0;
2387 }
2388
2389 static enum ofperr
2390 check_output_reg(const struct nx_action_output_reg *naor,
2391                  const struct flow *flow)
2392 {
2393     struct mf_subfield src;
2394     size_t i;
2395
2396     for (i = 0; i < sizeof naor->zero; i++) {
2397         if (naor->zero[i]) {
2398             return OFPERR_OFPBAC_BAD_ARGUMENT;
2399         }
2400     }
2401
2402     nxm_decode(&src, naor->src, naor->ofs_nbits);
2403     return mf_check_src(&src, flow);
2404 }
2405
2406 enum ofperr
2407 validate_actions(const union ofp_action *actions, size_t n_actions,
2408                  const struct flow *flow, int max_ports)
2409 {
2410     const union ofp_action *a;
2411     size_t left;
2412
2413     OFPUTIL_ACTION_FOR_EACH (a, left, actions, n_actions) {
2414         enum ofperr error;
2415         uint16_t port;
2416         int code;
2417
2418         code = ofputil_decode_action(a);
2419         if (code < 0) {
2420             error = -code;
2421             VLOG_WARN_RL(&bad_ofmsg_rl,
2422                          "action decoding error at offset %td (%s)",
2423                          (a - actions) * sizeof *a, ofperr_get_name(error));
2424
2425             return error;
2426         }
2427
2428         error = 0;
2429         switch ((enum ofputil_action_code) code) {
2430         case OFPUTIL_OFPAT_OUTPUT:
2431             error = ofputil_check_output_port(ntohs(a->output.port),
2432                                               max_ports);
2433             break;
2434
2435         case OFPUTIL_OFPAT_SET_VLAN_VID:
2436             if (a->vlan_vid.vlan_vid & ~htons(0xfff)) {
2437                 error = OFPERR_OFPBAC_BAD_ARGUMENT;
2438             }
2439             break;
2440
2441         case OFPUTIL_OFPAT_SET_VLAN_PCP:
2442             if (a->vlan_pcp.vlan_pcp & ~7) {
2443                 error = OFPERR_OFPBAC_BAD_ARGUMENT;
2444             }
2445             break;
2446
2447         case OFPUTIL_OFPAT_ENQUEUE:
2448             port = ntohs(((const struct ofp_action_enqueue *) a)->port);
2449             if (port >= max_ports && port != OFPP_IN_PORT
2450                 && port != OFPP_LOCAL) {
2451                 error = OFPERR_OFPBAC_BAD_OUT_PORT;
2452             }
2453             break;
2454
2455         case OFPUTIL_NXAST_REG_MOVE:
2456             error = nxm_check_reg_move((const struct nx_action_reg_move *) a,
2457                                        flow);
2458             break;
2459
2460         case OFPUTIL_NXAST_REG_LOAD:
2461             error = nxm_check_reg_load((const struct nx_action_reg_load *) a,
2462                                        flow);
2463             break;
2464
2465         case OFPUTIL_NXAST_MULTIPATH:
2466             error = multipath_check((const struct nx_action_multipath *) a,
2467                                     flow);
2468             break;
2469
2470         case OFPUTIL_NXAST_AUTOPATH:
2471             error = autopath_check((const struct nx_action_autopath *) a,
2472                                    flow);
2473             break;
2474
2475         case OFPUTIL_NXAST_BUNDLE:
2476         case OFPUTIL_NXAST_BUNDLE_LOAD:
2477             error = bundle_check((const struct nx_action_bundle *) a,
2478                                  max_ports, flow);
2479             break;
2480
2481         case OFPUTIL_NXAST_OUTPUT_REG:
2482             error = check_output_reg((const struct nx_action_output_reg *) a,
2483                                      flow);
2484             break;
2485
2486         case OFPUTIL_NXAST_RESUBMIT_TABLE:
2487             error = check_resubmit_table(
2488                 (const struct nx_action_resubmit *) a);
2489             break;
2490
2491         case OFPUTIL_NXAST_LEARN:
2492             error = learn_check((const struct nx_action_learn *) a, flow);
2493             break;
2494
2495         case OFPUTIL_OFPAT_STRIP_VLAN:
2496         case OFPUTIL_OFPAT_SET_NW_SRC:
2497         case OFPUTIL_OFPAT_SET_NW_DST:
2498         case OFPUTIL_OFPAT_SET_NW_TOS:
2499         case OFPUTIL_OFPAT_SET_TP_SRC:
2500         case OFPUTIL_OFPAT_SET_TP_DST:
2501         case OFPUTIL_OFPAT_SET_DL_SRC:
2502         case OFPUTIL_OFPAT_SET_DL_DST:
2503         case OFPUTIL_NXAST_RESUBMIT:
2504         case OFPUTIL_NXAST_SET_TUNNEL:
2505         case OFPUTIL_NXAST_SET_QUEUE:
2506         case OFPUTIL_NXAST_POP_QUEUE:
2507         case OFPUTIL_NXAST_NOTE:
2508         case OFPUTIL_NXAST_SET_TUNNEL64:
2509         case OFPUTIL_NXAST_EXIT:
2510         case OFPUTIL_NXAST_DEC_TTL:
2511             break;
2512         }
2513
2514         if (error) {
2515             VLOG_WARN_RL(&bad_ofmsg_rl, "bad action at offset %td (%s)",
2516                          (a - actions) * sizeof *a, ofperr_get_name(error));
2517             return error;
2518         }
2519     }
2520     if (left) {
2521         VLOG_WARN_RL(&bad_ofmsg_rl, "bad action format at offset %zu",
2522                      (n_actions - left) * sizeof *a);
2523         return OFPERR_OFPBAC_BAD_LEN;
2524     }
2525     return 0;
2526 }
2527
2528 struct ofputil_action {
2529     int code;
2530     unsigned int min_len;
2531     unsigned int max_len;
2532 };
2533
2534 static const struct ofputil_action action_bad_type
2535     = { -OFPERR_OFPBAC_BAD_TYPE,   0, UINT_MAX };
2536 static const struct ofputil_action action_bad_len
2537     = { -OFPERR_OFPBAC_BAD_LEN,    0, UINT_MAX };
2538 static const struct ofputil_action action_bad_vendor
2539     = { -OFPERR_OFPBAC_BAD_VENDOR, 0, UINT_MAX };
2540
2541 static const struct ofputil_action *
2542 ofputil_decode_ofpat_action(const union ofp_action *a)
2543 {
2544     enum ofp_action_type type = ntohs(a->type);
2545
2546     switch (type) {
2547 #define OFPAT_ACTION(ENUM, STRUCT, NAME)                    \
2548         case ENUM: {                                        \
2549             static const struct ofputil_action action = {   \
2550                 OFPUTIL_##ENUM,                             \
2551                 sizeof(struct STRUCT),                      \
2552                 sizeof(struct STRUCT)                       \
2553             };                                              \
2554             return &action;                                 \
2555         }
2556 #include "ofp-util.def"
2557
2558     case OFPAT_VENDOR:
2559     default:
2560         return &action_bad_type;
2561     }
2562 }
2563
2564 static const struct ofputil_action *
2565 ofputil_decode_nxast_action(const union ofp_action *a)
2566 {
2567     const struct nx_action_header *nah = (const struct nx_action_header *) a;
2568     enum nx_action_subtype subtype = ntohs(nah->subtype);
2569
2570     switch (subtype) {
2571 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)            \
2572         case ENUM: {                                            \
2573             static const struct ofputil_action action = {       \
2574                 OFPUTIL_##ENUM,                                 \
2575                 sizeof(struct STRUCT),                          \
2576                 EXTENSIBLE ? UINT_MAX : sizeof(struct STRUCT)   \
2577             };                                                  \
2578             return &action;                                     \
2579         }
2580 #include "ofp-util.def"
2581
2582     case NXAST_SNAT__OBSOLETE:
2583     case NXAST_DROP_SPOOFED_ARP__OBSOLETE:
2584     default:
2585         return &action_bad_type;
2586     }
2587 }
2588
2589 /* Parses 'a' to determine its type.  Returns a nonnegative OFPUTIL_OFPAT_* or
2590  * OFPUTIL_NXAST_* constant if successful, otherwise a negative OFPERR_* error
2591  * code.
2592  *
2593  * The caller must have already verified that 'a''s length is correct (that is,
2594  * a->header.len is nonzero and a multiple of sizeof(union ofp_action) and no
2595  * longer than the amount of space allocated to 'a').
2596  *
2597  * This function verifies that 'a''s length is correct for the type of action
2598  * that it represents. */
2599 int
2600 ofputil_decode_action(const union ofp_action *a)
2601 {
2602     const struct ofputil_action *action;
2603     uint16_t len = ntohs(a->header.len);
2604
2605     if (a->type != htons(OFPAT_VENDOR)) {
2606         action = ofputil_decode_ofpat_action(a);
2607     } else {
2608         switch (ntohl(a->vendor.vendor)) {
2609         case NX_VENDOR_ID:
2610             if (len < sizeof(struct nx_action_header)) {
2611                 return -OFPERR_OFPBAC_BAD_LEN;
2612             }
2613             action = ofputil_decode_nxast_action(a);
2614             break;
2615         default:
2616             action = &action_bad_vendor;
2617             break;
2618         }
2619     }
2620
2621     return (len >= action->min_len && len <= action->max_len
2622             ? action->code
2623             : -OFPERR_OFPBAC_BAD_LEN);
2624 }
2625
2626 /* Parses 'a' and returns its type as an OFPUTIL_OFPAT_* or OFPUTIL_NXAST_*
2627  * constant.  The caller must have already validated that 'a' is a valid action
2628  * understood by Open vSwitch (e.g. by a previous successful call to
2629  * ofputil_decode_action()). */
2630 enum ofputil_action_code
2631 ofputil_decode_action_unsafe(const union ofp_action *a)
2632 {
2633     const struct ofputil_action *action;
2634
2635     if (a->type != htons(OFPAT_VENDOR)) {
2636         action = ofputil_decode_ofpat_action(a);
2637     } else {
2638         action = ofputil_decode_nxast_action(a);
2639     }
2640
2641     return action->code;
2642 }
2643
2644 /* Returns the 'enum ofputil_action_code' corresponding to 'name' (e.g. if
2645  * 'name' is "output" then the return value is OFPUTIL_OFPAT_OUTPUT), or -1 if
2646  * 'name' is not the name of any action.
2647  *
2648  * ofp-util.def lists the mapping from names to action. */
2649 int
2650 ofputil_action_code_from_name(const char *name)
2651 {
2652     static const char *names[OFPUTIL_N_ACTIONS] = {
2653 #define OFPAT_ACTION(ENUM, STRUCT, NAME)             NAME,
2654 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) NAME,
2655 #include "ofp-util.def"
2656     };
2657
2658     const char **p;
2659
2660     for (p = names; p < &names[ARRAY_SIZE(names)]; p++) {
2661         if (*p && !strcasecmp(name, *p)) {
2662             return p - names;
2663         }
2664     }
2665     return -1;
2666 }
2667
2668 /* Appends an action of the type specified by 'code' to 'buf' and returns the
2669  * action.  Initializes the parts of 'action' that identify it as having type
2670  * <ENUM> and length 'sizeof *action' and zeros the rest.  For actions that
2671  * have variable length, the length used and cleared is that of struct
2672  * <STRUCT>.  */
2673 void *
2674 ofputil_put_action(enum ofputil_action_code code, struct ofpbuf *buf)
2675 {
2676     switch (code) {
2677 #define OFPAT_ACTION(ENUM, STRUCT, NAME)                    \
2678     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
2679 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)        \
2680     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
2681 #include "ofp-util.def"
2682     }
2683     NOT_REACHED();
2684 }
2685
2686 #define OFPAT_ACTION(ENUM, STRUCT, NAME)                        \
2687     void                                                        \
2688     ofputil_init_##ENUM(struct STRUCT *s)                       \
2689     {                                                           \
2690         memset(s, 0, sizeof *s);                                \
2691         s->type = htons(ENUM);                                  \
2692         s->len = htons(sizeof *s);                              \
2693     }                                                           \
2694                                                                 \
2695     struct STRUCT *                                             \
2696     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
2697     {                                                           \
2698         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
2699         ofputil_init_##ENUM(s);                                 \
2700         return s;                                               \
2701     }
2702 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)            \
2703     void                                                        \
2704     ofputil_init_##ENUM(struct STRUCT *s)                       \
2705     {                                                           \
2706         memset(s, 0, sizeof *s);                                \
2707         s->type = htons(OFPAT_VENDOR);                          \
2708         s->len = htons(sizeof *s);                              \
2709         s->vendor = htonl(NX_VENDOR_ID);                        \
2710         s->subtype = htons(ENUM);                               \
2711     }                                                           \
2712                                                                 \
2713     struct STRUCT *                                             \
2714     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
2715     {                                                           \
2716         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
2717         ofputil_init_##ENUM(s);                                 \
2718         return s;                                               \
2719     }
2720 #include "ofp-util.def"
2721
2722 /* Returns true if 'action' outputs to 'port', false otherwise. */
2723 bool
2724 action_outputs_to_port(const union ofp_action *action, ovs_be16 port)
2725 {
2726     switch (ntohs(action->type)) {
2727     case OFPAT_OUTPUT:
2728         return action->output.port == port;
2729     case OFPAT_ENQUEUE:
2730         return ((const struct ofp_action_enqueue *) action)->port == port;
2731     default:
2732         return false;
2733     }
2734 }
2735
2736 /* "Normalizes" the wildcards in 'rule'.  That means:
2737  *
2738  *    1. If the type of level N is known, then only the valid fields for that
2739  *       level may be specified.  For example, ARP does not have a TOS field,
2740  *       so nw_tos must be wildcarded if 'rule' specifies an ARP flow.
2741  *       Similarly, IPv4 does not have any IPv6 addresses, so ipv6_src and
2742  *       ipv6_dst (and other fields) must be wildcarded if 'rule' specifies an
2743  *       IPv4 flow.
2744  *
2745  *    2. If the type of level N is not known (or not understood by Open
2746  *       vSwitch), then no fields at all for that level may be specified.  For
2747  *       example, Open vSwitch does not understand SCTP, an L4 protocol, so the
2748  *       L4 fields tp_src and tp_dst must be wildcarded if 'rule' specifies an
2749  *       SCTP flow.
2750  *
2751  * 'flow_format' specifies the format of the flow as received or as intended to
2752  * be sent.  This is important for IPv6 and ARP, for which NXM supports more
2753  * detailed matching. */
2754 void
2755 ofputil_normalize_rule(struct cls_rule *rule, enum nx_flow_format flow_format)
2756 {
2757     enum {
2758         MAY_NW_ADDR     = 1 << 0, /* nw_src, nw_dst */
2759         MAY_TP_ADDR     = 1 << 1, /* tp_src, tp_dst */
2760         MAY_NW_PROTO    = 1 << 2, /* nw_proto */
2761         MAY_IPVx        = 1 << 3, /* tos, frag, ttl */
2762         MAY_ARP_SHA     = 1 << 4, /* arp_sha */
2763         MAY_ARP_THA     = 1 << 5, /* arp_tha */
2764         MAY_IPV6        = 1 << 6, /* ipv6_src, ipv6_dst, ipv6_label */
2765         MAY_ND_TARGET   = 1 << 7  /* nd_target */
2766     } may_match;
2767
2768     struct flow_wildcards wc;
2769
2770     /* Figure out what fields may be matched. */
2771     if (rule->flow.dl_type == htons(ETH_TYPE_IP)) {
2772         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_NW_ADDR;
2773         if (rule->flow.nw_proto == IPPROTO_TCP ||
2774             rule->flow.nw_proto == IPPROTO_UDP ||
2775             rule->flow.nw_proto == IPPROTO_ICMP) {
2776             may_match |= MAY_TP_ADDR;
2777         }
2778     } else if (rule->flow.dl_type == htons(ETH_TYPE_IPV6)
2779                && flow_format == NXFF_NXM) {
2780         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_IPV6;
2781         if (rule->flow.nw_proto == IPPROTO_TCP ||
2782             rule->flow.nw_proto == IPPROTO_UDP) {
2783             may_match |= MAY_TP_ADDR;
2784         } else if (rule->flow.nw_proto == IPPROTO_ICMPV6) {
2785             may_match |= MAY_TP_ADDR;
2786             if (rule->flow.tp_src == htons(ND_NEIGHBOR_SOLICIT)) {
2787                 may_match |= MAY_ND_TARGET | MAY_ARP_SHA;
2788             } else if (rule->flow.tp_src == htons(ND_NEIGHBOR_ADVERT)) {
2789                 may_match |= MAY_ND_TARGET | MAY_ARP_THA;
2790             }
2791         }
2792     } else if (rule->flow.dl_type == htons(ETH_TYPE_ARP)) {
2793         may_match = MAY_NW_PROTO | MAY_NW_ADDR;
2794         if (flow_format == NXFF_NXM) {
2795             may_match |= MAY_ARP_SHA | MAY_ARP_THA;
2796         }
2797     } else {
2798         may_match = 0;
2799     }
2800
2801     /* Clear the fields that may not be matched. */
2802     wc = rule->wc;
2803     if (!(may_match & MAY_NW_ADDR)) {
2804         wc.nw_src_mask = wc.nw_dst_mask = htonl(0);
2805     }
2806     if (!(may_match & MAY_TP_ADDR)) {
2807         wc.tp_src_mask = wc.tp_dst_mask = htons(0);
2808     }
2809     if (!(may_match & MAY_NW_PROTO)) {
2810         wc.wildcards |= FWW_NW_PROTO;
2811     }
2812     if (!(may_match & MAY_IPVx)) {
2813         wc.wildcards |= FWW_NW_DSCP;
2814         wc.wildcards |= FWW_NW_ECN;
2815         wc.wildcards |= FWW_NW_TTL;
2816     }
2817     if (!(may_match & MAY_ARP_SHA)) {
2818         wc.wildcards |= FWW_ARP_SHA;
2819     }
2820     if (!(may_match & MAY_ARP_THA)) {
2821         wc.wildcards |= FWW_ARP_THA;
2822     }
2823     if (!(may_match & MAY_IPV6)) {
2824         wc.ipv6_src_mask = wc.ipv6_dst_mask = in6addr_any;
2825         wc.wildcards |= FWW_IPV6_LABEL;
2826     }
2827     if (!(may_match & MAY_ND_TARGET)) {
2828         wc.wildcards |= FWW_ND_TARGET;
2829     }
2830
2831     /* Log any changes. */
2832     if (!flow_wildcards_equal(&wc, &rule->wc)) {
2833         bool log = !VLOG_DROP_INFO(&bad_ofmsg_rl);
2834         char *pre = log ? cls_rule_to_string(rule) : NULL;
2835
2836         rule->wc = wc;
2837         cls_rule_zero_wildcarded_fields(rule);
2838
2839         if (log) {
2840             char *post = cls_rule_to_string(rule);
2841             VLOG_INFO("normalization changed ofp_match, details:");
2842             VLOG_INFO(" pre: %s", pre);
2843             VLOG_INFO("post: %s", post);
2844             free(pre);
2845             free(post);
2846         }
2847     }
2848 }
2849
2850 /* Attempts to pull 'actions_len' bytes from the front of 'b'.  Returns 0 if
2851  * successful, otherwise an OpenFlow error.
2852  *
2853  * If successful, the first action is stored in '*actionsp' and the number of
2854  * "union ofp_action" size elements into '*n_actionsp'.  Otherwise NULL and 0
2855  * are stored, respectively.
2856  *
2857  * This function does not check that the actions are valid (the caller should
2858  * do so, with validate_actions()).  The caller is also responsible for making
2859  * sure that 'b->data' is initially aligned appropriately for "union
2860  * ofp_action". */
2861 enum ofperr
2862 ofputil_pull_actions(struct ofpbuf *b, unsigned int actions_len,
2863                      union ofp_action **actionsp, size_t *n_actionsp)
2864 {
2865     if (actions_len % OFP_ACTION_ALIGN != 0) {
2866         VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
2867                      "is not a multiple of %d", actions_len, OFP_ACTION_ALIGN);
2868         goto error;
2869     }
2870
2871     *actionsp = ofpbuf_try_pull(b, actions_len);
2872     if (*actionsp == NULL) {
2873         VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
2874                      "exceeds remaining message length (%zu)",
2875                      actions_len, b->size);
2876         goto error;
2877     }
2878
2879     *n_actionsp = actions_len / OFP_ACTION_ALIGN;
2880     return 0;
2881
2882 error:
2883     *actionsp = NULL;
2884     *n_actionsp = 0;
2885     return OFPERR_OFPBRC_BAD_LEN;
2886 }
2887
2888 bool
2889 ofputil_actions_equal(const union ofp_action *a, size_t n_a,
2890                       const union ofp_action *b, size_t n_b)
2891 {
2892     return n_a == n_b && (!n_a || !memcmp(a, b, n_a * sizeof *a));
2893 }
2894
2895 union ofp_action *
2896 ofputil_actions_clone(const union ofp_action *actions, size_t n)
2897 {
2898     return n ? xmemdup(actions, n * sizeof *actions) : NULL;
2899 }
2900
2901 /* Parses a key or a key-value pair from '*stringp'.
2902  *
2903  * On success: Stores the key into '*keyp'.  Stores the value, if present, into
2904  * '*valuep', otherwise an empty string.  Advances '*stringp' past the end of
2905  * the key-value pair, preparing it for another call.  '*keyp' and '*valuep'
2906  * are substrings of '*stringp' created by replacing some of its bytes by null
2907  * terminators.  Returns true.
2908  *
2909  * If '*stringp' is just white space or commas, sets '*keyp' and '*valuep' to
2910  * NULL and returns false. */
2911 bool
2912 ofputil_parse_key_value(char **stringp, char **keyp, char **valuep)
2913 {
2914     char *pos, *key, *value;
2915     size_t key_len;
2916
2917     pos = *stringp;
2918     pos += strspn(pos, ", \t\r\n");
2919     if (*pos == '\0') {
2920         *keyp = *valuep = NULL;
2921         return false;
2922     }
2923
2924     key = pos;
2925     key_len = strcspn(pos, ":=(, \t\r\n");
2926     if (key[key_len] == ':' || key[key_len] == '=') {
2927         /* The value can be separated by a colon. */
2928         size_t value_len;
2929
2930         value = key + key_len + 1;
2931         value_len = strcspn(value, ", \t\r\n");
2932         pos = value + value_len + (value[value_len] != '\0');
2933         value[value_len] = '\0';
2934     } else if (key[key_len] == '(') {
2935         /* The value can be surrounded by balanced parentheses.  The outermost
2936          * set of parentheses is removed. */
2937         int level = 1;
2938         size_t value_len;
2939
2940         value = key + key_len + 1;
2941         for (value_len = 0; level > 0; value_len++) {
2942             switch (value[value_len]) {
2943             case '\0':
2944                 ovs_fatal(0, "unbalanced parentheses in argument to %s", key);
2945
2946             case '(':
2947                 level++;
2948                 break;
2949
2950             case ')':
2951                 level--;
2952                 break;
2953             }
2954         }
2955         value[value_len - 1] = '\0';
2956         pos = value + value_len;
2957     } else {
2958         /* There might be no value at all. */
2959         value = key + key_len;  /* Will become the empty string below. */
2960         pos = key + key_len + (key[key_len] != '\0');
2961     }
2962     key[key_len] = '\0';
2963
2964     *stringp = pos;
2965     *keyp = key;
2966     *valuep = value;
2967     return true;
2968 }