Add information about time left before timeouts to flow dumps.
[cascardo/ovs.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 /* Returns a string representing the message type of 'type'.  The string is the
1784  * enumeration constant for the type, e.g. "OFPT_HELLO".  For statistics
1785  * messages, the constant is followed by "request" or "reply",
1786  * e.g. "OFPST_AGGREGATE reply". */
1787 const char *
1788 ofputil_msg_type_name(const struct ofputil_msg_type *type)
1789 {
1790     return type->name;
1791 }
1792 \f
1793 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
1794  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
1795  * an arbitrary transaction id.  Allocated bytes beyond the header, if any, are
1796  * zeroed.
1797  *
1798  * The caller is responsible for freeing '*bufferp' when it is no longer
1799  * needed.
1800  *
1801  * The OpenFlow header length is initially set to 'openflow_len'; if the
1802  * message is later extended, the length should be updated with
1803  * update_openflow_length() before sending.
1804  *
1805  * Returns the header. */
1806 void *
1807 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp)
1808 {
1809     *bufferp = ofpbuf_new(openflow_len);
1810     return put_openflow_xid(openflow_len, type, alloc_xid(), *bufferp);
1811 }
1812
1813 /* Similar to make_openflow() but creates a Nicira vendor extension message
1814  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1815 void *
1816 make_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf **bufferp)
1817 {
1818     return make_nxmsg_xid(openflow_len, subtype, alloc_xid(), bufferp);
1819 }
1820
1821 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
1822  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
1823  * transaction id 'xid'.  Allocated bytes beyond the header, if any, are
1824  * zeroed.
1825  *
1826  * The caller is responsible for freeing '*bufferp' when it is no longer
1827  * needed.
1828  *
1829  * The OpenFlow header length is initially set to 'openflow_len'; if the
1830  * message is later extended, the length should be updated with
1831  * update_openflow_length() before sending.
1832  *
1833  * Returns the header. */
1834 void *
1835 make_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
1836                   struct ofpbuf **bufferp)
1837 {
1838     *bufferp = ofpbuf_new(openflow_len);
1839     return put_openflow_xid(openflow_len, type, xid, *bufferp);
1840 }
1841
1842 /* Similar to make_openflow_xid() but creates a Nicira vendor extension message
1843  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1844 void *
1845 make_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
1846                struct ofpbuf **bufferp)
1847 {
1848     *bufferp = ofpbuf_new(openflow_len);
1849     return put_nxmsg_xid(openflow_len, subtype, xid, *bufferp);
1850 }
1851
1852 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
1853  * with the given 'type' and an arbitrary transaction id.  Allocated bytes
1854  * beyond the header, if any, are zeroed.
1855  *
1856  * The OpenFlow header length is initially set to 'openflow_len'; if the
1857  * message is later extended, the length should be updated with
1858  * update_openflow_length() before sending.
1859  *
1860  * Returns the header. */
1861 void *
1862 put_openflow(size_t openflow_len, uint8_t type, struct ofpbuf *buffer)
1863 {
1864     return put_openflow_xid(openflow_len, type, alloc_xid(), buffer);
1865 }
1866
1867 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
1868  * with the given 'type' and an transaction id 'xid'.  Allocated bytes beyond
1869  * the header, if any, are zeroed.
1870  *
1871  * The OpenFlow header length is initially set to 'openflow_len'; if the
1872  * message is later extended, the length should be updated with
1873  * update_openflow_length() before sending.
1874  *
1875  * Returns the header. */
1876 void *
1877 put_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
1878                  struct ofpbuf *buffer)
1879 {
1880     struct ofp_header *oh;
1881
1882     assert(openflow_len >= sizeof *oh);
1883     assert(openflow_len <= UINT16_MAX);
1884
1885     oh = ofpbuf_put_uninit(buffer, openflow_len);
1886     oh->version = OFP_VERSION;
1887     oh->type = type;
1888     oh->length = htons(openflow_len);
1889     oh->xid = xid;
1890     memset(oh + 1, 0, openflow_len - sizeof *oh);
1891     return oh;
1892 }
1893
1894 /* Similar to put_openflow() but append a Nicira vendor extension message with
1895  * the specific 'subtype'.  'subtype' should be in host byte order. */
1896 void *
1897 put_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf *buffer)
1898 {
1899     return put_nxmsg_xid(openflow_len, subtype, alloc_xid(), buffer);
1900 }
1901
1902 /* Similar to put_openflow_xid() but append a Nicira vendor extension message
1903  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1904 void *
1905 put_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
1906               struct ofpbuf *buffer)
1907 {
1908     struct nicira_header *nxh;
1909
1910     nxh = put_openflow_xid(openflow_len, OFPT_VENDOR, xid, buffer);
1911     nxh->vendor = htonl(NX_VENDOR_ID);
1912     nxh->subtype = htonl(subtype);
1913     return nxh;
1914 }
1915
1916 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
1917  * 'buffer->size'. */
1918 void
1919 update_openflow_length(struct ofpbuf *buffer)
1920 {
1921     struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
1922     oh->length = htons(buffer->size);
1923 }
1924
1925 static void
1926 put_stats__(ovs_be32 xid, uint8_t ofp_type,
1927             ovs_be16 ofpst_type, ovs_be32 nxst_subtype,
1928             struct ofpbuf *msg)
1929 {
1930     if (ofpst_type == htons(OFPST_VENDOR)) {
1931         struct nicira_stats_msg *nsm;
1932
1933         nsm = put_openflow_xid(sizeof *nsm, ofp_type, xid, msg);
1934         nsm->vsm.osm.type = ofpst_type;
1935         nsm->vsm.vendor = htonl(NX_VENDOR_ID);
1936         nsm->subtype = nxst_subtype;
1937     } else {
1938         struct ofp_stats_msg *osm;
1939
1940         osm = put_openflow_xid(sizeof *osm, ofp_type, xid, msg);
1941         osm->type = ofpst_type;
1942     }
1943 }
1944
1945 /* Creates a statistics request message with total length 'openflow_len'
1946  * (including all headers) and the given 'ofpst_type', and stores the buffer
1947  * containing the new message in '*bufferp'.  If 'ofpst_type' is OFPST_VENDOR
1948  * then 'nxst_subtype' is used as the Nicira vendor extension statistics
1949  * subtype (otherwise 'nxst_subtype' is ignored).
1950  *
1951  * Initializes bytes following the headers to all-bits-zero.
1952  *
1953  * Returns the first byte of the new message. */
1954 void *
1955 ofputil_make_stats_request(size_t openflow_len, uint16_t ofpst_type,
1956                            uint32_t nxst_subtype, struct ofpbuf **bufferp)
1957 {
1958     struct ofpbuf *msg;
1959
1960     msg = *bufferp = ofpbuf_new(openflow_len);
1961     put_stats__(alloc_xid(), OFPT_STATS_REQUEST,
1962                 htons(ofpst_type), htonl(nxst_subtype), msg);
1963     ofpbuf_padto(msg, openflow_len);
1964
1965     return msg->data;
1966 }
1967
1968 static void
1969 put_stats_reply__(const struct ofp_stats_msg *request, struct ofpbuf *msg)
1970 {
1971     assert(request->header.type == OFPT_STATS_REQUEST ||
1972            request->header.type == OFPT_STATS_REPLY);
1973     put_stats__(request->header.xid, OFPT_STATS_REPLY, request->type,
1974                 (request->type != htons(OFPST_VENDOR)
1975                  ? htonl(0)
1976                  : ((const struct nicira_stats_msg *) request)->subtype),
1977                 msg);
1978 }
1979
1980 /* Creates a statistics reply message with total length 'openflow_len'
1981  * (including all headers) and the same type (either a standard OpenFlow
1982  * statistics type or a Nicira extension type and subtype) as 'request', and
1983  * stores the buffer containing the new message in '*bufferp'.
1984  *
1985  * Initializes bytes following the headers to all-bits-zero.
1986  *
1987  * Returns the first byte of the new message. */
1988 void *
1989 ofputil_make_stats_reply(size_t openflow_len,
1990                          const struct ofp_stats_msg *request,
1991                          struct ofpbuf **bufferp)
1992 {
1993     struct ofpbuf *msg;
1994
1995     msg = *bufferp = ofpbuf_new(openflow_len);
1996     put_stats_reply__(request, msg);
1997     ofpbuf_padto(msg, openflow_len);
1998
1999     return msg->data;
2000 }
2001
2002 /* Initializes 'replies' as a list of ofpbufs that will contain a series of
2003  * replies to 'request', which should be an OpenFlow or Nicira extension
2004  * statistics request.  Initially 'replies' will have a single reply message
2005  * that has only a header.  The functions ofputil_reserve_stats_reply() and
2006  * ofputil_append_stats_reply() may be used to add to the reply. */
2007 void
2008 ofputil_start_stats_reply(const struct ofp_stats_msg *request,
2009                           struct list *replies)
2010 {
2011     struct ofpbuf *msg;
2012
2013     msg = ofpbuf_new(1024);
2014     put_stats_reply__(request, msg);
2015
2016     list_init(replies);
2017     list_push_back(replies, &msg->list_node);
2018 }
2019
2020 /* Prepares to append up to 'len' bytes to the series of statistics replies in
2021  * 'replies', which should have been initialized with
2022  * ofputil_start_stats_reply().  Returns an ofpbuf with at least 'len' bytes of
2023  * tailroom.  (The 'len' bytes have not actually be allocated; the caller must
2024  * do so with e.g. ofpbuf_put_uninit().) */
2025 struct ofpbuf *
2026 ofputil_reserve_stats_reply(size_t len, struct list *replies)
2027 {
2028     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
2029     struct ofp_stats_msg *osm = msg->data;
2030
2031     if (msg->size + len <= UINT16_MAX) {
2032         ofpbuf_prealloc_tailroom(msg, len);
2033     } else {
2034         osm->flags |= htons(OFPSF_REPLY_MORE);
2035
2036         msg = ofpbuf_new(MAX(1024, sizeof(struct nicira_stats_msg) + len));
2037         put_stats_reply__(osm, msg);
2038         list_push_back(replies, &msg->list_node);
2039     }
2040     return msg;
2041 }
2042
2043 /* Appends 'len' bytes to the series of statistics replies in 'replies', and
2044  * returns the first byte. */
2045 void *
2046 ofputil_append_stats_reply(size_t len, struct list *replies)
2047 {
2048     return ofpbuf_put_uninit(ofputil_reserve_stats_reply(len, replies), len);
2049 }
2050
2051 /* Returns the first byte past the ofp_stats_msg header in 'oh'. */
2052 const void *
2053 ofputil_stats_body(const struct ofp_header *oh)
2054 {
2055     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
2056     return (const struct ofp_stats_msg *) oh + 1;
2057 }
2058
2059 /* Returns the number of bytes past the ofp_stats_msg header in 'oh'. */
2060 size_t
2061 ofputil_stats_body_len(const struct ofp_header *oh)
2062 {
2063     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
2064     return ntohs(oh->length) - sizeof(struct ofp_stats_msg);
2065 }
2066
2067 /* Returns the first byte past the nicira_stats_msg header in 'oh'. */
2068 const void *
2069 ofputil_nxstats_body(const struct ofp_header *oh)
2070 {
2071     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
2072     return ((const struct nicira_stats_msg *) oh) + 1;
2073 }
2074
2075 /* Returns the number of bytes past the nicira_stats_msg header in 'oh'. */
2076 size_t
2077 ofputil_nxstats_body_len(const struct ofp_header *oh)
2078 {
2079     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
2080     return ntohs(oh->length) - sizeof(struct nicira_stats_msg);
2081 }
2082
2083 struct ofpbuf *
2084 make_flow_mod(uint16_t command, const struct cls_rule *rule,
2085               size_t actions_len)
2086 {
2087     struct ofp_flow_mod *ofm;
2088     size_t size = sizeof *ofm + actions_len;
2089     struct ofpbuf *out = ofpbuf_new(size);
2090     ofm = ofpbuf_put_zeros(out, sizeof *ofm);
2091     ofm->header.version = OFP_VERSION;
2092     ofm->header.type = OFPT_FLOW_MOD;
2093     ofm->header.length = htons(size);
2094     ofm->cookie = 0;
2095     ofm->priority = htons(MIN(rule->priority, UINT16_MAX));
2096     ofputil_cls_rule_to_match(rule, &ofm->match);
2097     ofm->command = htons(command);
2098     return out;
2099 }
2100
2101 struct ofpbuf *
2102 make_add_flow(const struct cls_rule *rule, uint32_t buffer_id,
2103               uint16_t idle_timeout, size_t actions_len)
2104 {
2105     struct ofpbuf *out = make_flow_mod(OFPFC_ADD, rule, actions_len);
2106     struct ofp_flow_mod *ofm = out->data;
2107     ofm->idle_timeout = htons(idle_timeout);
2108     ofm->hard_timeout = htons(OFP_FLOW_PERMANENT);
2109     ofm->buffer_id = htonl(buffer_id);
2110     return out;
2111 }
2112
2113 struct ofpbuf *
2114 make_del_flow(const struct cls_rule *rule)
2115 {
2116     struct ofpbuf *out = make_flow_mod(OFPFC_DELETE_STRICT, rule, 0);
2117     struct ofp_flow_mod *ofm = out->data;
2118     ofm->out_port = htons(OFPP_NONE);
2119     return out;
2120 }
2121
2122 struct ofpbuf *
2123 make_add_simple_flow(const struct cls_rule *rule,
2124                      uint32_t buffer_id, uint16_t out_port,
2125                      uint16_t idle_timeout)
2126 {
2127     if (out_port != OFPP_NONE) {
2128         struct ofp_action_output *oao;
2129         struct ofpbuf *buffer;
2130
2131         buffer = make_add_flow(rule, buffer_id, idle_timeout, sizeof *oao);
2132         ofputil_put_OFPAT_OUTPUT(buffer)->port = htons(out_port);
2133         return buffer;
2134     } else {
2135         return make_add_flow(rule, buffer_id, idle_timeout, 0);
2136     }
2137 }
2138
2139 struct ofpbuf *
2140 make_packet_in(uint32_t buffer_id, uint16_t in_port, uint8_t reason,
2141                const struct ofpbuf *payload, int max_send_len)
2142 {
2143     struct ofp_packet_in *opi;
2144     struct ofpbuf *buf;
2145     int send_len;
2146
2147     send_len = MIN(max_send_len, payload->size);
2148     buf = ofpbuf_new(sizeof *opi + send_len);
2149     opi = put_openflow_xid(offsetof(struct ofp_packet_in, data),
2150                            OFPT_PACKET_IN, 0, buf);
2151     opi->buffer_id = htonl(buffer_id);
2152     opi->total_len = htons(payload->size);
2153     opi->in_port = htons(in_port);
2154     opi->reason = reason;
2155     ofpbuf_put(buf, payload->data, send_len);
2156     update_openflow_length(buf);
2157
2158     return buf;
2159 }
2160
2161 struct ofpbuf *
2162 make_packet_out(const struct ofpbuf *packet, uint32_t buffer_id,
2163                 uint16_t in_port,
2164                 const struct ofp_action_header *actions, size_t n_actions)
2165 {
2166     size_t actions_len = n_actions * sizeof *actions;
2167     struct ofp_packet_out *opo;
2168     size_t size = sizeof *opo + actions_len + (packet ? packet->size : 0);
2169     struct ofpbuf *out = ofpbuf_new(size);
2170
2171     opo = ofpbuf_put_uninit(out, sizeof *opo);
2172     opo->header.version = OFP_VERSION;
2173     opo->header.type = OFPT_PACKET_OUT;
2174     opo->header.length = htons(size);
2175     opo->header.xid = htonl(0);
2176     opo->buffer_id = htonl(buffer_id);
2177     opo->in_port = htons(in_port);
2178     opo->actions_len = htons(actions_len);
2179     ofpbuf_put(out, actions, actions_len);
2180     if (packet) {
2181         ofpbuf_put(out, packet->data, packet->size);
2182     }
2183     return out;
2184 }
2185
2186 struct ofpbuf *
2187 make_unbuffered_packet_out(const struct ofpbuf *packet,
2188                            uint16_t in_port, uint16_t out_port)
2189 {
2190     struct ofp_action_output action;
2191     action.type = htons(OFPAT_OUTPUT);
2192     action.len = htons(sizeof action);
2193     action.port = htons(out_port);
2194     return make_packet_out(packet, UINT32_MAX, in_port,
2195                            (struct ofp_action_header *) &action, 1);
2196 }
2197
2198 struct ofpbuf *
2199 make_buffered_packet_out(uint32_t buffer_id,
2200                          uint16_t in_port, uint16_t out_port)
2201 {
2202     if (out_port != OFPP_NONE) {
2203         struct ofp_action_output action;
2204         action.type = htons(OFPAT_OUTPUT);
2205         action.len = htons(sizeof action);
2206         action.port = htons(out_port);
2207         return make_packet_out(NULL, buffer_id, in_port,
2208                                (struct ofp_action_header *) &action, 1);
2209     } else {
2210         return make_packet_out(NULL, buffer_id, in_port, NULL, 0);
2211     }
2212 }
2213
2214 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
2215 struct ofpbuf *
2216 make_echo_request(void)
2217 {
2218     struct ofp_header *rq;
2219     struct ofpbuf *out = ofpbuf_new(sizeof *rq);
2220     rq = ofpbuf_put_uninit(out, sizeof *rq);
2221     rq->version = OFP_VERSION;
2222     rq->type = OFPT_ECHO_REQUEST;
2223     rq->length = htons(sizeof *rq);
2224     rq->xid = htonl(0);
2225     return out;
2226 }
2227
2228 /* Creates and returns an OFPT_ECHO_REPLY message matching the
2229  * OFPT_ECHO_REQUEST message in 'rq'. */
2230 struct ofpbuf *
2231 make_echo_reply(const struct ofp_header *rq)
2232 {
2233     size_t size = ntohs(rq->length);
2234     struct ofpbuf *out = ofpbuf_new(size);
2235     struct ofp_header *reply = ofpbuf_put(out, rq, size);
2236     reply->type = OFPT_ECHO_REPLY;
2237     return out;
2238 }
2239
2240 const char *
2241 ofputil_frag_handling_to_string(enum ofp_config_flags flags)
2242 {
2243     switch (flags & OFPC_FRAG_MASK) {
2244     case OFPC_FRAG_NORMAL:   return "normal";
2245     case OFPC_FRAG_DROP:     return "drop";
2246     case OFPC_FRAG_REASM:    return "reassemble";
2247     case OFPC_FRAG_NX_MATCH: return "nx-match";
2248     }
2249
2250     NOT_REACHED();
2251 }
2252
2253 bool
2254 ofputil_frag_handling_from_string(const char *s, enum ofp_config_flags *flags)
2255 {
2256     if (!strcasecmp(s, "normal")) {
2257         *flags = OFPC_FRAG_NORMAL;
2258     } else if (!strcasecmp(s, "drop")) {
2259         *flags = OFPC_FRAG_DROP;
2260     } else if (!strcasecmp(s, "reassemble")) {
2261         *flags = OFPC_FRAG_REASM;
2262     } else if (!strcasecmp(s, "nx-match")) {
2263         *flags = OFPC_FRAG_NX_MATCH;
2264     } else {
2265         return false;
2266     }
2267     return true;
2268 }
2269
2270 /* Checks that 'port' is a valid output port for the OFPAT_OUTPUT action, given
2271  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
2272  * 'port' is valid, otherwise an OpenFlow return code. */
2273 enum ofperr
2274 ofputil_check_output_port(uint16_t port, int max_ports)
2275 {
2276     switch (port) {
2277     case OFPP_IN_PORT:
2278     case OFPP_TABLE:
2279     case OFPP_NORMAL:
2280     case OFPP_FLOOD:
2281     case OFPP_ALL:
2282     case OFPP_CONTROLLER:
2283     case OFPP_LOCAL:
2284         return 0;
2285
2286     default:
2287         if (port < max_ports) {
2288             return 0;
2289         }
2290         return OFPERR_OFPBAC_BAD_OUT_PORT;
2291     }
2292 }
2293
2294 #define OFPUTIL_NAMED_PORTS                     \
2295         OFPUTIL_NAMED_PORT(IN_PORT)             \
2296         OFPUTIL_NAMED_PORT(TABLE)               \
2297         OFPUTIL_NAMED_PORT(NORMAL)              \
2298         OFPUTIL_NAMED_PORT(FLOOD)               \
2299         OFPUTIL_NAMED_PORT(ALL)                 \
2300         OFPUTIL_NAMED_PORT(CONTROLLER)          \
2301         OFPUTIL_NAMED_PORT(LOCAL)               \
2302         OFPUTIL_NAMED_PORT(NONE)
2303
2304 /* Checks whether 's' is the string representation of an OpenFlow port number,
2305  * either as an integer or a string name (e.g. "LOCAL").  If it is, stores the
2306  * number in '*port' and returns true.  Otherwise, returns false. */
2307 bool
2308 ofputil_port_from_string(const char *name, uint16_t *port)
2309 {
2310     struct pair {
2311         const char *name;
2312         uint16_t value;
2313     };
2314     static const struct pair pairs[] = {
2315 #define OFPUTIL_NAMED_PORT(NAME) {#NAME, OFPP_##NAME},
2316         OFPUTIL_NAMED_PORTS
2317 #undef OFPUTIL_NAMED_PORT
2318     };
2319     static const int n_pairs = ARRAY_SIZE(pairs);
2320     int i;
2321
2322     if (str_to_int(name, 0, &i) && i >= 0 && i < UINT16_MAX) {
2323         *port = i;
2324         return true;
2325     }
2326
2327     for (i = 0; i < n_pairs; i++) {
2328         if (!strcasecmp(name, pairs[i].name)) {
2329             *port = pairs[i].value;
2330             return true;
2331         }
2332     }
2333     return false;
2334 }
2335
2336 /* Appends to 's' a string representation of the OpenFlow port number 'port'.
2337  * Most ports' string representation is just the port number, but for special
2338  * ports, e.g. OFPP_LOCAL, it is the name, e.g. "LOCAL". */
2339 void
2340 ofputil_format_port(uint16_t port, struct ds *s)
2341 {
2342     const char *name;
2343
2344     switch (port) {
2345 #define OFPUTIL_NAMED_PORT(NAME) case OFPP_##NAME: name = #NAME; break;
2346         OFPUTIL_NAMED_PORTS
2347 #undef OFPUTIL_NAMED_PORT
2348
2349     default:
2350         ds_put_format(s, "%"PRIu16, port);
2351         return;
2352     }
2353     ds_put_cstr(s, name);
2354 }
2355
2356 static enum ofperr
2357 check_resubmit_table(const struct nx_action_resubmit *nar)
2358 {
2359     if (nar->pad[0] || nar->pad[1] || nar->pad[2]) {
2360         return OFPERR_OFPBAC_BAD_ARGUMENT;
2361     }
2362     return 0;
2363 }
2364
2365 static enum ofperr
2366 check_output_reg(const struct nx_action_output_reg *naor,
2367                  const struct flow *flow)
2368 {
2369     struct mf_subfield src;
2370     size_t i;
2371
2372     for (i = 0; i < sizeof naor->zero; i++) {
2373         if (naor->zero[i]) {
2374             return OFPERR_OFPBAC_BAD_ARGUMENT;
2375         }
2376     }
2377
2378     nxm_decode(&src, naor->src, naor->ofs_nbits);
2379     return mf_check_src(&src, flow);
2380 }
2381
2382 enum ofperr
2383 validate_actions(const union ofp_action *actions, size_t n_actions,
2384                  const struct flow *flow, int max_ports)
2385 {
2386     const union ofp_action *a;
2387     size_t left;
2388
2389     OFPUTIL_ACTION_FOR_EACH (a, left, actions, n_actions) {
2390         enum ofperr error;
2391         uint16_t port;
2392         int code;
2393
2394         code = ofputil_decode_action(a);
2395         if (code < 0) {
2396             error = -code;
2397             VLOG_WARN_RL(&bad_ofmsg_rl,
2398                          "action decoding error at offset %td (%s)",
2399                          (a - actions) * sizeof *a, ofperr_get_name(error));
2400
2401             return error;
2402         }
2403
2404         error = 0;
2405         switch ((enum ofputil_action_code) code) {
2406         case OFPUTIL_OFPAT_OUTPUT:
2407             error = ofputil_check_output_port(ntohs(a->output.port),
2408                                               max_ports);
2409             break;
2410
2411         case OFPUTIL_OFPAT_SET_VLAN_VID:
2412             if (a->vlan_vid.vlan_vid & ~htons(0xfff)) {
2413                 error = OFPERR_OFPBAC_BAD_ARGUMENT;
2414             }
2415             break;
2416
2417         case OFPUTIL_OFPAT_SET_VLAN_PCP:
2418             if (a->vlan_pcp.vlan_pcp & ~7) {
2419                 error = OFPERR_OFPBAC_BAD_ARGUMENT;
2420             }
2421             break;
2422
2423         case OFPUTIL_OFPAT_ENQUEUE:
2424             port = ntohs(((const struct ofp_action_enqueue *) a)->port);
2425             if (port >= max_ports && port != OFPP_IN_PORT
2426                 && port != OFPP_LOCAL) {
2427                 error = OFPERR_OFPBAC_BAD_OUT_PORT;
2428             }
2429             break;
2430
2431         case OFPUTIL_NXAST_REG_MOVE:
2432             error = nxm_check_reg_move((const struct nx_action_reg_move *) a,
2433                                        flow);
2434             break;
2435
2436         case OFPUTIL_NXAST_REG_LOAD:
2437             error = nxm_check_reg_load((const struct nx_action_reg_load *) a,
2438                                        flow);
2439             break;
2440
2441         case OFPUTIL_NXAST_MULTIPATH:
2442             error = multipath_check((const struct nx_action_multipath *) a,
2443                                     flow);
2444             break;
2445
2446         case OFPUTIL_NXAST_AUTOPATH:
2447             error = autopath_check((const struct nx_action_autopath *) a,
2448                                    flow);
2449             break;
2450
2451         case OFPUTIL_NXAST_BUNDLE:
2452         case OFPUTIL_NXAST_BUNDLE_LOAD:
2453             error = bundle_check((const struct nx_action_bundle *) a,
2454                                  max_ports, flow);
2455             break;
2456
2457         case OFPUTIL_NXAST_OUTPUT_REG:
2458             error = check_output_reg((const struct nx_action_output_reg *) a,
2459                                      flow);
2460             break;
2461
2462         case OFPUTIL_NXAST_RESUBMIT_TABLE:
2463             error = check_resubmit_table(
2464                 (const struct nx_action_resubmit *) a);
2465             break;
2466
2467         case OFPUTIL_NXAST_LEARN:
2468             error = learn_check((const struct nx_action_learn *) a, flow);
2469             break;
2470
2471         case OFPUTIL_OFPAT_STRIP_VLAN:
2472         case OFPUTIL_OFPAT_SET_NW_SRC:
2473         case OFPUTIL_OFPAT_SET_NW_DST:
2474         case OFPUTIL_OFPAT_SET_NW_TOS:
2475         case OFPUTIL_OFPAT_SET_TP_SRC:
2476         case OFPUTIL_OFPAT_SET_TP_DST:
2477         case OFPUTIL_OFPAT_SET_DL_SRC:
2478         case OFPUTIL_OFPAT_SET_DL_DST:
2479         case OFPUTIL_NXAST_RESUBMIT:
2480         case OFPUTIL_NXAST_SET_TUNNEL:
2481         case OFPUTIL_NXAST_SET_QUEUE:
2482         case OFPUTIL_NXAST_POP_QUEUE:
2483         case OFPUTIL_NXAST_NOTE:
2484         case OFPUTIL_NXAST_SET_TUNNEL64:
2485         case OFPUTIL_NXAST_EXIT:
2486         case OFPUTIL_NXAST_DEC_TTL:
2487             break;
2488         }
2489
2490         if (error) {
2491             VLOG_WARN_RL(&bad_ofmsg_rl, "bad action at offset %td (%s)",
2492                          (a - actions) * sizeof *a, ofperr_get_name(error));
2493             return error;
2494         }
2495     }
2496     if (left) {
2497         VLOG_WARN_RL(&bad_ofmsg_rl, "bad action format at offset %zu",
2498                      (n_actions - left) * sizeof *a);
2499         return OFPERR_OFPBAC_BAD_LEN;
2500     }
2501     return 0;
2502 }
2503
2504 struct ofputil_action {
2505     int code;
2506     unsigned int min_len;
2507     unsigned int max_len;
2508 };
2509
2510 static const struct ofputil_action action_bad_type
2511     = { -OFPERR_OFPBAC_BAD_TYPE,   0, UINT_MAX };
2512 static const struct ofputil_action action_bad_len
2513     = { -OFPERR_OFPBAC_BAD_LEN,    0, UINT_MAX };
2514 static const struct ofputil_action action_bad_vendor
2515     = { -OFPERR_OFPBAC_BAD_VENDOR, 0, UINT_MAX };
2516
2517 static const struct ofputil_action *
2518 ofputil_decode_ofpat_action(const union ofp_action *a)
2519 {
2520     enum ofp_action_type type = ntohs(a->type);
2521
2522     switch (type) {
2523 #define OFPAT_ACTION(ENUM, STRUCT, NAME)                    \
2524         case ENUM: {                                        \
2525             static const struct ofputil_action action = {   \
2526                 OFPUTIL_##ENUM,                             \
2527                 sizeof(struct STRUCT),                      \
2528                 sizeof(struct STRUCT)                       \
2529             };                                              \
2530             return &action;                                 \
2531         }
2532 #include "ofp-util.def"
2533
2534     case OFPAT_VENDOR:
2535     default:
2536         return &action_bad_type;
2537     }
2538 }
2539
2540 static const struct ofputil_action *
2541 ofputil_decode_nxast_action(const union ofp_action *a)
2542 {
2543     const struct nx_action_header *nah = (const struct nx_action_header *) a;
2544     enum nx_action_subtype subtype = ntohs(nah->subtype);
2545
2546     switch (subtype) {
2547 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)            \
2548         case ENUM: {                                            \
2549             static const struct ofputil_action action = {       \
2550                 OFPUTIL_##ENUM,                                 \
2551                 sizeof(struct STRUCT),                          \
2552                 EXTENSIBLE ? UINT_MAX : sizeof(struct STRUCT)   \
2553             };                                                  \
2554             return &action;                                     \
2555         }
2556 #include "ofp-util.def"
2557
2558     case NXAST_SNAT__OBSOLETE:
2559     case NXAST_DROP_SPOOFED_ARP__OBSOLETE:
2560     default:
2561         return &action_bad_type;
2562     }
2563 }
2564
2565 /* Parses 'a' to determine its type.  Returns a nonnegative OFPUTIL_OFPAT_* or
2566  * OFPUTIL_NXAST_* constant if successful, otherwise a negative OFPERR_* error
2567  * code.
2568  *
2569  * The caller must have already verified that 'a''s length is correct (that is,
2570  * a->header.len is nonzero and a multiple of sizeof(union ofp_action) and no
2571  * longer than the amount of space allocated to 'a').
2572  *
2573  * This function verifies that 'a''s length is correct for the type of action
2574  * that it represents. */
2575 int
2576 ofputil_decode_action(const union ofp_action *a)
2577 {
2578     const struct ofputil_action *action;
2579     uint16_t len = ntohs(a->header.len);
2580
2581     if (a->type != htons(OFPAT_VENDOR)) {
2582         action = ofputil_decode_ofpat_action(a);
2583     } else {
2584         switch (ntohl(a->vendor.vendor)) {
2585         case NX_VENDOR_ID:
2586             if (len < sizeof(struct nx_action_header)) {
2587                 return -OFPERR_OFPBAC_BAD_LEN;
2588             }
2589             action = ofputil_decode_nxast_action(a);
2590             break;
2591         default:
2592             action = &action_bad_vendor;
2593             break;
2594         }
2595     }
2596
2597     return (len >= action->min_len && len <= action->max_len
2598             ? action->code
2599             : -OFPERR_OFPBAC_BAD_LEN);
2600 }
2601
2602 /* Parses 'a' and returns its type as an OFPUTIL_OFPAT_* or OFPUTIL_NXAST_*
2603  * constant.  The caller must have already validated that 'a' is a valid action
2604  * understood by Open vSwitch (e.g. by a previous successful call to
2605  * ofputil_decode_action()). */
2606 enum ofputil_action_code
2607 ofputil_decode_action_unsafe(const union ofp_action *a)
2608 {
2609     const struct ofputil_action *action;
2610
2611     if (a->type != htons(OFPAT_VENDOR)) {
2612         action = ofputil_decode_ofpat_action(a);
2613     } else {
2614         action = ofputil_decode_nxast_action(a);
2615     }
2616
2617     return action->code;
2618 }
2619
2620 /* Returns the 'enum ofputil_action_code' corresponding to 'name' (e.g. if
2621  * 'name' is "output" then the return value is OFPUTIL_OFPAT_OUTPUT), or -1 if
2622  * 'name' is not the name of any action.
2623  *
2624  * ofp-util.def lists the mapping from names to action. */
2625 int
2626 ofputil_action_code_from_name(const char *name)
2627 {
2628     static const char *names[OFPUTIL_N_ACTIONS] = {
2629 #define OFPAT_ACTION(ENUM, STRUCT, NAME)             NAME,
2630 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) NAME,
2631 #include "ofp-util.def"
2632     };
2633
2634     const char **p;
2635
2636     for (p = names; p < &names[ARRAY_SIZE(names)]; p++) {
2637         if (*p && !strcasecmp(name, *p)) {
2638             return p - names;
2639         }
2640     }
2641     return -1;
2642 }
2643
2644 /* Appends an action of the type specified by 'code' to 'buf' and returns the
2645  * action.  Initializes the parts of 'action' that identify it as having type
2646  * <ENUM> and length 'sizeof *action' and zeros the rest.  For actions that
2647  * have variable length, the length used and cleared is that of struct
2648  * <STRUCT>.  */
2649 void *
2650 ofputil_put_action(enum ofputil_action_code code, struct ofpbuf *buf)
2651 {
2652     switch (code) {
2653 #define OFPAT_ACTION(ENUM, STRUCT, NAME)                    \
2654     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
2655 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)        \
2656     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
2657 #include "ofp-util.def"
2658     }
2659     NOT_REACHED();
2660 }
2661
2662 #define OFPAT_ACTION(ENUM, STRUCT, NAME)                        \
2663     void                                                        \
2664     ofputil_init_##ENUM(struct STRUCT *s)                       \
2665     {                                                           \
2666         memset(s, 0, sizeof *s);                                \
2667         s->type = htons(ENUM);                                  \
2668         s->len = htons(sizeof *s);                              \
2669     }                                                           \
2670                                                                 \
2671     struct STRUCT *                                             \
2672     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
2673     {                                                           \
2674         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
2675         ofputil_init_##ENUM(s);                                 \
2676         return s;                                               \
2677     }
2678 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)            \
2679     void                                                        \
2680     ofputil_init_##ENUM(struct STRUCT *s)                       \
2681     {                                                           \
2682         memset(s, 0, sizeof *s);                                \
2683         s->type = htons(OFPAT_VENDOR);                          \
2684         s->len = htons(sizeof *s);                              \
2685         s->vendor = htonl(NX_VENDOR_ID);                        \
2686         s->subtype = htons(ENUM);                               \
2687     }                                                           \
2688                                                                 \
2689     struct STRUCT *                                             \
2690     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
2691     {                                                           \
2692         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
2693         ofputil_init_##ENUM(s);                                 \
2694         return s;                                               \
2695     }
2696 #include "ofp-util.def"
2697
2698 /* Returns true if 'action' outputs to 'port', false otherwise. */
2699 bool
2700 action_outputs_to_port(const union ofp_action *action, ovs_be16 port)
2701 {
2702     switch (ntohs(action->type)) {
2703     case OFPAT_OUTPUT:
2704         return action->output.port == port;
2705     case OFPAT_ENQUEUE:
2706         return ((const struct ofp_action_enqueue *) action)->port == port;
2707     default:
2708         return false;
2709     }
2710 }
2711
2712 /* "Normalizes" the wildcards in 'rule'.  That means:
2713  *
2714  *    1. If the type of level N is known, then only the valid fields for that
2715  *       level may be specified.  For example, ARP does not have a TOS field,
2716  *       so nw_tos must be wildcarded if 'rule' specifies an ARP flow.
2717  *       Similarly, IPv4 does not have any IPv6 addresses, so ipv6_src and
2718  *       ipv6_dst (and other fields) must be wildcarded if 'rule' specifies an
2719  *       IPv4 flow.
2720  *
2721  *    2. If the type of level N is not known (or not understood by Open
2722  *       vSwitch), then no fields at all for that level may be specified.  For
2723  *       example, Open vSwitch does not understand SCTP, an L4 protocol, so the
2724  *       L4 fields tp_src and tp_dst must be wildcarded if 'rule' specifies an
2725  *       SCTP flow.
2726  *
2727  * 'flow_format' specifies the format of the flow as received or as intended to
2728  * be sent.  This is important for IPv6 and ARP, for which NXM supports more
2729  * detailed matching. */
2730 void
2731 ofputil_normalize_rule(struct cls_rule *rule, enum nx_flow_format flow_format)
2732 {
2733     enum {
2734         MAY_NW_ADDR     = 1 << 0, /* nw_src, nw_dst */
2735         MAY_TP_ADDR     = 1 << 1, /* tp_src, tp_dst */
2736         MAY_NW_PROTO    = 1 << 2, /* nw_proto */
2737         MAY_IPVx        = 1 << 3, /* tos, frag, ttl */
2738         MAY_ARP_SHA     = 1 << 4, /* arp_sha */
2739         MAY_ARP_THA     = 1 << 5, /* arp_tha */
2740         MAY_IPV6        = 1 << 6, /* ipv6_src, ipv6_dst, ipv6_label */
2741         MAY_ND_TARGET   = 1 << 7  /* nd_target */
2742     } may_match;
2743
2744     struct flow_wildcards wc;
2745
2746     /* Figure out what fields may be matched. */
2747     if (rule->flow.dl_type == htons(ETH_TYPE_IP)) {
2748         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_NW_ADDR;
2749         if (rule->flow.nw_proto == IPPROTO_TCP ||
2750             rule->flow.nw_proto == IPPROTO_UDP ||
2751             rule->flow.nw_proto == IPPROTO_ICMP) {
2752             may_match |= MAY_TP_ADDR;
2753         }
2754     } else if (rule->flow.dl_type == htons(ETH_TYPE_IPV6)
2755                && flow_format == NXFF_NXM) {
2756         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_IPV6;
2757         if (rule->flow.nw_proto == IPPROTO_TCP ||
2758             rule->flow.nw_proto == IPPROTO_UDP) {
2759             may_match |= MAY_TP_ADDR;
2760         } else if (rule->flow.nw_proto == IPPROTO_ICMPV6) {
2761             may_match |= MAY_TP_ADDR;
2762             if (rule->flow.tp_src == htons(ND_NEIGHBOR_SOLICIT)) {
2763                 may_match |= MAY_ND_TARGET | MAY_ARP_SHA;
2764             } else if (rule->flow.tp_src == htons(ND_NEIGHBOR_ADVERT)) {
2765                 may_match |= MAY_ND_TARGET | MAY_ARP_THA;
2766             }
2767         }
2768     } else if (rule->flow.dl_type == htons(ETH_TYPE_ARP)) {
2769         may_match = MAY_NW_PROTO | MAY_NW_ADDR;
2770         if (flow_format == NXFF_NXM) {
2771             may_match |= MAY_ARP_SHA | MAY_ARP_THA;
2772         }
2773     } else {
2774         may_match = 0;
2775     }
2776
2777     /* Clear the fields that may not be matched. */
2778     wc = rule->wc;
2779     if (!(may_match & MAY_NW_ADDR)) {
2780         wc.nw_src_mask = wc.nw_dst_mask = htonl(0);
2781     }
2782     if (!(may_match & MAY_TP_ADDR)) {
2783         wc.tp_src_mask = wc.tp_dst_mask = htons(0);
2784     }
2785     if (!(may_match & MAY_NW_PROTO)) {
2786         wc.wildcards |= FWW_NW_PROTO;
2787     }
2788     if (!(may_match & MAY_IPVx)) {
2789         wc.wildcards |= FWW_NW_DSCP;
2790         wc.wildcards |= FWW_NW_ECN;
2791         wc.wildcards |= FWW_NW_TTL;
2792     }
2793     if (!(may_match & MAY_ARP_SHA)) {
2794         wc.wildcards |= FWW_ARP_SHA;
2795     }
2796     if (!(may_match & MAY_ARP_THA)) {
2797         wc.wildcards |= FWW_ARP_THA;
2798     }
2799     if (!(may_match & MAY_IPV6)) {
2800         wc.ipv6_src_mask = wc.ipv6_dst_mask = in6addr_any;
2801         wc.wildcards |= FWW_IPV6_LABEL;
2802     }
2803     if (!(may_match & MAY_ND_TARGET)) {
2804         wc.wildcards |= FWW_ND_TARGET;
2805     }
2806
2807     /* Log any changes. */
2808     if (!flow_wildcards_equal(&wc, &rule->wc)) {
2809         bool log = !VLOG_DROP_INFO(&bad_ofmsg_rl);
2810         char *pre = log ? cls_rule_to_string(rule) : NULL;
2811
2812         rule->wc = wc;
2813         cls_rule_zero_wildcarded_fields(rule);
2814
2815         if (log) {
2816             char *post = cls_rule_to_string(rule);
2817             VLOG_INFO("normalization changed ofp_match, details:");
2818             VLOG_INFO(" pre: %s", pre);
2819             VLOG_INFO("post: %s", post);
2820             free(pre);
2821             free(post);
2822         }
2823     }
2824 }
2825
2826 /* Attempts to pull 'actions_len' bytes from the front of 'b'.  Returns 0 if
2827  * successful, otherwise an OpenFlow error.
2828  *
2829  * If successful, the first action is stored in '*actionsp' and the number of
2830  * "union ofp_action" size elements into '*n_actionsp'.  Otherwise NULL and 0
2831  * are stored, respectively.
2832  *
2833  * This function does not check that the actions are valid (the caller should
2834  * do so, with validate_actions()).  The caller is also responsible for making
2835  * sure that 'b->data' is initially aligned appropriately for "union
2836  * ofp_action". */
2837 enum ofperr
2838 ofputil_pull_actions(struct ofpbuf *b, unsigned int actions_len,
2839                      union ofp_action **actionsp, size_t *n_actionsp)
2840 {
2841     if (actions_len % OFP_ACTION_ALIGN != 0) {
2842         VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
2843                      "is not a multiple of %d", actions_len, OFP_ACTION_ALIGN);
2844         goto error;
2845     }
2846
2847     *actionsp = ofpbuf_try_pull(b, actions_len);
2848     if (*actionsp == NULL) {
2849         VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
2850                      "exceeds remaining message length (%zu)",
2851                      actions_len, b->size);
2852         goto error;
2853     }
2854
2855     *n_actionsp = actions_len / OFP_ACTION_ALIGN;
2856     return 0;
2857
2858 error:
2859     *actionsp = NULL;
2860     *n_actionsp = 0;
2861     return OFPERR_OFPBRC_BAD_LEN;
2862 }
2863
2864 bool
2865 ofputil_actions_equal(const union ofp_action *a, size_t n_a,
2866                       const union ofp_action *b, size_t n_b)
2867 {
2868     return n_a == n_b && (!n_a || !memcmp(a, b, n_a * sizeof *a));
2869 }
2870
2871 union ofp_action *
2872 ofputil_actions_clone(const union ofp_action *actions, size_t n)
2873 {
2874     return n ? xmemdup(actions, n * sizeof *actions) : NULL;
2875 }
2876
2877 /* Parses a key or a key-value pair from '*stringp'.
2878  *
2879  * On success: Stores the key into '*keyp'.  Stores the value, if present, into
2880  * '*valuep', otherwise an empty string.  Advances '*stringp' past the end of
2881  * the key-value pair, preparing it for another call.  '*keyp' and '*valuep'
2882  * are substrings of '*stringp' created by replacing some of its bytes by null
2883  * terminators.  Returns true.
2884  *
2885  * If '*stringp' is just white space or commas, sets '*keyp' and '*valuep' to
2886  * NULL and returns false. */
2887 bool
2888 ofputil_parse_key_value(char **stringp, char **keyp, char **valuep)
2889 {
2890     char *pos, *key, *value;
2891     size_t key_len;
2892
2893     pos = *stringp;
2894     pos += strspn(pos, ", \t\r\n");
2895     if (*pos == '\0') {
2896         *keyp = *valuep = NULL;
2897         return false;
2898     }
2899
2900     key = pos;
2901     key_len = strcspn(pos, ":=(, \t\r\n");
2902     if (key[key_len] == ':' || key[key_len] == '=') {
2903         /* The value can be separated by a colon. */
2904         size_t value_len;
2905
2906         value = key + key_len + 1;
2907         value_len = strcspn(value, ", \t\r\n");
2908         pos = value + value_len + (value[value_len] != '\0');
2909         value[value_len] = '\0';
2910     } else if (key[key_len] == '(') {
2911         /* The value can be surrounded by balanced parentheses.  The outermost
2912          * set of parentheses is removed. */
2913         int level = 1;
2914         size_t value_len;
2915
2916         value = key + key_len + 1;
2917         for (value_len = 0; level > 0; value_len++) {
2918             switch (value[value_len]) {
2919             case '\0':
2920                 ovs_fatal(0, "unbalanced parentheses in argument to %s", key);
2921
2922             case '(':
2923                 level++;
2924                 break;
2925
2926             case ')':
2927                 level--;
2928                 break;
2929             }
2930         }
2931         value[value_len - 1] = '\0';
2932         pos = value + value_len;
2933     } else {
2934         /* There might be no value at all. */
2935         value = key + key_len;  /* Will become the empty string below. */
2936         pos = key + key_len + (key[key_len] != '\0');
2937     }
2938     key[key_len] = '\0';
2939
2940     *stringp = pos;
2941     *keyp = key;
2942     *valuep = value;
2943     return true;
2944 }