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