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