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