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