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