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