Don't overload IP TOS with the frag matching bits.
[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 == 5);
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_ND_TARGET
112                       | FWW_IPV6_LABEL);
113
114     if (!(ofpfw & OFPFW_NW_TOS)) {
115         wc->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.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->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.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 == 5);
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->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     /* Other formats can express this rule. */
901     return NXFF_OPENFLOW10;
902 }
903
904 /* Returns an OpenFlow message that can be used to set the flow format to
905  * 'flow_format'.  */
906 struct ofpbuf *
907 ofputil_make_set_flow_format(enum nx_flow_format flow_format)
908 {
909     struct nxt_set_flow_format *sff;
910     struct ofpbuf *msg;
911
912     sff = make_nxmsg(sizeof *sff, NXT_SET_FLOW_FORMAT, &msg);
913     sff->format = htonl(flow_format);
914
915     return msg;
916 }
917
918 /* Returns an OpenFlow message that can be used to turn the flow_mod_table_id
919  * extension on or off (according to 'flow_mod_table_id'). */
920 struct ofpbuf *
921 ofputil_make_flow_mod_table_id(bool flow_mod_table_id)
922 {
923     struct nxt_flow_mod_table_id *nfmti;
924     struct ofpbuf *msg;
925
926     nfmti = make_nxmsg(sizeof *nfmti, NXT_FLOW_MOD_TABLE_ID, &msg);
927     nfmti->set = flow_mod_table_id;
928     return msg;
929 }
930
931 /* Converts an OFPT_FLOW_MOD or NXT_FLOW_MOD message 'oh' into an abstract
932  * flow_mod in 'fm'.  Returns 0 if successful, otherwise an OpenFlow error
933  * code.
934  *
935  * 'flow_mod_table_id' should be true if the NXT_FLOW_MOD_TABLE_ID extension is
936  * enabled, false otherwise.
937  *
938  * Does not validate the flow_mod actions. */
939 int
940 ofputil_decode_flow_mod(struct ofputil_flow_mod *fm,
941                         const struct ofp_header *oh, bool flow_mod_table_id)
942 {
943     const struct ofputil_msg_type *type;
944     uint16_t command;
945     struct ofpbuf b;
946
947     ofpbuf_use_const(&b, oh, ntohs(oh->length));
948
949     ofputil_decode_msg_type(oh, &type);
950     if (ofputil_msg_type_code(type) == OFPUTIL_OFPT_FLOW_MOD) {
951         /* Standard OpenFlow flow_mod. */
952         const struct ofp_flow_mod *ofm;
953         uint16_t priority;
954         int error;
955
956         /* Dissect the message. */
957         ofm = ofpbuf_pull(&b, sizeof *ofm);
958         error = ofputil_pull_actions(&b, b.size, &fm->actions, &fm->n_actions);
959         if (error) {
960             return error;
961         }
962
963         /* Set priority based on original wildcards.  Normally we'd allow
964          * ofputil_cls_rule_from_match() to do this for us, but
965          * ofputil_normalize_rule() can put wildcards where the original flow
966          * didn't have them. */
967         priority = ntohs(ofm->priority);
968         if (!(ofm->match.wildcards & htonl(OFPFW_ALL))) {
969             priority = UINT16_MAX;
970         }
971
972         /* Translate the rule. */
973         ofputil_cls_rule_from_match(&ofm->match, priority, &fm->cr);
974         ofputil_normalize_rule(&fm->cr, NXFF_OPENFLOW10);
975
976         /* Translate the message. */
977         fm->cookie = ofm->cookie;
978         command = ntohs(ofm->command);
979         fm->idle_timeout = ntohs(ofm->idle_timeout);
980         fm->hard_timeout = ntohs(ofm->hard_timeout);
981         fm->buffer_id = ntohl(ofm->buffer_id);
982         fm->out_port = ntohs(ofm->out_port);
983         fm->flags = ntohs(ofm->flags);
984     } else if (ofputil_msg_type_code(type) == OFPUTIL_NXT_FLOW_MOD) {
985         /* Nicira extended flow_mod. */
986         const struct nx_flow_mod *nfm;
987         int error;
988
989         /* Dissect the message. */
990         nfm = ofpbuf_pull(&b, sizeof *nfm);
991         error = nx_pull_match(&b, ntohs(nfm->match_len), ntohs(nfm->priority),
992                               &fm->cr);
993         if (error) {
994             return error;
995         }
996         error = ofputil_pull_actions(&b, b.size, &fm->actions, &fm->n_actions);
997         if (error) {
998             return error;
999         }
1000
1001         /* Translate the message. */
1002         fm->cookie = nfm->cookie;
1003         command = ntohs(nfm->command);
1004         fm->idle_timeout = ntohs(nfm->idle_timeout);
1005         fm->hard_timeout = ntohs(nfm->hard_timeout);
1006         fm->buffer_id = ntohl(nfm->buffer_id);
1007         fm->out_port = ntohs(nfm->out_port);
1008         fm->flags = ntohs(nfm->flags);
1009     } else {
1010         NOT_REACHED();
1011     }
1012
1013     if (flow_mod_table_id) {
1014         fm->command = command & 0xff;
1015         fm->table_id = command >> 8;
1016     } else {
1017         fm->command = command;
1018         fm->table_id = 0xff;
1019     }
1020
1021     return 0;
1022 }
1023
1024 /* Converts 'fm' into an OFPT_FLOW_MOD or NXT_FLOW_MOD message according to
1025  * 'flow_format' and returns the message.
1026  *
1027  * 'flow_mod_table_id' should be true if the NXT_FLOW_MOD_TABLE_ID extension is
1028  * enabled, false otherwise. */
1029 struct ofpbuf *
1030 ofputil_encode_flow_mod(const struct ofputil_flow_mod *fm,
1031                         enum nx_flow_format flow_format,
1032                         bool flow_mod_table_id)
1033 {
1034     size_t actions_len = fm->n_actions * sizeof *fm->actions;
1035     struct ofpbuf *msg;
1036     uint16_t command;
1037
1038     command = (flow_mod_table_id
1039                ? (fm->command & 0xff) | (fm->table_id << 8)
1040                : fm->command);
1041
1042     if (flow_format == NXFF_OPENFLOW10) {
1043         struct ofp_flow_mod *ofm;
1044
1045         msg = ofpbuf_new(sizeof *ofm + actions_len);
1046         ofm = put_openflow(sizeof *ofm, OFPT_FLOW_MOD, msg);
1047         ofputil_cls_rule_to_match(&fm->cr, &ofm->match);
1048         ofm->cookie = fm->cookie;
1049         ofm->command = htons(command);
1050         ofm->idle_timeout = htons(fm->idle_timeout);
1051         ofm->hard_timeout = htons(fm->hard_timeout);
1052         ofm->priority = htons(fm->cr.priority);
1053         ofm->buffer_id = htonl(fm->buffer_id);
1054         ofm->out_port = htons(fm->out_port);
1055         ofm->flags = htons(fm->flags);
1056     } else if (flow_format == NXFF_NXM) {
1057         struct nx_flow_mod *nfm;
1058         int match_len;
1059
1060         msg = ofpbuf_new(sizeof *nfm + NXM_TYPICAL_LEN + actions_len);
1061         put_nxmsg(sizeof *nfm, NXT_FLOW_MOD, msg);
1062         match_len = nx_put_match(msg, &fm->cr);
1063
1064         nfm = msg->data;
1065         nfm->cookie = fm->cookie;
1066         nfm->command = htons(command);
1067         nfm->idle_timeout = htons(fm->idle_timeout);
1068         nfm->hard_timeout = htons(fm->hard_timeout);
1069         nfm->priority = htons(fm->cr.priority);
1070         nfm->buffer_id = htonl(fm->buffer_id);
1071         nfm->out_port = htons(fm->out_port);
1072         nfm->flags = htons(fm->flags);
1073         nfm->match_len = htons(match_len);
1074     } else {
1075         NOT_REACHED();
1076     }
1077
1078     ofpbuf_put(msg, fm->actions, actions_len);
1079     update_openflow_length(msg);
1080     return msg;
1081 }
1082
1083 static int
1084 ofputil_decode_ofpst_flow_request(struct ofputil_flow_stats_request *fsr,
1085                                   const struct ofp_header *oh,
1086                                   bool aggregate)
1087 {
1088     const struct ofp_flow_stats_request *ofsr =
1089         (const struct ofp_flow_stats_request *) oh;
1090
1091     fsr->aggregate = aggregate;
1092     ofputil_cls_rule_from_match(&ofsr->match, 0, &fsr->match);
1093     fsr->out_port = ntohs(ofsr->out_port);
1094     fsr->table_id = ofsr->table_id;
1095
1096     return 0;
1097 }
1098
1099 static int
1100 ofputil_decode_nxst_flow_request(struct ofputil_flow_stats_request *fsr,
1101                                  const struct ofp_header *oh,
1102                                  bool aggregate)
1103 {
1104     const struct nx_flow_stats_request *nfsr;
1105     struct ofpbuf b;
1106     int error;
1107
1108     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1109
1110     nfsr = ofpbuf_pull(&b, sizeof *nfsr);
1111     error = nx_pull_match(&b, ntohs(nfsr->match_len), 0, &fsr->match);
1112     if (error) {
1113         return error;
1114     }
1115     if (b.size) {
1116         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1117     }
1118
1119     fsr->aggregate = aggregate;
1120     fsr->out_port = ntohs(nfsr->out_port);
1121     fsr->table_id = nfsr->table_id;
1122
1123     return 0;
1124 }
1125
1126 /* Converts an OFPST_FLOW, OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE
1127  * request 'oh', into an abstract flow_stats_request in 'fsr'.  Returns 0 if
1128  * successful, otherwise an OpenFlow error code. */
1129 int
1130 ofputil_decode_flow_stats_request(struct ofputil_flow_stats_request *fsr,
1131                                   const struct ofp_header *oh)
1132 {
1133     const struct ofputil_msg_type *type;
1134     struct ofpbuf b;
1135     int code;
1136
1137     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1138
1139     ofputil_decode_msg_type(oh, &type);
1140     code = ofputil_msg_type_code(type);
1141     switch (code) {
1142     case OFPUTIL_OFPST_FLOW_REQUEST:
1143         return ofputil_decode_ofpst_flow_request(fsr, oh, false);
1144
1145     case OFPUTIL_OFPST_AGGREGATE_REQUEST:
1146         return ofputil_decode_ofpst_flow_request(fsr, oh, true);
1147
1148     case OFPUTIL_NXST_FLOW_REQUEST:
1149         return ofputil_decode_nxst_flow_request(fsr, oh, false);
1150
1151     case OFPUTIL_NXST_AGGREGATE_REQUEST:
1152         return ofputil_decode_nxst_flow_request(fsr, oh, true);
1153
1154     default:
1155         /* Hey, the caller lied. */
1156         NOT_REACHED();
1157     }
1158 }
1159
1160 /* Converts abstract flow_stats_request 'fsr' into an OFPST_FLOW,
1161  * OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE request 'oh' according to
1162  * 'flow_format', and returns the message. */
1163 struct ofpbuf *
1164 ofputil_encode_flow_stats_request(const struct ofputil_flow_stats_request *fsr,
1165                                   enum nx_flow_format flow_format)
1166 {
1167     struct ofpbuf *msg;
1168
1169     if (flow_format == NXFF_OPENFLOW10) {
1170         struct ofp_flow_stats_request *ofsr;
1171         int type;
1172
1173         type = fsr->aggregate ? OFPST_AGGREGATE : OFPST_FLOW;
1174         ofsr = ofputil_make_stats_request(sizeof *ofsr, type, 0, &msg);
1175         ofputil_cls_rule_to_match(&fsr->match, &ofsr->match);
1176         ofsr->table_id = fsr->table_id;
1177         ofsr->out_port = htons(fsr->out_port);
1178     } else if (flow_format == NXFF_NXM) {
1179         struct nx_flow_stats_request *nfsr;
1180         int match_len;
1181         int subtype;
1182
1183         subtype = fsr->aggregate ? NXST_AGGREGATE : NXST_FLOW;
1184         ofputil_make_stats_request(sizeof *nfsr, OFPST_VENDOR, subtype, &msg);
1185         match_len = nx_put_match(msg, &fsr->match);
1186
1187         nfsr = msg->data;
1188         nfsr->out_port = htons(fsr->out_port);
1189         nfsr->match_len = htons(match_len);
1190         nfsr->table_id = fsr->table_id;
1191     } else {
1192         NOT_REACHED();
1193     }
1194
1195     return msg;
1196 }
1197
1198 /* Converts an OFPST_FLOW or NXST_FLOW reply in 'msg' into an abstract
1199  * ofputil_flow_stats in 'fs'.
1200  *
1201  * Multiple OFPST_FLOW or NXST_FLOW replies can be packed into a single
1202  * OpenFlow message.  Calling this function multiple times for a single 'msg'
1203  * iterates through the replies.  The caller must initially leave 'msg''s layer
1204  * pointers null and not modify them between calls.
1205  *
1206  * Returns 0 if successful, EOF if no replies were left in this 'msg',
1207  * otherwise a positive errno value. */
1208 int
1209 ofputil_decode_flow_stats_reply(struct ofputil_flow_stats *fs,
1210                                 struct ofpbuf *msg)
1211 {
1212     const struct ofputil_msg_type *type;
1213     int code;
1214
1215     ofputil_decode_msg_type(msg->l2 ? msg->l2 : msg->data, &type);
1216     code = ofputil_msg_type_code(type);
1217     if (!msg->l2) {
1218         msg->l2 = msg->data;
1219         if (code == OFPUTIL_OFPST_FLOW_REPLY) {
1220             ofpbuf_pull(msg, sizeof(struct ofp_stats_msg));
1221         } else if (code == OFPUTIL_NXST_FLOW_REPLY) {
1222             ofpbuf_pull(msg, sizeof(struct nicira_stats_msg));
1223         } else {
1224             NOT_REACHED();
1225         }
1226     }
1227
1228     if (!msg->size) {
1229         return EOF;
1230     } else if (code == OFPUTIL_OFPST_FLOW_REPLY) {
1231         const struct ofp_flow_stats *ofs;
1232         size_t length;
1233
1234         ofs = ofpbuf_try_pull(msg, sizeof *ofs);
1235         if (!ofs) {
1236             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply has %zu leftover "
1237                          "bytes at end", msg->size);
1238             return EINVAL;
1239         }
1240
1241         length = ntohs(ofs->length);
1242         if (length < sizeof *ofs) {
1243             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply claims invalid "
1244                          "length %zu", length);
1245             return EINVAL;
1246         }
1247
1248         if (ofputil_pull_actions(msg, length - sizeof *ofs,
1249                                  &fs->actions, &fs->n_actions)) {
1250             return EINVAL;
1251         }
1252
1253         fs->cookie = get_32aligned_be64(&ofs->cookie);
1254         ofputil_cls_rule_from_match(&ofs->match, ntohs(ofs->priority),
1255                                     &fs->rule);
1256         fs->table_id = ofs->table_id;
1257         fs->duration_sec = ntohl(ofs->duration_sec);
1258         fs->duration_nsec = ntohl(ofs->duration_nsec);
1259         fs->idle_timeout = ntohs(ofs->idle_timeout);
1260         fs->hard_timeout = ntohs(ofs->hard_timeout);
1261         fs->packet_count = ntohll(get_32aligned_be64(&ofs->packet_count));
1262         fs->byte_count = ntohll(get_32aligned_be64(&ofs->byte_count));
1263     } else if (code == OFPUTIL_NXST_FLOW_REPLY) {
1264         const struct nx_flow_stats *nfs;
1265         size_t match_len, length;
1266
1267         nfs = ofpbuf_try_pull(msg, sizeof *nfs);
1268         if (!nfs) {
1269             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply has %zu leftover "
1270                          "bytes at end", msg->size);
1271             return EINVAL;
1272         }
1273
1274         length = ntohs(nfs->length);
1275         match_len = ntohs(nfs->match_len);
1276         if (length < sizeof *nfs + ROUND_UP(match_len, 8)) {
1277             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply with match_len=%zu "
1278                          "claims invalid length %zu", match_len, length);
1279             return EINVAL;
1280         }
1281         if (nx_pull_match(msg, match_len, ntohs(nfs->priority), &fs->rule)) {
1282             return EINVAL;
1283         }
1284
1285         if (ofputil_pull_actions(msg,
1286                                  length - sizeof *nfs - ROUND_UP(match_len, 8),
1287                                  &fs->actions, &fs->n_actions)) {
1288             return EINVAL;
1289         }
1290
1291         fs->cookie = nfs->cookie;
1292         fs->table_id = nfs->table_id;
1293         fs->duration_sec = ntohl(nfs->duration_sec);
1294         fs->duration_nsec = ntohl(nfs->duration_nsec);
1295         fs->idle_timeout = ntohs(nfs->idle_timeout);
1296         fs->hard_timeout = ntohs(nfs->hard_timeout);
1297         fs->packet_count = ntohll(nfs->packet_count);
1298         fs->byte_count = ntohll(nfs->byte_count);
1299     } else {
1300         NOT_REACHED();
1301     }
1302
1303     return 0;
1304 }
1305
1306 /* Returns 'count' unchanged except that UINT64_MAX becomes 0.
1307  *
1308  * We use this in situations where OVS internally uses UINT64_MAX to mean
1309  * "value unknown" but OpenFlow 1.0 does not define any unknown value. */
1310 static uint64_t
1311 unknown_to_zero(uint64_t count)
1312 {
1313     return count != UINT64_MAX ? count : 0;
1314 }
1315
1316 /* Appends an OFPST_FLOW or NXST_FLOW reply that contains the data in 'fs' to
1317  * those already present in the list of ofpbufs in 'replies'.  'replies' should
1318  * have been initialized with ofputil_start_stats_reply(). */
1319 void
1320 ofputil_append_flow_stats_reply(const struct ofputil_flow_stats *fs,
1321                                 struct list *replies)
1322 {
1323     size_t act_len = fs->n_actions * sizeof *fs->actions;
1324     const struct ofp_stats_msg *osm;
1325
1326     osm = ofpbuf_from_list(list_back(replies))->data;
1327     if (osm->type == htons(OFPST_FLOW)) {
1328         size_t len = offsetof(struct ofp_flow_stats, actions) + act_len;
1329         struct ofp_flow_stats *ofs;
1330
1331         ofs = ofputil_append_stats_reply(len, replies);
1332         ofs->length = htons(len);
1333         ofs->table_id = fs->table_id;
1334         ofs->pad = 0;
1335         ofputil_cls_rule_to_match(&fs->rule, &ofs->match);
1336         ofs->duration_sec = htonl(fs->duration_sec);
1337         ofs->duration_nsec = htonl(fs->duration_nsec);
1338         ofs->priority = htons(fs->rule.priority);
1339         ofs->idle_timeout = htons(fs->idle_timeout);
1340         ofs->hard_timeout = htons(fs->hard_timeout);
1341         memset(ofs->pad2, 0, sizeof ofs->pad2);
1342         put_32aligned_be64(&ofs->cookie, fs->cookie);
1343         put_32aligned_be64(&ofs->packet_count,
1344                            htonll(unknown_to_zero(fs->packet_count)));
1345         put_32aligned_be64(&ofs->byte_count,
1346                            htonll(unknown_to_zero(fs->byte_count)));
1347         memcpy(ofs->actions, fs->actions, act_len);
1348     } else if (osm->type == htons(OFPST_VENDOR)) {
1349         struct nx_flow_stats *nfs;
1350         struct ofpbuf *msg;
1351         size_t start_len;
1352
1353         msg = ofputil_reserve_stats_reply(
1354             sizeof *nfs + NXM_MAX_LEN + act_len, replies);
1355         start_len = msg->size;
1356
1357         nfs = ofpbuf_put_uninit(msg, sizeof *nfs);
1358         nfs->table_id = fs->table_id;
1359         nfs->pad = 0;
1360         nfs->duration_sec = htonl(fs->duration_sec);
1361         nfs->duration_nsec = htonl(fs->duration_nsec);
1362         nfs->priority = htons(fs->rule.priority);
1363         nfs->idle_timeout = htons(fs->idle_timeout);
1364         nfs->hard_timeout = htons(fs->hard_timeout);
1365         nfs->match_len = htons(nx_put_match(msg, &fs->rule));
1366         memset(nfs->pad2, 0, sizeof nfs->pad2);
1367         nfs->cookie = fs->cookie;
1368         nfs->packet_count = htonll(fs->packet_count);
1369         nfs->byte_count = htonll(fs->byte_count);
1370         ofpbuf_put(msg, fs->actions, act_len);
1371         nfs->length = htons(msg->size - start_len);
1372     } else {
1373         NOT_REACHED();
1374     }
1375 }
1376
1377 /* Converts abstract ofputil_aggregate_stats 'stats' into an OFPST_AGGREGATE or
1378  * NXST_AGGREGATE reply according to 'flow_format', and returns the message. */
1379 struct ofpbuf *
1380 ofputil_encode_aggregate_stats_reply(
1381     const struct ofputil_aggregate_stats *stats,
1382     const struct ofp_stats_msg *request)
1383 {
1384     struct ofpbuf *msg;
1385
1386     if (request->type == htons(OFPST_AGGREGATE)) {
1387         struct ofp_aggregate_stats_reply *asr;
1388
1389         asr = ofputil_make_stats_reply(sizeof *asr, request, &msg);
1390         put_32aligned_be64(&asr->packet_count,
1391                            htonll(unknown_to_zero(stats->packet_count)));
1392         put_32aligned_be64(&asr->byte_count,
1393                            htonll(unknown_to_zero(stats->byte_count)));
1394         asr->flow_count = htonl(stats->flow_count);
1395     } else if (request->type == htons(OFPST_VENDOR)) {
1396         struct nx_aggregate_stats_reply *nasr;
1397
1398         nasr = ofputil_make_stats_reply(sizeof *nasr, request, &msg);
1399         assert(nasr->nsm.subtype == htonl(NXST_AGGREGATE));
1400         nasr->packet_count = htonll(stats->packet_count);
1401         nasr->byte_count = htonll(stats->byte_count);
1402         nasr->flow_count = htonl(stats->flow_count);
1403     } else {
1404         NOT_REACHED();
1405     }
1406
1407     return msg;
1408 }
1409
1410 /* Converts an OFPT_FLOW_REMOVED or NXT_FLOW_REMOVED message 'oh' into an
1411  * abstract ofputil_flow_removed in 'fr'.  Returns 0 if successful, otherwise
1412  * an OpenFlow error code. */
1413 int
1414 ofputil_decode_flow_removed(struct ofputil_flow_removed *fr,
1415                             const struct ofp_header *oh)
1416 {
1417     const struct ofputil_msg_type *type;
1418     enum ofputil_msg_code code;
1419
1420     ofputil_decode_msg_type(oh, &type);
1421     code = ofputil_msg_type_code(type);
1422     if (code == OFPUTIL_OFPT_FLOW_REMOVED) {
1423         const struct ofp_flow_removed *ofr;
1424
1425         ofr = (const struct ofp_flow_removed *) oh;
1426         ofputil_cls_rule_from_match(&ofr->match, ntohs(ofr->priority),
1427                                     &fr->rule);
1428         fr->cookie = ofr->cookie;
1429         fr->reason = ofr->reason;
1430         fr->duration_sec = ntohl(ofr->duration_sec);
1431         fr->duration_nsec = ntohl(ofr->duration_nsec);
1432         fr->idle_timeout = ntohs(ofr->idle_timeout);
1433         fr->packet_count = ntohll(ofr->packet_count);
1434         fr->byte_count = ntohll(ofr->byte_count);
1435     } else if (code == OFPUTIL_NXT_FLOW_REMOVED) {
1436         struct nx_flow_removed *nfr;
1437         struct ofpbuf b;
1438         int error;
1439
1440         ofpbuf_use_const(&b, oh, ntohs(oh->length));
1441
1442         nfr = ofpbuf_pull(&b, sizeof *nfr);
1443         error = nx_pull_match(&b, ntohs(nfr->match_len), ntohs(nfr->priority),
1444                               &fr->rule);
1445         if (error) {
1446             return error;
1447         }
1448         if (b.size) {
1449             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1450         }
1451
1452         fr->cookie = nfr->cookie;
1453         fr->reason = nfr->reason;
1454         fr->duration_sec = ntohl(nfr->duration_sec);
1455         fr->duration_nsec = ntohl(nfr->duration_nsec);
1456         fr->idle_timeout = ntohs(nfr->idle_timeout);
1457         fr->packet_count = ntohll(nfr->packet_count);
1458         fr->byte_count = ntohll(nfr->byte_count);
1459     } else {
1460         NOT_REACHED();
1461     }
1462
1463     return 0;
1464 }
1465
1466 /* Converts abstract ofputil_flow_removed 'fr' into an OFPT_FLOW_REMOVED or
1467  * NXT_FLOW_REMOVED message 'oh' according to 'flow_format', and returns the
1468  * message. */
1469 struct ofpbuf *
1470 ofputil_encode_flow_removed(const struct ofputil_flow_removed *fr,
1471                             enum nx_flow_format flow_format)
1472 {
1473     struct ofpbuf *msg;
1474
1475     if (flow_format == NXFF_OPENFLOW10) {
1476         struct ofp_flow_removed *ofr;
1477
1478         ofr = make_openflow_xid(sizeof *ofr, OFPT_FLOW_REMOVED, htonl(0),
1479                                 &msg);
1480         ofputil_cls_rule_to_match(&fr->rule, &ofr->match);
1481         ofr->cookie = fr->cookie;
1482         ofr->priority = htons(fr->rule.priority);
1483         ofr->reason = fr->reason;
1484         ofr->duration_sec = htonl(fr->duration_sec);
1485         ofr->duration_nsec = htonl(fr->duration_nsec);
1486         ofr->idle_timeout = htons(fr->idle_timeout);
1487         ofr->packet_count = htonll(unknown_to_zero(fr->packet_count));
1488         ofr->byte_count = htonll(unknown_to_zero(fr->byte_count));
1489     } else if (flow_format == NXFF_NXM) {
1490         struct nx_flow_removed *nfr;
1491         int match_len;
1492
1493         make_nxmsg_xid(sizeof *nfr, NXT_FLOW_REMOVED, htonl(0), &msg);
1494         match_len = nx_put_match(msg, &fr->rule);
1495
1496         nfr = msg->data;
1497         nfr->cookie = fr->cookie;
1498         nfr->priority = htons(fr->rule.priority);
1499         nfr->reason = fr->reason;
1500         nfr->duration_sec = htonl(fr->duration_sec);
1501         nfr->duration_nsec = htonl(fr->duration_nsec);
1502         nfr->idle_timeout = htons(fr->idle_timeout);
1503         nfr->match_len = htons(match_len);
1504         nfr->packet_count = htonll(fr->packet_count);
1505         nfr->byte_count = htonll(fr->byte_count);
1506     } else {
1507         NOT_REACHED();
1508     }
1509
1510     return msg;
1511 }
1512
1513 /* Converts abstract ofputil_packet_in 'pin' into an OFPT_PACKET_IN message
1514  * and returns the message.
1515  *
1516  * If 'rw_packet' is NULL, the caller takes ownership of the newly allocated
1517  * returned ofpbuf.
1518  *
1519  * If 'rw_packet' is nonnull, then it must contain the same data as
1520  * pin->packet.  'rw_packet' is allowed to be the same ofpbuf as pin->packet.
1521  * It is modified in-place into an OFPT_PACKET_IN message according to 'pin',
1522  * and then ofputil_encode_packet_in() returns 'rw_packet'.  If 'rw_packet' has
1523  * enough headroom to insert a "struct ofp_packet_in", this is more efficient
1524  * than ofputil_encode_packet_in() because it does not copy the packet
1525  * payload. */
1526 struct ofpbuf *
1527 ofputil_encode_packet_in(const struct ofputil_packet_in *pin,
1528                         struct ofpbuf *rw_packet)
1529 {
1530     int total_len = pin->packet->size;
1531     struct ofp_packet_in opi;
1532
1533     if (rw_packet) {
1534         if (pin->send_len < rw_packet->size) {
1535             rw_packet->size = pin->send_len;
1536         }
1537     } else {
1538         rw_packet = ofpbuf_clone_data_with_headroom(
1539             pin->packet->data, MIN(pin->send_len, pin->packet->size),
1540             offsetof(struct ofp_packet_in, data));
1541     }
1542
1543     /* Add OFPT_PACKET_IN. */
1544     memset(&opi, 0, sizeof opi);
1545     opi.header.version = OFP_VERSION;
1546     opi.header.type = OFPT_PACKET_IN;
1547     opi.total_len = htons(total_len);
1548     opi.in_port = htons(pin->in_port);
1549     opi.reason = pin->reason;
1550     opi.buffer_id = htonl(pin->buffer_id);
1551     ofpbuf_push(rw_packet, &opi, offsetof(struct ofp_packet_in, data));
1552     update_openflow_length(rw_packet);
1553
1554     return rw_packet;
1555 }
1556
1557 /* Returns a string representing the message type of 'type'.  The string is the
1558  * enumeration constant for the type, e.g. "OFPT_HELLO".  For statistics
1559  * messages, the constant is followed by "request" or "reply",
1560  * e.g. "OFPST_AGGREGATE reply". */
1561 const char *
1562 ofputil_msg_type_name(const struct ofputil_msg_type *type)
1563 {
1564     return type->name;
1565 }
1566 \f
1567 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
1568  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
1569  * an arbitrary transaction id.  Allocated bytes beyond the header, if any, are
1570  * zeroed.
1571  *
1572  * The caller is responsible for freeing '*bufferp' when it is no longer
1573  * needed.
1574  *
1575  * The OpenFlow header length is initially set to 'openflow_len'; if the
1576  * message is later extended, the length should be updated with
1577  * update_openflow_length() before sending.
1578  *
1579  * Returns the header. */
1580 void *
1581 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp)
1582 {
1583     *bufferp = ofpbuf_new(openflow_len);
1584     return put_openflow_xid(openflow_len, type, alloc_xid(), *bufferp);
1585 }
1586
1587 /* Similar to make_openflow() but creates a Nicira vendor extension message
1588  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1589 void *
1590 make_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf **bufferp)
1591 {
1592     return make_nxmsg_xid(openflow_len, subtype, alloc_xid(), bufferp);
1593 }
1594
1595 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
1596  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
1597  * transaction id 'xid'.  Allocated bytes beyond the header, if any, are
1598  * zeroed.
1599  *
1600  * The caller is responsible for freeing '*bufferp' when it is no longer
1601  * needed.
1602  *
1603  * The OpenFlow header length is initially set to 'openflow_len'; if the
1604  * message is later extended, the length should be updated with
1605  * update_openflow_length() before sending.
1606  *
1607  * Returns the header. */
1608 void *
1609 make_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
1610                   struct ofpbuf **bufferp)
1611 {
1612     *bufferp = ofpbuf_new(openflow_len);
1613     return put_openflow_xid(openflow_len, type, xid, *bufferp);
1614 }
1615
1616 /* Similar to make_openflow_xid() but creates a Nicira vendor extension message
1617  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1618 void *
1619 make_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
1620                struct ofpbuf **bufferp)
1621 {
1622     *bufferp = ofpbuf_new(openflow_len);
1623     return put_nxmsg_xid(openflow_len, subtype, xid, *bufferp);
1624 }
1625
1626 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
1627  * with the given 'type' and an arbitrary transaction id.  Allocated bytes
1628  * beyond the header, if any, are zeroed.
1629  *
1630  * The OpenFlow header length is initially set to 'openflow_len'; if the
1631  * message is later extended, the length should be updated with
1632  * update_openflow_length() before sending.
1633  *
1634  * Returns the header. */
1635 void *
1636 put_openflow(size_t openflow_len, uint8_t type, struct ofpbuf *buffer)
1637 {
1638     return put_openflow_xid(openflow_len, type, alloc_xid(), buffer);
1639 }
1640
1641 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
1642  * with the given 'type' and an transaction id 'xid'.  Allocated bytes beyond
1643  * the header, if any, are zeroed.
1644  *
1645  * The OpenFlow header length is initially set to 'openflow_len'; if the
1646  * message is later extended, the length should be updated with
1647  * update_openflow_length() before sending.
1648  *
1649  * Returns the header. */
1650 void *
1651 put_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
1652                  struct ofpbuf *buffer)
1653 {
1654     struct ofp_header *oh;
1655
1656     assert(openflow_len >= sizeof *oh);
1657     assert(openflow_len <= UINT16_MAX);
1658
1659     oh = ofpbuf_put_uninit(buffer, openflow_len);
1660     oh->version = OFP_VERSION;
1661     oh->type = type;
1662     oh->length = htons(openflow_len);
1663     oh->xid = xid;
1664     memset(oh + 1, 0, openflow_len - sizeof *oh);
1665     return oh;
1666 }
1667
1668 /* Similar to put_openflow() but append a Nicira vendor extension message with
1669  * the specific 'subtype'.  'subtype' should be in host byte order. */
1670 void *
1671 put_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf *buffer)
1672 {
1673     return put_nxmsg_xid(openflow_len, subtype, alloc_xid(), buffer);
1674 }
1675
1676 /* Similar to put_openflow_xid() but append a Nicira vendor extension message
1677  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1678 void *
1679 put_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
1680               struct ofpbuf *buffer)
1681 {
1682     struct nicira_header *nxh;
1683
1684     nxh = put_openflow_xid(openflow_len, OFPT_VENDOR, xid, buffer);
1685     nxh->vendor = htonl(NX_VENDOR_ID);
1686     nxh->subtype = htonl(subtype);
1687     return nxh;
1688 }
1689
1690 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
1691  * 'buffer->size'. */
1692 void
1693 update_openflow_length(struct ofpbuf *buffer)
1694 {
1695     struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
1696     oh->length = htons(buffer->size);
1697 }
1698
1699 static void
1700 put_stats__(ovs_be32 xid, uint8_t ofp_type,
1701             ovs_be16 ofpst_type, ovs_be32 nxst_subtype,
1702             struct ofpbuf *msg)
1703 {
1704     if (ofpst_type == htons(OFPST_VENDOR)) {
1705         struct nicira_stats_msg *nsm;
1706
1707         nsm = put_openflow_xid(sizeof *nsm, ofp_type, xid, msg);
1708         nsm->vsm.osm.type = ofpst_type;
1709         nsm->vsm.vendor = htonl(NX_VENDOR_ID);
1710         nsm->subtype = nxst_subtype;
1711     } else {
1712         struct ofp_stats_msg *osm;
1713
1714         osm = put_openflow_xid(sizeof *osm, ofp_type, xid, msg);
1715         osm->type = ofpst_type;
1716     }
1717 }
1718
1719 /* Creates a statistics request message with total length 'openflow_len'
1720  * (including all headers) and the given 'ofpst_type', and stores the buffer
1721  * containing the new message in '*bufferp'.  If 'ofpst_type' is OFPST_VENDOR
1722  * then 'nxst_subtype' is used as the Nicira vendor extension statistics
1723  * subtype (otherwise 'nxst_subtype' is ignored).
1724  *
1725  * Initializes bytes following the headers to all-bits-zero.
1726  *
1727  * Returns the first byte of the new message. */
1728 void *
1729 ofputil_make_stats_request(size_t openflow_len, uint16_t ofpst_type,
1730                            uint32_t nxst_subtype, struct ofpbuf **bufferp)
1731 {
1732     struct ofpbuf *msg;
1733
1734     msg = *bufferp = ofpbuf_new(openflow_len);
1735     put_stats__(alloc_xid(), OFPT_STATS_REQUEST,
1736                 htons(ofpst_type), htonl(nxst_subtype), msg);
1737     ofpbuf_padto(msg, openflow_len);
1738
1739     return msg->data;
1740 }
1741
1742 static void
1743 put_stats_reply__(const struct ofp_stats_msg *request, struct ofpbuf *msg)
1744 {
1745     assert(request->header.type == OFPT_STATS_REQUEST ||
1746            request->header.type == OFPT_STATS_REPLY);
1747     put_stats__(request->header.xid, OFPT_STATS_REPLY, request->type,
1748                 (request->type != htons(OFPST_VENDOR)
1749                  ? htonl(0)
1750                  : ((const struct nicira_stats_msg *) request)->subtype),
1751                 msg);
1752 }
1753
1754 /* Creates a statistics reply message with total length 'openflow_len'
1755  * (including all headers) and the same type (either a standard OpenFlow
1756  * statistics type or a Nicira extension type and subtype) as 'request', and
1757  * stores the buffer containing the new message in '*bufferp'.
1758  *
1759  * Initializes bytes following the headers to all-bits-zero.
1760  *
1761  * Returns the first byte of the new message. */
1762 void *
1763 ofputil_make_stats_reply(size_t openflow_len,
1764                          const struct ofp_stats_msg *request,
1765                          struct ofpbuf **bufferp)
1766 {
1767     struct ofpbuf *msg;
1768
1769     msg = *bufferp = ofpbuf_new(openflow_len);
1770     put_stats_reply__(request, msg);
1771     ofpbuf_padto(msg, openflow_len);
1772
1773     return msg->data;
1774 }
1775
1776 /* Initializes 'replies' as a list of ofpbufs that will contain a series of
1777  * replies to 'request', which should be an OpenFlow or Nicira extension
1778  * statistics request.  Initially 'replies' will have a single reply message
1779  * that has only a header.  The functions ofputil_reserve_stats_reply() and
1780  * ofputil_append_stats_reply() may be used to add to the reply. */
1781 void
1782 ofputil_start_stats_reply(const struct ofp_stats_msg *request,
1783                           struct list *replies)
1784 {
1785     struct ofpbuf *msg;
1786
1787     msg = ofpbuf_new(1024);
1788     put_stats_reply__(request, msg);
1789
1790     list_init(replies);
1791     list_push_back(replies, &msg->list_node);
1792 }
1793
1794 /* Prepares to append up to 'len' bytes to the series of statistics replies in
1795  * 'replies', which should have been initialized with
1796  * ofputil_start_stats_reply().  Returns an ofpbuf with at least 'len' bytes of
1797  * tailroom.  (The 'len' bytes have not actually be allocated; the caller must
1798  * do so with e.g. ofpbuf_put_uninit().) */
1799 struct ofpbuf *
1800 ofputil_reserve_stats_reply(size_t len, struct list *replies)
1801 {
1802     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
1803     struct ofp_stats_msg *osm = msg->data;
1804
1805     if (msg->size + len <= UINT16_MAX) {
1806         ofpbuf_prealloc_tailroom(msg, len);
1807     } else {
1808         osm->flags |= htons(OFPSF_REPLY_MORE);
1809
1810         msg = ofpbuf_new(MAX(1024, sizeof(struct nicira_stats_msg) + len));
1811         put_stats_reply__(osm, msg);
1812         list_push_back(replies, &msg->list_node);
1813     }
1814     return msg;
1815 }
1816
1817 /* Appends 'len' bytes to the series of statistics replies in 'replies', and
1818  * returns the first byte. */
1819 void *
1820 ofputil_append_stats_reply(size_t len, struct list *replies)
1821 {
1822     return ofpbuf_put_uninit(ofputil_reserve_stats_reply(len, replies), len);
1823 }
1824
1825 /* Returns the first byte past the ofp_stats_msg header in 'oh'. */
1826 const void *
1827 ofputil_stats_body(const struct ofp_header *oh)
1828 {
1829     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1830     return (const struct ofp_stats_msg *) oh + 1;
1831 }
1832
1833 /* Returns the number of bytes past the ofp_stats_msg header in 'oh'. */
1834 size_t
1835 ofputil_stats_body_len(const struct ofp_header *oh)
1836 {
1837     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1838     return ntohs(oh->length) - sizeof(struct ofp_stats_msg);
1839 }
1840
1841 /* Returns the first byte past the nicira_stats_msg header in 'oh'. */
1842 const void *
1843 ofputil_nxstats_body(const struct ofp_header *oh)
1844 {
1845     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1846     return ((const struct nicira_stats_msg *) oh) + 1;
1847 }
1848
1849 /* Returns the number of bytes past the nicira_stats_msg header in 'oh'. */
1850 size_t
1851 ofputil_nxstats_body_len(const struct ofp_header *oh)
1852 {
1853     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1854     return ntohs(oh->length) - sizeof(struct nicira_stats_msg);
1855 }
1856
1857 struct ofpbuf *
1858 make_flow_mod(uint16_t command, const struct cls_rule *rule,
1859               size_t actions_len)
1860 {
1861     struct ofp_flow_mod *ofm;
1862     size_t size = sizeof *ofm + actions_len;
1863     struct ofpbuf *out = ofpbuf_new(size);
1864     ofm = ofpbuf_put_zeros(out, sizeof *ofm);
1865     ofm->header.version = OFP_VERSION;
1866     ofm->header.type = OFPT_FLOW_MOD;
1867     ofm->header.length = htons(size);
1868     ofm->cookie = 0;
1869     ofm->priority = htons(MIN(rule->priority, UINT16_MAX));
1870     ofputil_cls_rule_to_match(rule, &ofm->match);
1871     ofm->command = htons(command);
1872     return out;
1873 }
1874
1875 struct ofpbuf *
1876 make_add_flow(const struct cls_rule *rule, uint32_t buffer_id,
1877               uint16_t idle_timeout, size_t actions_len)
1878 {
1879     struct ofpbuf *out = make_flow_mod(OFPFC_ADD, rule, actions_len);
1880     struct ofp_flow_mod *ofm = out->data;
1881     ofm->idle_timeout = htons(idle_timeout);
1882     ofm->hard_timeout = htons(OFP_FLOW_PERMANENT);
1883     ofm->buffer_id = htonl(buffer_id);
1884     return out;
1885 }
1886
1887 struct ofpbuf *
1888 make_del_flow(const struct cls_rule *rule)
1889 {
1890     struct ofpbuf *out = make_flow_mod(OFPFC_DELETE_STRICT, rule, 0);
1891     struct ofp_flow_mod *ofm = out->data;
1892     ofm->out_port = htons(OFPP_NONE);
1893     return out;
1894 }
1895
1896 struct ofpbuf *
1897 make_add_simple_flow(const struct cls_rule *rule,
1898                      uint32_t buffer_id, uint16_t out_port,
1899                      uint16_t idle_timeout)
1900 {
1901     if (out_port != OFPP_NONE) {
1902         struct ofp_action_output *oao;
1903         struct ofpbuf *buffer;
1904
1905         buffer = make_add_flow(rule, buffer_id, idle_timeout, sizeof *oao);
1906         ofputil_put_OFPAT_OUTPUT(buffer)->port = htons(out_port);
1907         return buffer;
1908     } else {
1909         return make_add_flow(rule, buffer_id, idle_timeout, 0);
1910     }
1911 }
1912
1913 struct ofpbuf *
1914 make_packet_in(uint32_t buffer_id, uint16_t in_port, uint8_t reason,
1915                const struct ofpbuf *payload, int max_send_len)
1916 {
1917     struct ofp_packet_in *opi;
1918     struct ofpbuf *buf;
1919     int send_len;
1920
1921     send_len = MIN(max_send_len, payload->size);
1922     buf = ofpbuf_new(sizeof *opi + send_len);
1923     opi = put_openflow_xid(offsetof(struct ofp_packet_in, data),
1924                            OFPT_PACKET_IN, 0, buf);
1925     opi->buffer_id = htonl(buffer_id);
1926     opi->total_len = htons(payload->size);
1927     opi->in_port = htons(in_port);
1928     opi->reason = reason;
1929     ofpbuf_put(buf, payload->data, send_len);
1930     update_openflow_length(buf);
1931
1932     return buf;
1933 }
1934
1935 struct ofpbuf *
1936 make_packet_out(const struct ofpbuf *packet, uint32_t buffer_id,
1937                 uint16_t in_port,
1938                 const struct ofp_action_header *actions, size_t n_actions)
1939 {
1940     size_t actions_len = n_actions * sizeof *actions;
1941     struct ofp_packet_out *opo;
1942     size_t size = sizeof *opo + actions_len + (packet ? packet->size : 0);
1943     struct ofpbuf *out = ofpbuf_new(size);
1944
1945     opo = ofpbuf_put_uninit(out, sizeof *opo);
1946     opo->header.version = OFP_VERSION;
1947     opo->header.type = OFPT_PACKET_OUT;
1948     opo->header.length = htons(size);
1949     opo->header.xid = htonl(0);
1950     opo->buffer_id = htonl(buffer_id);
1951     opo->in_port = htons(in_port);
1952     opo->actions_len = htons(actions_len);
1953     ofpbuf_put(out, actions, actions_len);
1954     if (packet) {
1955         ofpbuf_put(out, packet->data, packet->size);
1956     }
1957     return out;
1958 }
1959
1960 struct ofpbuf *
1961 make_unbuffered_packet_out(const struct ofpbuf *packet,
1962                            uint16_t in_port, uint16_t out_port)
1963 {
1964     struct ofp_action_output action;
1965     action.type = htons(OFPAT_OUTPUT);
1966     action.len = htons(sizeof action);
1967     action.port = htons(out_port);
1968     return make_packet_out(packet, UINT32_MAX, in_port,
1969                            (struct ofp_action_header *) &action, 1);
1970 }
1971
1972 struct ofpbuf *
1973 make_buffered_packet_out(uint32_t buffer_id,
1974                          uint16_t in_port, uint16_t out_port)
1975 {
1976     if (out_port != OFPP_NONE) {
1977         struct ofp_action_output action;
1978         action.type = htons(OFPAT_OUTPUT);
1979         action.len = htons(sizeof action);
1980         action.port = htons(out_port);
1981         return make_packet_out(NULL, buffer_id, in_port,
1982                                (struct ofp_action_header *) &action, 1);
1983     } else {
1984         return make_packet_out(NULL, buffer_id, in_port, NULL, 0);
1985     }
1986 }
1987
1988 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
1989 struct ofpbuf *
1990 make_echo_request(void)
1991 {
1992     struct ofp_header *rq;
1993     struct ofpbuf *out = ofpbuf_new(sizeof *rq);
1994     rq = ofpbuf_put_uninit(out, sizeof *rq);
1995     rq->version = OFP_VERSION;
1996     rq->type = OFPT_ECHO_REQUEST;
1997     rq->length = htons(sizeof *rq);
1998     rq->xid = htonl(0);
1999     return out;
2000 }
2001
2002 /* Creates and returns an OFPT_ECHO_REPLY message matching the
2003  * OFPT_ECHO_REQUEST message in 'rq'. */
2004 struct ofpbuf *
2005 make_echo_reply(const struct ofp_header *rq)
2006 {
2007     size_t size = ntohs(rq->length);
2008     struct ofpbuf *out = ofpbuf_new(size);
2009     struct ofp_header *reply = ofpbuf_put(out, rq, size);
2010     reply->type = OFPT_ECHO_REPLY;
2011     return out;
2012 }
2013
2014 const char *
2015 ofputil_frag_handling_to_string(enum ofp_config_flags flags)
2016 {
2017     switch (flags & OFPC_FRAG_MASK) {
2018     case OFPC_FRAG_NORMAL:   return "normal";
2019     case OFPC_FRAG_DROP:     return "drop";
2020     case OFPC_FRAG_REASM:    return "reassemble";
2021     case OFPC_FRAG_NX_MATCH: return "nx-match";
2022     }
2023
2024     NOT_REACHED();
2025 }
2026
2027 bool
2028 ofputil_frag_handling_from_string(const char *s, enum ofp_config_flags *flags)
2029 {
2030     if (!strcasecmp(s, "normal")) {
2031         *flags = OFPC_FRAG_NORMAL;
2032     } else if (!strcasecmp(s, "drop")) {
2033         *flags = OFPC_FRAG_DROP;
2034     } else if (!strcasecmp(s, "reassemble")) {
2035         *flags = OFPC_FRAG_REASM;
2036     } else if (!strcasecmp(s, "nx-match")) {
2037         *flags = OFPC_FRAG_NX_MATCH;
2038     } else {
2039         return false;
2040     }
2041     return true;
2042 }
2043
2044 /* Checks that 'port' is a valid output port for the OFPAT_OUTPUT action, given
2045  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
2046  * 'port' is valid, otherwise an ofp_mkerr() return code. */
2047 int
2048 ofputil_check_output_port(uint16_t port, int max_ports)
2049 {
2050     switch (port) {
2051     case OFPP_IN_PORT:
2052     case OFPP_TABLE:
2053     case OFPP_NORMAL:
2054     case OFPP_FLOOD:
2055     case OFPP_ALL:
2056     case OFPP_CONTROLLER:
2057     case OFPP_LOCAL:
2058         return 0;
2059
2060     default:
2061         if (port < max_ports) {
2062             return 0;
2063         }
2064         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
2065     }
2066 }
2067
2068 #define OFPUTIL_NAMED_PORTS                     \
2069         OFPUTIL_NAMED_PORT(IN_PORT)             \
2070         OFPUTIL_NAMED_PORT(TABLE)               \
2071         OFPUTIL_NAMED_PORT(NORMAL)              \
2072         OFPUTIL_NAMED_PORT(FLOOD)               \
2073         OFPUTIL_NAMED_PORT(ALL)                 \
2074         OFPUTIL_NAMED_PORT(CONTROLLER)          \
2075         OFPUTIL_NAMED_PORT(LOCAL)               \
2076         OFPUTIL_NAMED_PORT(NONE)
2077
2078 /* Checks whether 's' is the string representation of an OpenFlow port number,
2079  * either as an integer or a string name (e.g. "LOCAL").  If it is, stores the
2080  * number in '*port' and returns true.  Otherwise, returns false. */
2081 bool
2082 ofputil_port_from_string(const char *name, uint16_t *port)
2083 {
2084     struct pair {
2085         const char *name;
2086         uint16_t value;
2087     };
2088     static const struct pair pairs[] = {
2089 #define OFPUTIL_NAMED_PORT(NAME) {#NAME, OFPP_##NAME},
2090         OFPUTIL_NAMED_PORTS
2091 #undef OFPUTIL_NAMED_PORT
2092     };
2093     static const int n_pairs = ARRAY_SIZE(pairs);
2094     int i;
2095
2096     if (str_to_int(name, 0, &i) && i >= 0 && i < UINT16_MAX) {
2097         *port = i;
2098         return true;
2099     }
2100
2101     for (i = 0; i < n_pairs; i++) {
2102         if (!strcasecmp(name, pairs[i].name)) {
2103             *port = pairs[i].value;
2104             return true;
2105         }
2106     }
2107     return false;
2108 }
2109
2110 /* Appends to 's' a string representation of the OpenFlow port number 'port'.
2111  * Most ports' string representation is just the port number, but for special
2112  * ports, e.g. OFPP_LOCAL, it is the name, e.g. "LOCAL". */
2113 void
2114 ofputil_format_port(uint16_t port, struct ds *s)
2115 {
2116     const char *name;
2117
2118     switch (port) {
2119 #define OFPUTIL_NAMED_PORT(NAME) case OFPP_##NAME: name = #NAME; break;
2120         OFPUTIL_NAMED_PORTS
2121 #undef OFPUTIL_NAMED_PORT
2122
2123     default:
2124         ds_put_format(s, "%"PRIu16, port);
2125         return;
2126     }
2127     ds_put_cstr(s, name);
2128 }
2129
2130 static int
2131 check_resubmit_table(const struct nx_action_resubmit *nar)
2132 {
2133     if (nar->pad[0] || nar->pad[1] || nar->pad[2]) {
2134         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
2135     }
2136     return 0;
2137 }
2138
2139 static int
2140 check_output_reg(const struct nx_action_output_reg *naor,
2141                  const struct flow *flow)
2142 {
2143     size_t i;
2144
2145     for (i = 0; i < sizeof naor->zero; i++) {
2146         if (naor->zero[i]) {
2147             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
2148         }
2149     }
2150
2151     return nxm_src_check(naor->src, nxm_decode_ofs(naor->ofs_nbits),
2152                          nxm_decode_n_bits(naor->ofs_nbits), flow);
2153 }
2154
2155 int
2156 validate_actions(const union ofp_action *actions, size_t n_actions,
2157                  const struct flow *flow, int max_ports)
2158 {
2159     const union ofp_action *a;
2160     size_t left;
2161
2162     OFPUTIL_ACTION_FOR_EACH (a, left, actions, n_actions) {
2163         uint16_t port;
2164         int error;
2165         int code;
2166
2167         code = ofputil_decode_action(a);
2168         if (code < 0) {
2169             char *msg;
2170
2171             error = -code;
2172             msg = ofputil_error_to_string(error);
2173             VLOG_WARN_RL(&bad_ofmsg_rl,
2174                          "action decoding error at offset %td (%s)",
2175                          (a - actions) * sizeof *a, msg);
2176             free(msg);
2177
2178             return error;
2179         }
2180
2181         error = 0;
2182         switch ((enum ofputil_action_code) code) {
2183         case OFPUTIL_OFPAT_OUTPUT:
2184             error = ofputil_check_output_port(ntohs(a->output.port),
2185                                               max_ports);
2186             break;
2187
2188         case OFPUTIL_OFPAT_SET_VLAN_VID:
2189             if (a->vlan_vid.vlan_vid & ~htons(0xfff)) {
2190                 error = ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
2191             }
2192             break;
2193
2194         case OFPUTIL_OFPAT_SET_VLAN_PCP:
2195             if (a->vlan_pcp.vlan_pcp & ~7) {
2196                 error = ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
2197             }
2198             break;
2199
2200         case OFPUTIL_OFPAT_ENQUEUE:
2201             port = ntohs(((const struct ofp_action_enqueue *) a)->port);
2202             if (port >= max_ports && port != OFPP_IN_PORT) {
2203                 error = ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
2204             }
2205             break;
2206
2207         case OFPUTIL_NXAST_REG_MOVE:
2208             error = nxm_check_reg_move((const struct nx_action_reg_move *) a,
2209                                        flow);
2210             break;
2211
2212         case OFPUTIL_NXAST_REG_LOAD:
2213             error = nxm_check_reg_load((const struct nx_action_reg_load *) a,
2214                                        flow);
2215             break;
2216
2217         case OFPUTIL_NXAST_MULTIPATH:
2218             error = multipath_check((const struct nx_action_multipath *) a,
2219                                     flow);
2220             break;
2221
2222         case OFPUTIL_NXAST_AUTOPATH:
2223             error = autopath_check((const struct nx_action_autopath *) a,
2224                                    flow);
2225             break;
2226
2227         case OFPUTIL_NXAST_BUNDLE:
2228         case OFPUTIL_NXAST_BUNDLE_LOAD:
2229             error = bundle_check((const struct nx_action_bundle *) a,
2230                                  max_ports, flow);
2231             break;
2232
2233         case OFPUTIL_NXAST_OUTPUT_REG:
2234             error = check_output_reg((const struct nx_action_output_reg *) a,
2235                                      flow);
2236             break;
2237
2238         case OFPUTIL_NXAST_RESUBMIT_TABLE:
2239             error = check_resubmit_table(
2240                 (const struct nx_action_resubmit *) a);
2241             break;
2242
2243         case OFPUTIL_NXAST_LEARN:
2244             error = learn_check((const struct nx_action_learn *) a, flow);
2245             break;
2246
2247         case OFPUTIL_OFPAT_STRIP_VLAN:
2248         case OFPUTIL_OFPAT_SET_NW_SRC:
2249         case OFPUTIL_OFPAT_SET_NW_DST:
2250         case OFPUTIL_OFPAT_SET_NW_TOS:
2251         case OFPUTIL_OFPAT_SET_TP_SRC:
2252         case OFPUTIL_OFPAT_SET_TP_DST:
2253         case OFPUTIL_OFPAT_SET_DL_SRC:
2254         case OFPUTIL_OFPAT_SET_DL_DST:
2255         case OFPUTIL_NXAST_RESUBMIT:
2256         case OFPUTIL_NXAST_SET_TUNNEL:
2257         case OFPUTIL_NXAST_SET_QUEUE:
2258         case OFPUTIL_NXAST_POP_QUEUE:
2259         case OFPUTIL_NXAST_NOTE:
2260         case OFPUTIL_NXAST_SET_TUNNEL64:
2261         case OFPUTIL_NXAST_EXIT:
2262             break;
2263         }
2264
2265         if (error) {
2266             char *msg = ofputil_error_to_string(error);
2267             VLOG_WARN_RL(&bad_ofmsg_rl, "bad action at offset %td (%s)",
2268                          (a - actions) * sizeof *a, msg);
2269             free(msg);
2270             return error;
2271         }
2272     }
2273     if (left) {
2274         VLOG_WARN_RL(&bad_ofmsg_rl, "bad action format at offset %zu",
2275                      (n_actions - left) * sizeof *a);
2276         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
2277     }
2278     return 0;
2279 }
2280
2281 struct ofputil_action {
2282     int code;
2283     unsigned int min_len;
2284     unsigned int max_len;
2285 };
2286
2287 static const struct ofputil_action action_bad_type
2288     = { -OFP_MKERR(OFPET_BAD_ACTION, OFPBAC_BAD_TYPE),   0, UINT_MAX };
2289 static const struct ofputil_action action_bad_len
2290     = { -OFP_MKERR(OFPET_BAD_ACTION, OFPBAC_BAD_LEN),    0, UINT_MAX };
2291 static const struct ofputil_action action_bad_vendor
2292     = { -OFP_MKERR(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR), 0, UINT_MAX };
2293
2294 static const struct ofputil_action *
2295 ofputil_decode_ofpat_action(const union ofp_action *a)
2296 {
2297     enum ofp_action_type type = ntohs(a->type);
2298
2299     switch (type) {
2300 #define OFPAT_ACTION(ENUM, STRUCT, NAME)                    \
2301         case ENUM: {                                        \
2302             static const struct ofputil_action action = {   \
2303                 OFPUTIL_##ENUM,                             \
2304                 sizeof(struct STRUCT),                      \
2305                 sizeof(struct STRUCT)                       \
2306             };                                              \
2307             return &action;                                 \
2308         }
2309 #include "ofp-util.def"
2310
2311     case OFPAT_VENDOR:
2312     default:
2313         return &action_bad_type;
2314     }
2315 }
2316
2317 static const struct ofputil_action *
2318 ofputil_decode_nxast_action(const union ofp_action *a)
2319 {
2320     const struct nx_action_header *nah = (const struct nx_action_header *) a;
2321     enum nx_action_subtype subtype = ntohs(nah->subtype);
2322
2323     switch (subtype) {
2324 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)            \
2325         case ENUM: {                                            \
2326             static const struct ofputil_action action = {       \
2327                 OFPUTIL_##ENUM,                                 \
2328                 sizeof(struct STRUCT),                          \
2329                 EXTENSIBLE ? UINT_MAX : sizeof(struct STRUCT)   \
2330             };                                                  \
2331             return &action;                                     \
2332         }
2333 #include "ofp-util.def"
2334
2335     case NXAST_SNAT__OBSOLETE:
2336     case NXAST_DROP_SPOOFED_ARP__OBSOLETE:
2337     default:
2338         return &action_bad_type;
2339     }
2340 }
2341
2342 /* Parses 'a' to determine its type.  Returns a nonnegative OFPUTIL_OFPAT_* or
2343  * OFPUTIL_NXAST_* constant if successful, otherwise a negative OpenFlow error
2344  * code (as returned by ofp_mkerr()).
2345  *
2346  * The caller must have already verified that 'a''s length is correct (that is,
2347  * a->header.len is nonzero and a multiple of sizeof(union ofp_action) and no
2348  * longer than the amount of space allocated to 'a').
2349  *
2350  * This function verifies that 'a''s length is correct for the type of action
2351  * that it represents. */
2352 int
2353 ofputil_decode_action(const union ofp_action *a)
2354 {
2355     const struct ofputil_action *action;
2356     uint16_t len = ntohs(a->header.len);
2357
2358     if (a->type != htons(OFPAT_VENDOR)) {
2359         action = ofputil_decode_ofpat_action(a);
2360     } else {
2361         switch (ntohl(a->vendor.vendor)) {
2362         case NX_VENDOR_ID:
2363             if (len < sizeof(struct nx_action_header)) {
2364                 return -ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
2365             }
2366             action = ofputil_decode_nxast_action(a);
2367             break;
2368         default:
2369             action = &action_bad_vendor;
2370             break;
2371         }
2372     }
2373
2374     return (len >= action->min_len && len <= action->max_len
2375             ? action->code
2376             : -ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN));
2377 }
2378
2379 /* Parses 'a' and returns its type as an OFPUTIL_OFPAT_* or OFPUTIL_NXAST_*
2380  * constant.  The caller must have already validated that 'a' is a valid action
2381  * understood by Open vSwitch (e.g. by a previous successful call to
2382  * ofputil_decode_action()). */
2383 enum ofputil_action_code
2384 ofputil_decode_action_unsafe(const union ofp_action *a)
2385 {
2386     const struct ofputil_action *action;
2387
2388     if (a->type != htons(OFPAT_VENDOR)) {
2389         action = ofputil_decode_ofpat_action(a);
2390     } else {
2391         action = ofputil_decode_nxast_action(a);
2392     }
2393
2394     return action->code;
2395 }
2396
2397 /* Returns the 'enum ofputil_action_code' corresponding to 'name' (e.g. if
2398  * 'name' is "output" then the return value is OFPUTIL_OFPAT_OUTPUT), or -1 if
2399  * 'name' is not the name of any action.
2400  *
2401  * ofp-util.def lists the mapping from names to action. */
2402 int
2403 ofputil_action_code_from_name(const char *name)
2404 {
2405     static const char *names[OFPUTIL_N_ACTIONS] = {
2406 #define OFPAT_ACTION(ENUM, STRUCT, NAME)             NAME,
2407 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) NAME,
2408 #include "ofp-util.def"
2409     };
2410
2411     const char **p;
2412
2413     for (p = names; p < &names[ARRAY_SIZE(names)]; p++) {
2414         if (*p && !strcasecmp(name, *p)) {
2415             return p - names;
2416         }
2417     }
2418     return -1;
2419 }
2420
2421 /* Appends an action of the type specified by 'code' to 'buf' and returns the
2422  * action.  Initializes the parts of 'action' that identify it as having type
2423  * <ENUM> and length 'sizeof *action' and zeros the rest.  For actions that
2424  * have variable length, the length used and cleared is that of struct
2425  * <STRUCT>.  */
2426 void *
2427 ofputil_put_action(enum ofputil_action_code code, struct ofpbuf *buf)
2428 {
2429     switch (code) {
2430 #define OFPAT_ACTION(ENUM, STRUCT, NAME)                    \
2431     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
2432 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)        \
2433     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
2434 #include "ofp-util.def"
2435     }
2436     NOT_REACHED();
2437 }
2438
2439 #define OFPAT_ACTION(ENUM, STRUCT, NAME)                        \
2440     void                                                        \
2441     ofputil_init_##ENUM(struct STRUCT *s)                       \
2442     {                                                           \
2443         memset(s, 0, sizeof *s);                                \
2444         s->type = htons(ENUM);                                  \
2445         s->len = htons(sizeof *s);                              \
2446     }                                                           \
2447                                                                 \
2448     struct STRUCT *                                             \
2449     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
2450     {                                                           \
2451         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
2452         ofputil_init_##ENUM(s);                                 \
2453         return s;                                               \
2454     }
2455 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)            \
2456     void                                                        \
2457     ofputil_init_##ENUM(struct STRUCT *s)                       \
2458     {                                                           \
2459         memset(s, 0, sizeof *s);                                \
2460         s->type = htons(OFPAT_VENDOR);                          \
2461         s->len = htons(sizeof *s);                              \
2462         s->vendor = htonl(NX_VENDOR_ID);                        \
2463         s->subtype = htons(ENUM);                               \
2464     }                                                           \
2465                                                                 \
2466     struct STRUCT *                                             \
2467     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
2468     {                                                           \
2469         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
2470         ofputil_init_##ENUM(s);                                 \
2471         return s;                                               \
2472     }
2473 #include "ofp-util.def"
2474
2475 /* Returns true if 'action' outputs to 'port', false otherwise. */
2476 bool
2477 action_outputs_to_port(const union ofp_action *action, ovs_be16 port)
2478 {
2479     switch (ntohs(action->type)) {
2480     case OFPAT_OUTPUT:
2481         return action->output.port == port;
2482     case OFPAT_ENQUEUE:
2483         return ((const struct ofp_action_enqueue *) action)->port == port;
2484     default:
2485         return false;
2486     }
2487 }
2488
2489 /* "Normalizes" the wildcards in 'rule'.  That means:
2490  *
2491  *    1. If the type of level N is known, then only the valid fields for that
2492  *       level may be specified.  For example, ARP does not have a TOS field,
2493  *       so nw_tos must be wildcarded if 'rule' specifies an ARP flow.
2494  *       Similarly, IPv4 does not have any IPv6 addresses, so ipv6_src and
2495  *       ipv6_dst (and other fields) must be wildcarded if 'rule' specifies an
2496  *       IPv4 flow.
2497  *
2498  *    2. If the type of level N is not known (or not understood by Open
2499  *       vSwitch), then no fields at all for that level may be specified.  For
2500  *       example, Open vSwitch does not understand SCTP, an L4 protocol, so the
2501  *       L4 fields tp_src and tp_dst must be wildcarded if 'rule' specifies an
2502  *       SCTP flow.
2503  *
2504  * 'flow_format' specifies the format of the flow as received or as intended to
2505  * be sent.  This is important for IPv6 and ARP, for which NXM supports more
2506  * detailed matching. */
2507 void
2508 ofputil_normalize_rule(struct cls_rule *rule, enum nx_flow_format flow_format)
2509 {
2510     enum {
2511         MAY_NW_ADDR     = 1 << 0, /* nw_src, nw_dst */
2512         MAY_TP_ADDR     = 1 << 1, /* tp_src, tp_dst */
2513         MAY_NW_PROTO    = 1 << 2, /* nw_proto */
2514         MAY_IPVx        = 1 << 3, /* tos, frag */
2515         MAY_ARP_SHA     = 1 << 4, /* arp_sha */
2516         MAY_ARP_THA     = 1 << 5, /* arp_tha */
2517         MAY_IPV6_ADDR   = 1 << 6, /* ipv6_src, ipv6_dst */
2518         MAY_ND_TARGET   = 1 << 7  /* nd_target */
2519     } may_match;
2520
2521     struct flow_wildcards wc;
2522
2523     /* Figure out what fields may be matched. */
2524     if (rule->flow.dl_type == htons(ETH_TYPE_IP)) {
2525         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_NW_ADDR;
2526         if (rule->flow.nw_proto == IPPROTO_TCP ||
2527             rule->flow.nw_proto == IPPROTO_UDP ||
2528             rule->flow.nw_proto == IPPROTO_ICMP) {
2529             may_match |= MAY_TP_ADDR;
2530         }
2531     } else if (rule->flow.dl_type == htons(ETH_TYPE_IPV6)
2532                && flow_format == NXFF_NXM) {
2533         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_IPV6_ADDR;
2534         if (rule->flow.nw_proto == IPPROTO_TCP ||
2535             rule->flow.nw_proto == IPPROTO_UDP) {
2536             may_match |= MAY_TP_ADDR;
2537         } else if (rule->flow.nw_proto == IPPROTO_ICMPV6) {
2538             may_match |= MAY_TP_ADDR;
2539             if (rule->flow.tp_src == htons(ND_NEIGHBOR_SOLICIT)) {
2540                 may_match |= MAY_ND_TARGET | MAY_ARP_SHA;
2541             } else if (rule->flow.tp_src == htons(ND_NEIGHBOR_ADVERT)) {
2542                 may_match |= MAY_ND_TARGET | MAY_ARP_THA;
2543             }
2544         }
2545     } else if (rule->flow.dl_type == htons(ETH_TYPE_ARP)) {
2546         may_match = MAY_NW_PROTO | MAY_NW_ADDR;
2547         if (flow_format == NXFF_NXM) {
2548             may_match |= MAY_ARP_SHA | MAY_ARP_THA;
2549         }
2550     } else {
2551         may_match = 0;
2552     }
2553
2554     /* Clear the fields that may not be matched. */
2555     wc = rule->wc;
2556     if (!(may_match & MAY_NW_ADDR)) {
2557         wc.nw_src_mask = wc.nw_dst_mask = htonl(0);
2558     }
2559     if (!(may_match & MAY_TP_ADDR)) {
2560         wc.wildcards |= FWW_TP_SRC | FWW_TP_DST;
2561     }
2562     if (!(may_match & MAY_NW_PROTO)) {
2563         wc.wildcards |= FWW_NW_PROTO;
2564     }
2565     if (!(may_match & MAY_IPVx)) {
2566         wc.tos_mask = 0;
2567         wc.frag_mask = 0;
2568     }
2569     if (!(may_match & MAY_ARP_SHA)) {
2570         wc.wildcards |= FWW_ARP_SHA;
2571     }
2572     if (!(may_match & MAY_ARP_THA)) {
2573         wc.wildcards |= FWW_ARP_THA;
2574     }
2575     if (!(may_match & MAY_IPV6_ADDR)) {
2576         wc.ipv6_src_mask = wc.ipv6_dst_mask = in6addr_any;
2577         wc.wildcards |= FWW_IPV6_LABEL;
2578     }
2579     if (!(may_match & MAY_ND_TARGET)) {
2580         wc.wildcards |= FWW_ND_TARGET;
2581     }
2582
2583     /* Log any changes. */
2584     if (!flow_wildcards_equal(&wc, &rule->wc)) {
2585         bool log = !VLOG_DROP_INFO(&bad_ofmsg_rl);
2586         char *pre = log ? cls_rule_to_string(rule) : NULL;
2587
2588         rule->wc = wc;
2589         cls_rule_zero_wildcarded_fields(rule);
2590
2591         if (log) {
2592             char *post = cls_rule_to_string(rule);
2593             VLOG_INFO("normalization changed ofp_match, details:");
2594             VLOG_INFO(" pre: %s", pre);
2595             VLOG_INFO("post: %s", post);
2596             free(pre);
2597             free(post);
2598         }
2599     }
2600 }
2601
2602 static uint32_t
2603 vendor_code_to_id(uint8_t code)
2604 {
2605     switch (code) {
2606 #define OFPUTIL_VENDOR(NAME, VENDOR_ID) case NAME: return VENDOR_ID;
2607         OFPUTIL_VENDORS
2608 #undef OFPUTIL_VENDOR
2609     default:
2610         return UINT32_MAX;
2611     }
2612 }
2613
2614 static int
2615 vendor_id_to_code(uint32_t id)
2616 {
2617     switch (id) {
2618 #define OFPUTIL_VENDOR(NAME, VENDOR_ID) case VENDOR_ID: return NAME;
2619         OFPUTIL_VENDORS
2620 #undef OFPUTIL_VENDOR
2621     default:
2622         return -1;
2623     }
2624 }
2625
2626 /* Creates and returns an OpenFlow message of type OFPT_ERROR with the error
2627  * information taken from 'error', whose encoding must be as described in the
2628  * large comment in ofp-util.h.  If 'oh' is nonnull, then the error will use
2629  * oh->xid as its transaction ID, and it will include up to the first 64 bytes
2630  * of 'oh'.
2631  *
2632  * Returns NULL if 'error' is not an OpenFlow error code. */
2633 struct ofpbuf *
2634 ofputil_encode_error_msg(int error, const struct ofp_header *oh)
2635 {
2636     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2637
2638     struct ofpbuf *buf;
2639     const void *data;
2640     size_t len;
2641     uint8_t vendor;
2642     uint16_t type;
2643     uint16_t code;
2644     ovs_be32 xid;
2645
2646     if (!is_ofp_error(error)) {
2647         /* We format 'error' with strerror() here since it seems likely to be
2648          * a system errno value. */
2649         VLOG_WARN_RL(&rl, "invalid OpenFlow error code %d (%s)",
2650                      error, strerror(error));
2651         return NULL;
2652     }
2653
2654     if (oh) {
2655         xid = oh->xid;
2656         data = oh;
2657         len = ntohs(oh->length);
2658         if (len > 64) {
2659             len = 64;
2660         }
2661     } else {
2662         xid = 0;
2663         data = NULL;
2664         len = 0;
2665     }
2666
2667     vendor = get_ofp_err_vendor(error);
2668     type = get_ofp_err_type(error);
2669     code = get_ofp_err_code(error);
2670     if (vendor == OFPUTIL_VENDOR_OPENFLOW) {
2671         struct ofp_error_msg *oem;
2672
2673         oem = make_openflow_xid(len + sizeof *oem, OFPT_ERROR, xid, &buf);
2674         oem->type = htons(type);
2675         oem->code = htons(code);
2676     } else {
2677         struct ofp_error_msg *oem;
2678         struct nx_vendor_error *nve;
2679         uint32_t vendor_id;
2680
2681         vendor_id = vendor_code_to_id(vendor);
2682         if (vendor_id == UINT32_MAX) {
2683             VLOG_WARN_RL(&rl, "error %x contains invalid vendor code %d",
2684                          error, vendor);
2685             return NULL;
2686         }
2687
2688         oem = make_openflow_xid(len + sizeof *oem + sizeof *nve,
2689                                 OFPT_ERROR, xid, &buf);
2690         oem->type = htons(NXET_VENDOR);
2691         oem->code = htons(NXVC_VENDOR_ERROR);
2692
2693         nve = (struct nx_vendor_error *)oem->data;
2694         nve->vendor = htonl(vendor_id);
2695         nve->type = htons(type);
2696         nve->code = htons(code);
2697     }
2698
2699     if (len) {
2700         buf->size -= len;
2701         ofpbuf_put(buf, data, len);
2702     }
2703
2704     return buf;
2705 }
2706
2707 /* Decodes 'oh', which should be an OpenFlow OFPT_ERROR message, and returns an
2708  * Open vSwitch internal error code in the format described in the large
2709  * comment in ofp-util.h.
2710  *
2711  * If 'payload_ofs' is nonnull, on success '*payload_ofs' is set to the offset
2712  * to the payload starting from 'oh' and on failure it is set to 0. */
2713 int
2714 ofputil_decode_error_msg(const struct ofp_header *oh, size_t *payload_ofs)
2715 {
2716     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2717
2718     const struct ofp_error_msg *oem;
2719     uint16_t type, code;
2720     struct ofpbuf b;
2721     int vendor;
2722
2723     if (payload_ofs) {
2724         *payload_ofs = 0;
2725     }
2726     if (oh->type != OFPT_ERROR) {
2727         return EPROTO;
2728     }
2729
2730     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2731     oem = ofpbuf_try_pull(&b, sizeof *oem);
2732     if (!oem) {
2733         return EPROTO;
2734     }
2735
2736     type = ntohs(oem->type);
2737     code = ntohs(oem->code);
2738     if (type == NXET_VENDOR && code == NXVC_VENDOR_ERROR) {
2739         const struct nx_vendor_error *nve = ofpbuf_try_pull(&b, sizeof *nve);
2740         if (!nve) {
2741             return EPROTO;
2742         }
2743
2744         vendor = vendor_id_to_code(ntohl(nve->vendor));
2745         if (vendor < 0) {
2746             VLOG_WARN_RL(&rl, "error contains unknown vendor ID %#"PRIx32,
2747                          ntohl(nve->vendor));
2748             return EPROTO;
2749         }
2750         type = ntohs(nve->type);
2751         code = ntohs(nve->code);
2752     } else {
2753         vendor = OFPUTIL_VENDOR_OPENFLOW;
2754     }
2755
2756     if (type >= 1024) {
2757         VLOG_WARN_RL(&rl, "error contains type %"PRIu16" greater than "
2758                      "supported maximum value 1023", type);
2759         return EPROTO;
2760     }
2761
2762     if (payload_ofs) {
2763         *payload_ofs = (uint8_t *) b.data - (uint8_t *) oh;
2764     }
2765     return ofp_mkerr_vendor(vendor, type, code);
2766 }
2767
2768 void
2769 ofputil_format_error(struct ds *s, int error)
2770 {
2771     if (is_errno(error)) {
2772         ds_put_cstr(s, strerror(error));
2773     } else {
2774         uint16_t type = get_ofp_err_type(error);
2775         uint16_t code = get_ofp_err_code(error);
2776         const char *type_s = ofp_error_type_to_string(type);
2777         const char *code_s = ofp_error_code_to_string(type, code);
2778
2779         ds_put_format(s, "type ");
2780         if (type_s) {
2781             ds_put_cstr(s, type_s);
2782         } else {
2783             ds_put_format(s, "%"PRIu16, type);
2784         }
2785
2786         ds_put_cstr(s, ", code ");
2787         if (code_s) {
2788             ds_put_cstr(s, code_s);
2789         } else {
2790             ds_put_format(s, "%"PRIu16, code);
2791         }
2792     }
2793 }
2794
2795 char *
2796 ofputil_error_to_string(int error)
2797 {
2798     struct ds s = DS_EMPTY_INITIALIZER;
2799     ofputil_format_error(&s, error);
2800     return ds_steal_cstr(&s);
2801 }
2802
2803 /* Attempts to pull 'actions_len' bytes from the front of 'b'.  Returns 0 if
2804  * successful, otherwise an OpenFlow error.
2805  *
2806  * If successful, the first action is stored in '*actionsp' and the number of
2807  * "union ofp_action" size elements into '*n_actionsp'.  Otherwise NULL and 0
2808  * are stored, respectively.
2809  *
2810  * This function does not check that the actions are valid (the caller should
2811  * do so, with validate_actions()).  The caller is also responsible for making
2812  * sure that 'b->data' is initially aligned appropriately for "union
2813  * ofp_action". */
2814 int
2815 ofputil_pull_actions(struct ofpbuf *b, unsigned int actions_len,
2816                      union ofp_action **actionsp, size_t *n_actionsp)
2817 {
2818     if (actions_len % OFP_ACTION_ALIGN != 0) {
2819         VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
2820                      "is not a multiple of %d", actions_len, OFP_ACTION_ALIGN);
2821         goto error;
2822     }
2823
2824     *actionsp = ofpbuf_try_pull(b, actions_len);
2825     if (*actionsp == NULL) {
2826         VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
2827                      "exceeds remaining message length (%zu)",
2828                      actions_len, b->size);
2829         goto error;
2830     }
2831
2832     *n_actionsp = actions_len / OFP_ACTION_ALIGN;
2833     return 0;
2834
2835 error:
2836     *actionsp = NULL;
2837     *n_actionsp = 0;
2838     return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
2839 }
2840
2841 bool
2842 ofputil_actions_equal(const union ofp_action *a, size_t n_a,
2843                       const union ofp_action *b, size_t n_b)
2844 {
2845     return n_a == n_b && (!n_a || !memcmp(a, b, n_a * sizeof *a));
2846 }
2847
2848 union ofp_action *
2849 ofputil_actions_clone(const union ofp_action *actions, size_t n)
2850 {
2851     return n ? xmemdup(actions, n * sizeof *actions) : NULL;
2852 }
2853
2854 /* Parses a key or a key-value pair from '*stringp'.
2855  *
2856  * On success: Stores the key into '*keyp'.  Stores the value, if present, into
2857  * '*valuep', otherwise an empty string.  Advances '*stringp' past the end of
2858  * the key-value pair, preparing it for another call.  '*keyp' and '*valuep'
2859  * are substrings of '*stringp' created by replacing some of its bytes by null
2860  * terminators.  Returns true.
2861  *
2862  * If '*stringp' is just white space or commas, sets '*keyp' and '*valuep' to
2863  * NULL and returns false. */
2864 bool
2865 ofputil_parse_key_value(char **stringp, char **keyp, char **valuep)
2866 {
2867     char *pos, *key, *value;
2868     size_t key_len;
2869
2870     pos = *stringp;
2871     pos += strspn(pos, ", \t\r\n");
2872     if (*pos == '\0') {
2873         *keyp = *valuep = NULL;
2874         return false;
2875     }
2876
2877     key = pos;
2878     key_len = strcspn(pos, ":=(, \t\r\n");
2879     if (key[key_len] == ':' || key[key_len] == '=') {
2880         /* The value can be separated by a colon. */
2881         size_t value_len;
2882
2883         value = key + key_len + 1;
2884         value_len = strcspn(value, ", \t\r\n");
2885         pos = value + value_len + (value[value_len] != '\0');
2886         value[value_len] = '\0';
2887     } else if (key[key_len] == '(') {
2888         /* The value can be surrounded by balanced parentheses.  The outermost
2889          * set of parentheses is removed. */
2890         int level = 1;
2891         size_t value_len;
2892
2893         value = key + key_len + 1;
2894         for (value_len = 0; level > 0; value_len++) {
2895             switch (value[value_len]) {
2896             case '\0':
2897                 ovs_fatal(0, "unbalanced parentheses in argument to %s", key);
2898
2899             case '(':
2900                 level++;
2901                 break;
2902
2903             case ')':
2904                 level--;
2905                 break;
2906             }
2907         }
2908         value[value_len - 1] = '\0';
2909         pos = value + value_len;
2910     } else {
2911         /* There might be no value at all. */
2912         value = key + key_len;  /* Will become the empty string below. */
2913         pos = key + key_len + (key[key_len] != '\0');
2914     }
2915     key[key_len] = '\0';
2916
2917     *stringp = pos;
2918     *keyp = key;
2919     *valuep = value;
2920     return true;
2921 }