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