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