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