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