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