ovs-controller: Allow --wildcards to specify a wildcard set.
[sliver-openvswitch.git] / lib / ofp-util.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "ofp-print.h"
19 #include <errno.h>
20 #include <inttypes.h>
21 #include <netinet/icmp6.h>
22 #include <stdlib.h>
23 #include "autopath.h"
24 #include "byte-order.h"
25 #include "classifier.h"
26 #include "dynamic-string.h"
27 #include "multipath.h"
28 #include "nx-match.h"
29 #include "ofp-errors.h"
30 #include "ofp-util.h"
31 #include "ofpbuf.h"
32 #include "packets.h"
33 #include "random.h"
34 #include "unaligned.h"
35 #include "type-props.h"
36 #include "vlog.h"
37
38 VLOG_DEFINE_THIS_MODULE(ofp_util);
39
40 /* Rate limit for OpenFlow message parse errors.  These always indicate a bug
41  * in the peer and so there's not much point in showing a lot of them. */
42 static struct vlog_rate_limit bad_ofmsg_rl = VLOG_RATE_LIMIT_INIT(1, 5);
43
44 /* Given the wildcard bit count in the least-significant 6 of 'wcbits', returns
45  * an IP netmask with a 1 in each bit that must match and a 0 in each bit that
46  * is wildcarded.
47  *
48  * The bits in 'wcbits' are in the format used in enum ofp_flow_wildcards: 0
49  * is exact match, 1 ignores the LSB, 2 ignores the 2 least-significant bits,
50  * ..., 32 and higher wildcard the entire field.  This is the *opposite* of the
51  * usual convention where e.g. /24 indicates that 8 bits (not 24 bits) are
52  * wildcarded. */
53 ovs_be32
54 ofputil_wcbits_to_netmask(int wcbits)
55 {
56     wcbits &= 0x3f;
57     return wcbits < 32 ? htonl(~((1u << wcbits) - 1)) : 0;
58 }
59
60 /* Given the IP netmask 'netmask', returns the number of bits of the IP address
61  * that it wildcards.  'netmask' must be a CIDR netmask (see ip_is_cidr()). */
62 int
63 ofputil_netmask_to_wcbits(ovs_be32 netmask)
64 {
65     assert(ip_is_cidr(netmask));
66 #if __GNUC__ >= 4
67     return netmask == htonl(0) ? 32 : __builtin_ctz(ntohl(netmask));
68 #else
69     int wcbits;
70
71     for (wcbits = 32; netmask; wcbits--) {
72         netmask &= netmask - 1;
73     }
74
75     return wcbits;
76 #endif
77 }
78
79 /* A list of the FWW_* and OFPFW_ bits that have the same value, meaning, and
80  * name. */
81 #define WC_INVARIANT_LIST \
82     WC_INVARIANT_BIT(IN_PORT) \
83     WC_INVARIANT_BIT(DL_SRC) \
84     WC_INVARIANT_BIT(DL_DST) \
85     WC_INVARIANT_BIT(DL_TYPE) \
86     WC_INVARIANT_BIT(NW_PROTO) \
87     WC_INVARIANT_BIT(TP_SRC) \
88     WC_INVARIANT_BIT(TP_DST)
89
90 /* Verify that all of the invariant bits (as defined on WC_INVARIANT_LIST)
91  * actually have the same names and values. */
92 #define WC_INVARIANT_BIT(NAME) BUILD_ASSERT_DECL(FWW_##NAME == OFPFW_##NAME);
93     WC_INVARIANT_LIST
94 #undef WC_INVARIANT_BIT
95
96 /* WC_INVARIANTS is the invariant bits (as defined on WC_INVARIANT_LIST) all
97  * OR'd together. */
98 static const flow_wildcards_t WC_INVARIANTS = 0
99 #define WC_INVARIANT_BIT(NAME) | FWW_##NAME
100     WC_INVARIANT_LIST
101 #undef WC_INVARIANT_BIT
102 ;
103
104 /* Converts the wildcard in 'ofpfw' into a flow_wildcards in 'wc' for use in
105  * struct cls_rule.  It is the caller's responsibility to handle the special
106  * case where the flow match's dl_vlan is set to OFP_VLAN_NONE. */
107 void
108 ofputil_wildcard_from_openflow(uint32_t ofpfw, struct flow_wildcards *wc)
109 {
110     /* Initialize most of rule->wc. */
111     flow_wildcards_init_catchall(wc);
112     wc->wildcards = (OVS_FORCE flow_wildcards_t) ofpfw & WC_INVARIANTS;
113
114     /* Wildcard fields that aren't defined by ofp_match or tun_id. */
115     wc->wildcards |= (FWW_ARP_SHA | FWW_ARP_THA | FWW_ND_TARGET);
116
117     if (ofpfw & OFPFW_NW_TOS) {
118         wc->wildcards |= FWW_NW_TOS;
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;
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_TOS) {
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;
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     uint32_t value;             /* OFPT_*, OFPST_*, NXT_*, or NXST_*. */
275     const char *name;           /* e.g. "OFPT_FLOW_REMOVED". */
276     unsigned int min_size;      /* Minimum total message size in bytes. */
277     /* 0 if 'min_size' is the exact size that the message must be.  Otherwise,
278      * the message may exceed 'min_size' by an even multiple of this value. */
279     unsigned int extra_multiple;
280 };
281
282 struct ofputil_msg_category {
283     const char *name;           /* e.g. "OpenFlow message" */
284     const struct ofputil_msg_type *types;
285     size_t n_types;
286     int missing_error;          /* ofp_mkerr() value for missing type. */
287 };
288
289 static bool
290 ofputil_length_ok(const struct ofputil_msg_category *cat,
291                   const struct ofputil_msg_type *type,
292                   unsigned int size)
293 {
294     switch (type->extra_multiple) {
295     case 0:
296         if (size != type->min_size) {
297             VLOG_WARN_RL(&bad_ofmsg_rl, "received %s %s with incorrect "
298                          "length %u (expected length %u)",
299                          cat->name, type->name, size, type->min_size);
300             return false;
301         }
302         return true;
303
304     case 1:
305         if (size < type->min_size) {
306             VLOG_WARN_RL(&bad_ofmsg_rl, "received %s %s with incorrect "
307                          "length %u (expected length at least %u bytes)",
308                          cat->name, type->name, size, type->min_size);
309             return false;
310         }
311         return true;
312
313     default:
314         if (size < type->min_size
315             || (size - type->min_size) % type->extra_multiple) {
316             VLOG_WARN_RL(&bad_ofmsg_rl, "received %s %s with incorrect "
317                          "length %u (must be exactly %u bytes or longer "
318                          "by an integer multiple of %u bytes)",
319                          cat->name, type->name, size,
320                          type->min_size, type->extra_multiple);
321             return false;
322         }
323         return true;
324     }
325 }
326
327 static int
328 ofputil_lookup_openflow_message(const struct ofputil_msg_category *cat,
329                                 uint32_t value, unsigned int size,
330                                 const struct ofputil_msg_type **typep)
331 {
332     const struct ofputil_msg_type *type;
333
334     for (type = cat->types; type < &cat->types[cat->n_types]; type++) {
335         if (type->value == value) {
336             if (!ofputil_length_ok(cat, type, size)) {
337                 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
338             }
339             *typep = type;
340             return 0;
341         }
342     }
343
344     VLOG_WARN_RL(&bad_ofmsg_rl, "received %s of unknown type %"PRIu32,
345                  cat->name, value);
346     return cat->missing_error;
347 }
348
349 static int
350 ofputil_decode_vendor(const struct ofp_header *oh,
351                       const struct ofputil_msg_type **typep)
352 {
353     BUILD_ASSERT_DECL(sizeof(struct nxt_set_flow_format)
354                       != sizeof(struct nxt_flow_mod_table_id));
355
356     static const struct ofputil_msg_type nxt_messages[] = {
357         { OFPUTIL_NXT_ROLE_REQUEST,
358           NXT_ROLE_REQUEST, "NXT_ROLE_REQUEST",
359           sizeof(struct nx_role_request), 0 },
360
361         { OFPUTIL_NXT_ROLE_REPLY,
362           NXT_ROLE_REPLY, "NXT_ROLE_REPLY",
363           sizeof(struct nx_role_request), 0 },
364
365         { OFPUTIL_NXT_SET_FLOW_FORMAT,
366           NXT_SET_FLOW_FORMAT, "NXT_SET_FLOW_FORMAT",
367           sizeof(struct nxt_set_flow_format), 0 },
368
369         { OFPUTIL_NXT_FLOW_MOD,
370           NXT_FLOW_MOD, "NXT_FLOW_MOD",
371           sizeof(struct nx_flow_mod), 8 },
372
373         { OFPUTIL_NXT_FLOW_REMOVED,
374           NXT_FLOW_REMOVED, "NXT_FLOW_REMOVED",
375           sizeof(struct nx_flow_removed), 8 },
376     };
377
378     static const struct ofputil_msg_category nxt_category = {
379         "Nicira extension message",
380         nxt_messages, ARRAY_SIZE(nxt_messages),
381         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE)
382     };
383
384     const struct ofp_vendor_header *ovh;
385     const struct nicira_header *nh;
386
387     ovh = (const struct ofp_vendor_header *) oh;
388     if (ovh->vendor != htonl(NX_VENDOR_ID)) {
389         VLOG_WARN_RL(&bad_ofmsg_rl, "received vendor message for unknown "
390                      "vendor %"PRIx32, ntohl(ovh->vendor));
391         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_VENDOR);
392     }
393
394     if (ntohs(ovh->header.length) < sizeof(struct nicira_header)) {
395         VLOG_WARN_RL(&bad_ofmsg_rl, "received Nicira vendor message of "
396                      "length %u (expected at least %zu)",
397                      ntohs(ovh->header.length), sizeof(struct nicira_header));
398         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
399     }
400
401     nh = (const struct nicira_header *) oh;
402
403     if (nh->subtype == htonl(NXT_FLOW_MOD_TABLE_ID)
404         && oh->length == htons(sizeof(struct nxt_flow_mod_table_id))) {
405         /* NXT_SET_FLOW_FORMAT and NXT_FLOW_MOD_TABLE_ID accidentally have the
406          * same value but different lengths.  ofputil_lookup_openflow_message()
407          * doesn't support this case, so special case it here. */
408         static const struct ofputil_msg_type nxt_flow_mod_table_id =
409             { OFPUTIL_NXT_FLOW_MOD_TABLE_ID,
410               NXT_FLOW_MOD_TABLE_ID, "NXT_FLOW_MOD_TABLE_ID",
411               sizeof(struct nxt_flow_mod_table_id), 0 };
412
413         *typep = &nxt_flow_mod_table_id;
414         return 0;
415     }
416
417     return ofputil_lookup_openflow_message(&nxt_category, ntohl(nh->subtype),
418                                            ntohs(oh->length), typep);
419 }
420
421 static int
422 check_nxstats_msg(const struct ofp_header *oh)
423 {
424     const struct ofp_stats_request *osr;
425     ovs_be32 vendor;
426
427     osr = (const struct ofp_stats_request *) oh;
428
429     memcpy(&vendor, osr->body, sizeof vendor);
430     if (vendor != htonl(NX_VENDOR_ID)) {
431         VLOG_WARN_RL(&bad_ofmsg_rl, "received vendor stats message for "
432                      "unknown vendor %"PRIx32, ntohl(vendor));
433         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_VENDOR);
434     }
435
436     if (ntohs(osr->header.length) < sizeof(struct nicira_stats_msg)) {
437         VLOG_WARN_RL(&bad_ofmsg_rl, "truncated Nicira stats message");
438         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
439     }
440
441     return 0;
442 }
443
444 static int
445 ofputil_decode_nxst_request(const struct ofp_header *oh,
446                             const struct ofputil_msg_type **typep)
447 {
448     static const struct ofputil_msg_type nxst_requests[] = {
449         { OFPUTIL_NXST_FLOW_REQUEST,
450           NXST_FLOW, "NXST_FLOW request",
451           sizeof(struct nx_flow_stats_request), 8 },
452
453         { OFPUTIL_NXST_AGGREGATE_REQUEST,
454           NXST_AGGREGATE, "NXST_AGGREGATE request",
455           sizeof(struct nx_aggregate_stats_request), 8 },
456     };
457
458     static const struct ofputil_msg_category nxst_request_category = {
459         "Nicira extension statistics request",
460         nxst_requests, ARRAY_SIZE(nxst_requests),
461         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE)
462     };
463
464     const struct nicira_stats_msg *nsm;
465     int error;
466
467     error = check_nxstats_msg(oh);
468     if (error) {
469         return error;
470     }
471
472     nsm = (struct nicira_stats_msg *) oh;
473     return ofputil_lookup_openflow_message(&nxst_request_category,
474                                            ntohl(nsm->subtype),
475                                            ntohs(oh->length), typep);
476 }
477
478 static int
479 ofputil_decode_nxst_reply(const struct ofp_header *oh,
480                           const struct ofputil_msg_type **typep)
481 {
482     static const struct ofputil_msg_type nxst_replies[] = {
483         { OFPUTIL_NXST_FLOW_REPLY,
484           NXST_FLOW, "NXST_FLOW reply",
485           sizeof(struct nicira_stats_msg), 8 },
486
487         { OFPUTIL_NXST_AGGREGATE_REPLY,
488           NXST_AGGREGATE, "NXST_AGGREGATE reply",
489           sizeof(struct nx_aggregate_stats_reply), 0 },
490     };
491
492     static const struct ofputil_msg_category nxst_reply_category = {
493         "Nicira extension statistics reply",
494         nxst_replies, ARRAY_SIZE(nxst_replies),
495         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE)
496     };
497
498     const struct nicira_stats_msg *nsm;
499     int error;
500
501     error = check_nxstats_msg(oh);
502     if (error) {
503         return error;
504     }
505
506     nsm = (struct nicira_stats_msg *) oh;
507     return ofputil_lookup_openflow_message(&nxst_reply_category,
508                                            ntohl(nsm->subtype),
509                                            ntohs(oh->length), typep);
510 }
511
512 static int
513 ofputil_decode_ofpst_request(const struct ofp_header *oh,
514                              const struct ofputil_msg_type **typep)
515 {
516     enum { OSR_SIZE = sizeof(struct ofp_stats_request) };
517     static const struct ofputil_msg_type ofpst_requests[] = {
518         { OFPUTIL_OFPST_DESC_REQUEST,
519           OFPST_DESC, "OFPST_DESC request",
520           OSR_SIZE, 0 },
521
522         { OFPUTIL_OFPST_FLOW_REQUEST,
523           OFPST_FLOW, "OFPST_FLOW request",
524           OSR_SIZE + sizeof(struct ofp_flow_stats_request), 0 },
525
526         { OFPUTIL_OFPST_AGGREGATE_REQUEST,
527           OFPST_AGGREGATE, "OFPST_AGGREGATE request",
528           OSR_SIZE + sizeof(struct ofp_aggregate_stats_request), 0 },
529
530         { OFPUTIL_OFPST_TABLE_REQUEST,
531           OFPST_TABLE, "OFPST_TABLE request",
532           OSR_SIZE, 0 },
533
534         { OFPUTIL_OFPST_PORT_REQUEST,
535           OFPST_PORT, "OFPST_PORT request",
536           OSR_SIZE + sizeof(struct ofp_port_stats_request), 0 },
537
538         { OFPUTIL_OFPST_QUEUE_REQUEST,
539           OFPST_QUEUE, "OFPST_QUEUE request",
540           OSR_SIZE + sizeof(struct ofp_queue_stats_request), 0 },
541
542         { 0,
543           OFPST_VENDOR, "OFPST_VENDOR request",
544           OSR_SIZE + sizeof(uint32_t), 1 },
545     };
546
547     static const struct ofputil_msg_category ofpst_request_category = {
548         "OpenFlow statistics",
549         ofpst_requests, ARRAY_SIZE(ofpst_requests),
550         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT)
551     };
552
553     const struct ofp_stats_request *osr;
554     int error;
555
556     osr = (const struct ofp_stats_request *) oh;
557     error = ofputil_lookup_openflow_message(&ofpst_request_category,
558                                             ntohs(osr->type),
559                                             ntohs(oh->length), typep);
560     if (!error && osr->type == htons(OFPST_VENDOR)) {
561         error = ofputil_decode_nxst_request(oh, typep);
562     }
563     return error;
564 }
565
566 static int
567 ofputil_decode_ofpst_reply(const struct ofp_header *oh,
568                            const struct ofputil_msg_type **typep)
569 {
570     enum { OSR_SIZE = sizeof(struct ofp_stats_reply) };
571     static const struct ofputil_msg_type ofpst_replies[] = {
572         { OFPUTIL_OFPST_DESC_REPLY,
573           OFPST_DESC, "OFPST_DESC reply",
574           OSR_SIZE + sizeof(struct ofp_desc_stats), 0 },
575
576         { OFPUTIL_OFPST_FLOW_REPLY,
577           OFPST_FLOW, "OFPST_FLOW reply",
578           OSR_SIZE, 1 },
579
580         { OFPUTIL_OFPST_AGGREGATE_REPLY,
581           OFPST_AGGREGATE, "OFPST_AGGREGATE reply",
582           OSR_SIZE + sizeof(struct ofp_aggregate_stats_reply), 0 },
583
584         { OFPUTIL_OFPST_TABLE_REPLY,
585           OFPST_TABLE, "OFPST_TABLE reply",
586           OSR_SIZE, sizeof(struct ofp_table_stats) },
587
588         { OFPUTIL_OFPST_PORT_REPLY,
589           OFPST_PORT, "OFPST_PORT reply",
590           OSR_SIZE, sizeof(struct ofp_port_stats) },
591
592         { OFPUTIL_OFPST_QUEUE_REPLY,
593           OFPST_QUEUE, "OFPST_QUEUE reply",
594           OSR_SIZE, sizeof(struct ofp_queue_stats) },
595
596         { 0,
597           OFPST_VENDOR, "OFPST_VENDOR reply",
598           OSR_SIZE + sizeof(uint32_t), 1 },
599     };
600
601     static const struct ofputil_msg_category ofpst_reply_category = {
602         "OpenFlow statistics",
603         ofpst_replies, ARRAY_SIZE(ofpst_replies),
604         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT)
605     };
606
607     const struct ofp_stats_reply *osr = (const struct ofp_stats_reply *) oh;
608     int error;
609
610     error = ofputil_lookup_openflow_message(&ofpst_reply_category,
611                                            ntohs(osr->type),
612                                            ntohs(oh->length), typep);
613     if (!error && osr->type == htons(OFPST_VENDOR)) {
614         error = ofputil_decode_nxst_reply(oh, typep);
615     }
616     return error;
617 }
618
619 /* Decodes the message type represented by 'oh'.  Returns 0 if successful or
620  * an OpenFlow error code constructed with ofp_mkerr() on failure.  Either
621  * way, stores in '*typep' a type structure that can be inspected with the
622  * ofputil_msg_type_*() functions.
623  *
624  * oh->length must indicate the correct length of the message (and must be at
625  * least sizeof(struct ofp_header)).
626  *
627  * Success indicates that 'oh' is at least as long as the minimum-length
628  * message of its type. */
629 int
630 ofputil_decode_msg_type(const struct ofp_header *oh,
631                         const struct ofputil_msg_type **typep)
632 {
633     static const struct ofputil_msg_type ofpt_messages[] = {
634         { OFPUTIL_OFPT_HELLO,
635           OFPT_HELLO, "OFPT_HELLO",
636           sizeof(struct ofp_hello), 1 },
637
638         { OFPUTIL_OFPT_ERROR,
639           OFPT_ERROR, "OFPT_ERROR",
640           sizeof(struct ofp_error_msg), 1 },
641
642         { OFPUTIL_OFPT_ECHO_REQUEST,
643           OFPT_ECHO_REQUEST, "OFPT_ECHO_REQUEST",
644           sizeof(struct ofp_header), 1 },
645
646         { OFPUTIL_OFPT_ECHO_REPLY,
647           OFPT_ECHO_REPLY, "OFPT_ECHO_REPLY",
648           sizeof(struct ofp_header), 1 },
649
650         { OFPUTIL_OFPT_FEATURES_REQUEST,
651           OFPT_FEATURES_REQUEST, "OFPT_FEATURES_REQUEST",
652           sizeof(struct ofp_header), 0 },
653
654         { OFPUTIL_OFPT_FEATURES_REPLY,
655           OFPT_FEATURES_REPLY, "OFPT_FEATURES_REPLY",
656           sizeof(struct ofp_switch_features), sizeof(struct ofp_phy_port) },
657
658         { OFPUTIL_OFPT_GET_CONFIG_REQUEST,
659           OFPT_GET_CONFIG_REQUEST, "OFPT_GET_CONFIG_REQUEST",
660           sizeof(struct ofp_header), 0 },
661
662         { OFPUTIL_OFPT_GET_CONFIG_REPLY,
663           OFPT_GET_CONFIG_REPLY, "OFPT_GET_CONFIG_REPLY",
664           sizeof(struct ofp_switch_config), 0 },
665
666         { OFPUTIL_OFPT_SET_CONFIG,
667           OFPT_SET_CONFIG, "OFPT_SET_CONFIG",
668           sizeof(struct ofp_switch_config), 0 },
669
670         { OFPUTIL_OFPT_PACKET_IN,
671           OFPT_PACKET_IN, "OFPT_PACKET_IN",
672           offsetof(struct ofp_packet_in, data), 1 },
673
674         { OFPUTIL_OFPT_FLOW_REMOVED,
675           OFPT_FLOW_REMOVED, "OFPT_FLOW_REMOVED",
676           sizeof(struct ofp_flow_removed), 0 },
677
678         { OFPUTIL_OFPT_PORT_STATUS,
679           OFPT_PORT_STATUS, "OFPT_PORT_STATUS",
680           sizeof(struct ofp_port_status), 0 },
681
682         { OFPUTIL_OFPT_PACKET_OUT,
683           OFPT_PACKET_OUT, "OFPT_PACKET_OUT",
684           sizeof(struct ofp_packet_out), 1 },
685
686         { OFPUTIL_OFPT_FLOW_MOD,
687           OFPT_FLOW_MOD, "OFPT_FLOW_MOD",
688           sizeof(struct ofp_flow_mod), 1 },
689
690         { OFPUTIL_OFPT_PORT_MOD,
691           OFPT_PORT_MOD, "OFPT_PORT_MOD",
692           sizeof(struct ofp_port_mod), 0 },
693
694         { 0,
695           OFPT_STATS_REQUEST, "OFPT_STATS_REQUEST",
696           sizeof(struct ofp_stats_request), 1 },
697
698         { 0,
699           OFPT_STATS_REPLY, "OFPT_STATS_REPLY",
700           sizeof(struct ofp_stats_reply), 1 },
701
702         { OFPUTIL_OFPT_BARRIER_REQUEST,
703           OFPT_BARRIER_REQUEST, "OFPT_BARRIER_REQUEST",
704           sizeof(struct ofp_header), 0 },
705
706         { OFPUTIL_OFPT_BARRIER_REPLY,
707           OFPT_BARRIER_REPLY, "OFPT_BARRIER_REPLY",
708           sizeof(struct ofp_header), 0 },
709
710         { 0,
711           OFPT_VENDOR, "OFPT_VENDOR",
712           sizeof(struct ofp_vendor_header), 1 },
713     };
714
715     static const struct ofputil_msg_category ofpt_category = {
716         "OpenFlow message",
717         ofpt_messages, ARRAY_SIZE(ofpt_messages),
718         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE)
719     };
720
721     int error;
722
723     error = ofputil_lookup_openflow_message(&ofpt_category, oh->type,
724                                             ntohs(oh->length), typep);
725     if (!error) {
726         switch (oh->type) {
727         case OFPT_VENDOR:
728             error = ofputil_decode_vendor(oh, typep);
729             break;
730
731         case OFPT_STATS_REQUEST:
732             error = ofputil_decode_ofpst_request(oh, typep);
733             break;
734
735         case OFPT_STATS_REPLY:
736             error = ofputil_decode_ofpst_reply(oh, typep);
737
738         default:
739             break;
740         }
741     }
742     if (error) {
743         static const struct ofputil_msg_type ofputil_invalid_type = {
744             OFPUTIL_INVALID,
745             0, "OFPUTIL_INVALID",
746             0, 0
747         };
748
749         *typep = &ofputil_invalid_type;
750     }
751     return error;
752 }
753
754 /* Returns an OFPUTIL_* message type code for 'type'. */
755 enum ofputil_msg_code
756 ofputil_msg_type_code(const struct ofputil_msg_type *type)
757 {
758     return type->code;
759 }
760 \f
761 /* Flow formats. */
762
763 bool
764 ofputil_flow_format_is_valid(enum nx_flow_format flow_format)
765 {
766     switch (flow_format) {
767     case NXFF_OPENFLOW10:
768     case NXFF_NXM:
769         return true;
770     }
771
772     return false;
773 }
774
775 const char *
776 ofputil_flow_format_to_string(enum nx_flow_format flow_format)
777 {
778     switch (flow_format) {
779     case NXFF_OPENFLOW10:
780         return "openflow10";
781     case NXFF_NXM:
782         return "nxm";
783     default:
784         NOT_REACHED();
785     }
786 }
787
788 int
789 ofputil_flow_format_from_string(const char *s)
790 {
791     return (!strcmp(s, "openflow10") ? NXFF_OPENFLOW10
792             : !strcmp(s, "nxm") ? NXFF_NXM
793             : -1);
794 }
795
796 static bool
797 regs_fully_wildcarded(const struct flow_wildcards *wc)
798 {
799     int i;
800
801     for (i = 0; i < FLOW_N_REGS; i++) {
802         if (wc->reg_masks[i] != 0) {
803             return false;
804         }
805     }
806     return true;
807 }
808
809 /* Returns the minimum nx_flow_format to use for sending 'rule' to a switch
810  * (e.g. to add or remove a flow).  Only NXM can handle tunnel IDs, registers,
811  * or fixing the Ethernet multicast bit.  Otherwise, it's better to use
812  * NXFF_OPENFLOW10 for backward compatibility. */
813 enum nx_flow_format
814 ofputil_min_flow_format(const struct cls_rule *rule)
815 {
816     const struct flow_wildcards *wc = &rule->wc;
817
818     /* Only NXM supports separately wildcards the Ethernet multicast bit. */
819     if (!(wc->wildcards & FWW_DL_DST) != !(wc->wildcards & FWW_ETH_MCAST)) {
820         return NXFF_NXM;
821     }
822
823     /* Only NXM supports matching ARP hardware addresses. */
824     if (!(wc->wildcards & FWW_ARP_SHA) || !(wc->wildcards & FWW_ARP_THA)) {
825         return NXFF_NXM;
826     }
827
828     /* Only NXM supports matching IPv6 traffic. */
829     if (!(wc->wildcards & FWW_DL_TYPE)
830             && (rule->flow.dl_type == htons(ETH_TYPE_IPV6))) {
831         return NXFF_NXM;
832     }
833
834     /* Only NXM supports matching registers. */
835     if (!regs_fully_wildcarded(wc)) {
836         return NXFF_NXM;
837     }
838
839     /* Only NXM supports matching tun_id. */
840     if (wc->tun_id_mask != htonll(0)) {
841         return NXFF_NXM;
842     }
843
844     /* Other formats can express this rule. */
845     return NXFF_OPENFLOW10;
846 }
847
848 /* Returns an OpenFlow message that can be used to set the flow format to
849  * 'flow_format'.  */
850 struct ofpbuf *
851 ofputil_make_set_flow_format(enum nx_flow_format flow_format)
852 {
853     struct nxt_set_flow_format *sff;
854     struct ofpbuf *msg;
855
856     sff = make_nxmsg(sizeof *sff, NXT_SET_FLOW_FORMAT, &msg);
857     sff->format = htonl(flow_format);
858
859     return msg;
860 }
861
862 /* Returns an OpenFlow message that can be used to turn the flow_mod_table_id
863  * extension on or off (according to 'flow_mod_table_id'). */
864 struct ofpbuf *
865 ofputil_make_flow_mod_table_id(bool flow_mod_table_id)
866 {
867     struct nxt_flow_mod_table_id *nfmti;
868     struct ofpbuf *msg;
869
870     nfmti = make_nxmsg(sizeof *nfmti, NXT_FLOW_MOD_TABLE_ID, &msg);
871     nfmti->set = flow_mod_table_id;
872     return msg;
873 }
874
875 /* Converts an OFPT_FLOW_MOD or NXT_FLOW_MOD message 'oh' into an abstract
876  * flow_mod in 'fm'.  Returns 0 if successful, otherwise an OpenFlow error
877  * code.
878  *
879  * 'flow_mod_table_id' should be true if the NXT_FLOW_MOD_TABLE_ID extension is
880  * enabled, false otherwise.
881  *
882  * Does not validate the flow_mod actions. */
883 int
884 ofputil_decode_flow_mod(struct flow_mod *fm, const struct ofp_header *oh,
885                         bool flow_mod_table_id)
886 {
887     const struct ofputil_msg_type *type;
888     uint16_t command;
889     struct ofpbuf b;
890
891     ofpbuf_use_const(&b, oh, ntohs(oh->length));
892
893     ofputil_decode_msg_type(oh, &type);
894     if (ofputil_msg_type_code(type) == OFPUTIL_OFPT_FLOW_MOD) {
895         /* Standard OpenFlow flow_mod. */
896         const struct ofp_flow_mod *ofm;
897         uint16_t priority;
898         int error;
899
900         /* Dissect the message. */
901         ofm = ofpbuf_pull(&b, sizeof *ofm);
902         error = ofputil_pull_actions(&b, b.size, &fm->actions, &fm->n_actions);
903         if (error) {
904             return error;
905         }
906
907         /* Set priority based on original wildcards.  Normally we'd allow
908          * ofputil_cls_rule_from_match() to do this for us, but
909          * ofputil_normalize_rule() can put wildcards where the original flow
910          * didn't have them. */
911         priority = ntohs(ofm->priority);
912         if (!(ofm->match.wildcards & htonl(OFPFW_ALL))) {
913             priority = UINT16_MAX;
914         }
915
916         /* Translate the rule. */
917         ofputil_cls_rule_from_match(&ofm->match, priority, &fm->cr);
918         ofputil_normalize_rule(&fm->cr, NXFF_OPENFLOW10);
919
920         /* Translate the message. */
921         fm->cookie = ofm->cookie;
922         command = ntohs(ofm->command);
923         fm->idle_timeout = ntohs(ofm->idle_timeout);
924         fm->hard_timeout = ntohs(ofm->hard_timeout);
925         fm->buffer_id = ntohl(ofm->buffer_id);
926         fm->out_port = ntohs(ofm->out_port);
927         fm->flags = ntohs(ofm->flags);
928     } else if (ofputil_msg_type_code(type) == OFPUTIL_NXT_FLOW_MOD) {
929         /* Nicira extended flow_mod. */
930         const struct nx_flow_mod *nfm;
931         int error;
932
933         /* Dissect the message. */
934         nfm = ofpbuf_pull(&b, sizeof *nfm);
935         error = nx_pull_match(&b, ntohs(nfm->match_len), ntohs(nfm->priority),
936                               &fm->cr);
937         if (error) {
938             return error;
939         }
940         error = ofputil_pull_actions(&b, b.size, &fm->actions, &fm->n_actions);
941         if (error) {
942             return error;
943         }
944
945         /* Translate the message. */
946         fm->cookie = nfm->cookie;
947         command = ntohs(nfm->command);
948         fm->idle_timeout = ntohs(nfm->idle_timeout);
949         fm->hard_timeout = ntohs(nfm->hard_timeout);
950         fm->buffer_id = ntohl(nfm->buffer_id);
951         fm->out_port = ntohs(nfm->out_port);
952         fm->flags = ntohs(nfm->flags);
953     } else {
954         NOT_REACHED();
955     }
956
957     if (flow_mod_table_id) {
958         fm->command = command & 0xff;
959         fm->table_id = command >> 8;
960     } else {
961         fm->command = command;
962         fm->table_id = 0xff;
963     }
964
965     return 0;
966 }
967
968 /* Converts 'fm' into an OFPT_FLOW_MOD or NXT_FLOW_MOD message according to
969  * 'flow_format' and returns the message.
970  *
971  * 'flow_mod_table_id' should be true if the NXT_FLOW_MOD_TABLE_ID extension is
972  * enabled, false otherwise. */
973 struct ofpbuf *
974 ofputil_encode_flow_mod(const struct flow_mod *fm,
975                         enum nx_flow_format flow_format,
976                         bool flow_mod_table_id)
977 {
978     size_t actions_len = fm->n_actions * sizeof *fm->actions;
979     struct ofpbuf *msg;
980     uint16_t command;
981
982     command = (flow_mod_table_id
983                ? (fm->command & 0xff) | (fm->table_id << 8)
984                : fm->command);
985
986     if (flow_format == NXFF_OPENFLOW10) {
987         struct ofp_flow_mod *ofm;
988
989         msg = ofpbuf_new(sizeof *ofm + actions_len);
990         ofm = put_openflow(sizeof *ofm, OFPT_FLOW_MOD, msg);
991         ofputil_cls_rule_to_match(&fm->cr, &ofm->match);
992         ofm->cookie = fm->cookie;
993         ofm->command = htons(fm->command);
994         ofm->idle_timeout = htons(fm->idle_timeout);
995         ofm->hard_timeout = htons(fm->hard_timeout);
996         ofm->priority = htons(fm->cr.priority);
997         ofm->buffer_id = htonl(fm->buffer_id);
998         ofm->out_port = htons(fm->out_port);
999         ofm->flags = htons(fm->flags);
1000     } else if (flow_format == NXFF_NXM) {
1001         struct nx_flow_mod *nfm;
1002         int match_len;
1003
1004         msg = ofpbuf_new(sizeof *nfm + NXM_TYPICAL_LEN + actions_len);
1005         put_nxmsg(sizeof *nfm, NXT_FLOW_MOD, msg);
1006         match_len = nx_put_match(msg, &fm->cr);
1007
1008         nfm = msg->data;
1009         nfm->cookie = fm->cookie;
1010         nfm->command = htons(command);
1011         nfm->idle_timeout = htons(fm->idle_timeout);
1012         nfm->hard_timeout = htons(fm->hard_timeout);
1013         nfm->priority = htons(fm->cr.priority);
1014         nfm->buffer_id = htonl(fm->buffer_id);
1015         nfm->out_port = htons(fm->out_port);
1016         nfm->flags = htons(fm->flags);
1017         nfm->match_len = htons(match_len);
1018     } else {
1019         NOT_REACHED();
1020     }
1021
1022     ofpbuf_put(msg, fm->actions, actions_len);
1023     update_openflow_length(msg);
1024     return msg;
1025 }
1026
1027 static int
1028 ofputil_decode_ofpst_flow_request(struct flow_stats_request *fsr,
1029                                   const struct ofp_header *oh,
1030                                   bool aggregate)
1031 {
1032     const struct ofp_flow_stats_request *ofsr = ofputil_stats_body(oh);
1033
1034     fsr->aggregate = aggregate;
1035     ofputil_cls_rule_from_match(&ofsr->match, 0, &fsr->match);
1036     fsr->out_port = ntohs(ofsr->out_port);
1037     fsr->table_id = ofsr->table_id;
1038
1039     return 0;
1040 }
1041
1042 static int
1043 ofputil_decode_nxst_flow_request(struct flow_stats_request *fsr,
1044                                  const struct ofp_header *oh,
1045                                  bool aggregate)
1046 {
1047     const struct nx_flow_stats_request *nfsr;
1048     struct ofpbuf b;
1049     int error;
1050
1051     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1052
1053     nfsr = ofpbuf_pull(&b, sizeof *nfsr);
1054     error = nx_pull_match(&b, ntohs(nfsr->match_len), 0, &fsr->match);
1055     if (error) {
1056         return error;
1057     }
1058     if (b.size) {
1059         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1060     }
1061
1062     fsr->aggregate = aggregate;
1063     fsr->out_port = ntohs(nfsr->out_port);
1064     fsr->table_id = nfsr->table_id;
1065
1066     return 0;
1067 }
1068
1069 /* Converts an OFPST_FLOW, OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE
1070  * request 'oh', into an abstract flow_stats_request in 'fsr'.  Returns 0 if
1071  * successful, otherwise an OpenFlow error code. */
1072 int
1073 ofputil_decode_flow_stats_request(struct flow_stats_request *fsr,
1074                                   const struct ofp_header *oh)
1075 {
1076     const struct ofputil_msg_type *type;
1077     struct ofpbuf b;
1078     int code;
1079
1080     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1081
1082     ofputil_decode_msg_type(oh, &type);
1083     code = ofputil_msg_type_code(type);
1084     switch (code) {
1085     case OFPUTIL_OFPST_FLOW_REQUEST:
1086         return ofputil_decode_ofpst_flow_request(fsr, oh, false);
1087
1088     case OFPUTIL_OFPST_AGGREGATE_REQUEST:
1089         return ofputil_decode_ofpst_flow_request(fsr, oh, true);
1090
1091     case OFPUTIL_NXST_FLOW_REQUEST:
1092         return ofputil_decode_nxst_flow_request(fsr, oh, false);
1093
1094     case OFPUTIL_NXST_AGGREGATE_REQUEST:
1095         return ofputil_decode_nxst_flow_request(fsr, oh, true);
1096
1097     default:
1098         /* Hey, the caller lied. */
1099         NOT_REACHED();
1100     }
1101 }
1102
1103 /* Converts abstract flow_stats_request 'fsr' into an OFPST_FLOW,
1104  * OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE request 'oh' according to
1105  * 'flow_format', and returns the message. */
1106 struct ofpbuf *
1107 ofputil_encode_flow_stats_request(const struct flow_stats_request *fsr,
1108                                   enum nx_flow_format flow_format)
1109 {
1110     struct ofpbuf *msg;
1111
1112     if (flow_format == NXFF_OPENFLOW10) {
1113         struct ofp_flow_stats_request *ofsr;
1114         int type;
1115
1116         BUILD_ASSERT_DECL(sizeof(struct ofp_flow_stats_request)
1117                           == sizeof(struct ofp_aggregate_stats_request));
1118
1119         type = fsr->aggregate ? OFPST_AGGREGATE : OFPST_FLOW;
1120         ofsr = ofputil_make_stats_request(sizeof *ofsr, type, &msg);
1121         ofputil_cls_rule_to_match(&fsr->match, &ofsr->match);
1122         ofsr->table_id = fsr->table_id;
1123         ofsr->out_port = htons(fsr->out_port);
1124     } else if (flow_format == NXFF_NXM) {
1125         struct nx_flow_stats_request *nfsr;
1126         int match_len;
1127         int subtype;
1128
1129         subtype = fsr->aggregate ? NXST_AGGREGATE : NXST_FLOW;
1130         ofputil_make_nxstats_request(sizeof *nfsr, subtype, &msg);
1131         match_len = nx_put_match(msg, &fsr->match);
1132
1133         nfsr = msg->data;
1134         nfsr->out_port = htons(fsr->out_port);
1135         nfsr->match_len = htons(match_len);
1136         nfsr->table_id = fsr->table_id;
1137     } else {
1138         NOT_REACHED();
1139     }
1140
1141     return msg;
1142 }
1143
1144 /* Converts an OFPST_FLOW or NXST_FLOW reply in 'msg' into an abstract
1145  * ofputil_flow_stats in 'fs'.
1146  *
1147  * Multiple OFPST_FLOW or NXST_FLOW replies can be packed into a single
1148  * OpenFlow message.  Calling this function multiple times for a single 'msg'
1149  * iterates through the replies.  The caller must initially leave 'msg''s layer
1150  * pointers null and not modify them between calls.
1151  *
1152  * Returns 0 if successful, EOF if no replies were left in this 'msg',
1153  * otherwise a positive errno value. */
1154 int
1155 ofputil_decode_flow_stats_reply(struct ofputil_flow_stats *fs,
1156                                 struct ofpbuf *msg)
1157 {
1158     const struct ofputil_msg_type *type;
1159     int code;
1160
1161     ofputil_decode_msg_type(msg->l2 ? msg->l2 : msg->data, &type);
1162     code = ofputil_msg_type_code(type);
1163     if (!msg->l2) {
1164         msg->l2 = msg->data;
1165         if (code == OFPUTIL_OFPST_FLOW_REPLY) {
1166             ofpbuf_pull(msg, sizeof(struct ofp_stats_reply));
1167         } else if (code == OFPUTIL_NXST_FLOW_REPLY) {
1168             ofpbuf_pull(msg, sizeof(struct nicira_stats_msg));
1169         } else {
1170             NOT_REACHED();
1171         }
1172     }
1173
1174     if (!msg->size) {
1175         return EOF;
1176     } else if (code == OFPUTIL_OFPST_FLOW_REPLY) {
1177         const struct ofp_flow_stats *ofs;
1178         size_t length;
1179
1180         ofs = ofpbuf_try_pull(msg, sizeof *ofs);
1181         if (!ofs) {
1182             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply has %zu leftover "
1183                          "bytes at end", msg->size);
1184             return EINVAL;
1185         }
1186
1187         length = ntohs(ofs->length);
1188         if (length < sizeof *ofs) {
1189             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply claims invalid "
1190                          "length %zu", length);
1191             return EINVAL;
1192         }
1193
1194         if (ofputil_pull_actions(msg, length - sizeof *ofs,
1195                                  &fs->actions, &fs->n_actions)) {
1196             return EINVAL;
1197         }
1198
1199         fs->cookie = get_32aligned_be64(&ofs->cookie);
1200         ofputil_cls_rule_from_match(&ofs->match, ntohs(ofs->priority),
1201                                     &fs->rule);
1202         fs->table_id = ofs->table_id;
1203         fs->duration_sec = ntohl(ofs->duration_sec);
1204         fs->duration_nsec = ntohl(ofs->duration_nsec);
1205         fs->idle_timeout = ntohs(ofs->idle_timeout);
1206         fs->hard_timeout = ntohs(ofs->hard_timeout);
1207         fs->packet_count = ntohll(get_32aligned_be64(&ofs->packet_count));
1208         fs->byte_count = ntohll(get_32aligned_be64(&ofs->byte_count));
1209     } else if (code == OFPUTIL_NXST_FLOW_REPLY) {
1210         const struct nx_flow_stats *nfs;
1211         size_t match_len, length;
1212
1213         nfs = ofpbuf_try_pull(msg, sizeof *nfs);
1214         if (!nfs) {
1215             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply has %zu leftover "
1216                          "bytes at end", msg->size);
1217             return EINVAL;
1218         }
1219
1220         length = ntohs(nfs->length);
1221         match_len = ntohs(nfs->match_len);
1222         if (length < sizeof *nfs + ROUND_UP(match_len, 8)) {
1223             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply with match_len=%zu "
1224                          "claims invalid length %zu", match_len, length);
1225             return EINVAL;
1226         }
1227         if (nx_pull_match(msg, match_len, ntohs(nfs->priority), &fs->rule)) {
1228             return EINVAL;
1229         }
1230
1231         if (ofputil_pull_actions(msg,
1232                                  length - sizeof *nfs - ROUND_UP(match_len, 8),
1233                                  &fs->actions, &fs->n_actions)) {
1234             return EINVAL;
1235         }
1236
1237         fs->cookie = nfs->cookie;
1238         fs->table_id = nfs->table_id;
1239         fs->duration_sec = ntohl(nfs->duration_sec);
1240         fs->duration_nsec = ntohl(nfs->duration_nsec);
1241         fs->idle_timeout = ntohs(nfs->idle_timeout);
1242         fs->hard_timeout = ntohs(nfs->hard_timeout);
1243         fs->packet_count = ntohll(nfs->packet_count);
1244         fs->byte_count = ntohll(nfs->byte_count);
1245     } else {
1246         NOT_REACHED();
1247     }
1248
1249     return 0;
1250 }
1251
1252 /* Converts an OFPT_FLOW_REMOVED or NXT_FLOW_REMOVED message 'oh' into an
1253  * abstract ofputil_flow_removed in 'fr'.  Returns 0 if successful, otherwise
1254  * an OpenFlow error code. */
1255 int
1256 ofputil_decode_flow_removed(struct ofputil_flow_removed *fr,
1257                             const struct ofp_header *oh)
1258 {
1259     const struct ofputil_msg_type *type;
1260     enum ofputil_msg_code code;
1261
1262     ofputil_decode_msg_type(oh, &type);
1263     code = ofputil_msg_type_code(type);
1264     if (code == OFPUTIL_OFPT_FLOW_REMOVED) {
1265         const struct ofp_flow_removed *ofr;
1266
1267         ofr = (const struct ofp_flow_removed *) oh;
1268         ofputil_cls_rule_from_match(&ofr->match, ntohs(ofr->priority),
1269                                     &fr->rule);
1270         fr->cookie = ofr->cookie;
1271         fr->reason = ofr->reason;
1272         fr->duration_sec = ntohl(ofr->duration_sec);
1273         fr->duration_nsec = ntohl(ofr->duration_nsec);
1274         fr->idle_timeout = ntohs(ofr->idle_timeout);
1275         fr->packet_count = ntohll(ofr->packet_count);
1276         fr->byte_count = ntohll(ofr->byte_count);
1277     } else if (code == OFPUTIL_NXT_FLOW_REMOVED) {
1278         struct nx_flow_removed *nfr;
1279         struct ofpbuf b;
1280         int error;
1281
1282         ofpbuf_use_const(&b, oh, ntohs(oh->length));
1283
1284         nfr = ofpbuf_pull(&b, sizeof *nfr);
1285         error = nx_pull_match(&b, ntohs(nfr->match_len), ntohs(nfr->priority),
1286                               &fr->rule);
1287         if (error) {
1288             return error;
1289         }
1290         if (b.size) {
1291             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1292         }
1293
1294         fr->cookie = nfr->cookie;
1295         fr->reason = nfr->reason;
1296         fr->duration_sec = ntohl(nfr->duration_sec);
1297         fr->duration_nsec = ntohl(nfr->duration_nsec);
1298         fr->idle_timeout = ntohs(nfr->idle_timeout);
1299         fr->packet_count = ntohll(nfr->packet_count);
1300         fr->byte_count = ntohll(nfr->byte_count);
1301     } else {
1302         NOT_REACHED();
1303     }
1304
1305     return 0;
1306 }
1307
1308 /* Converts abstract ofputil_flow_removed 'fr' into an OFPT_FLOW_REMOVED or
1309  * NXT_FLOW_REMOVED message 'oh' according to 'flow_format', and returns the
1310  * message. */
1311 struct ofpbuf *
1312 ofputil_encode_flow_removed(const struct ofputil_flow_removed *fr,
1313                             enum nx_flow_format flow_format)
1314 {
1315     struct ofpbuf *msg;
1316
1317     if (flow_format == NXFF_OPENFLOW10) {
1318         struct ofp_flow_removed *ofr;
1319
1320         ofr = make_openflow_xid(sizeof *ofr, OFPT_FLOW_REMOVED, htonl(0),
1321                                 &msg);
1322         ofputil_cls_rule_to_match(&fr->rule, &ofr->match);
1323         ofr->cookie = fr->cookie;
1324         ofr->priority = htons(fr->rule.priority);
1325         ofr->reason = fr->reason;
1326         ofr->duration_sec = htonl(fr->duration_sec);
1327         ofr->duration_nsec = htonl(fr->duration_nsec);
1328         ofr->idle_timeout = htons(fr->idle_timeout);
1329         ofr->packet_count = htonll(fr->packet_count);
1330         ofr->byte_count = htonll(fr->byte_count);
1331     } else if (flow_format == NXFF_NXM) {
1332         struct nx_flow_removed *nfr;
1333         int match_len;
1334
1335         make_nxmsg_xid(sizeof *nfr, NXT_FLOW_REMOVED, htonl(0), &msg);
1336         match_len = nx_put_match(msg, &fr->rule);
1337
1338         nfr = msg->data;
1339         nfr->cookie = fr->cookie;
1340         nfr->priority = htons(fr->rule.priority);
1341         nfr->reason = fr->reason;
1342         nfr->duration_sec = htonl(fr->duration_sec);
1343         nfr->duration_nsec = htonl(fr->duration_nsec);
1344         nfr->idle_timeout = htons(fr->idle_timeout);
1345         nfr->match_len = htons(match_len);
1346         nfr->packet_count = htonll(fr->packet_count);
1347         nfr->byte_count = htonll(fr->byte_count);
1348     } else {
1349         NOT_REACHED();
1350     }
1351
1352     return msg;
1353 }
1354
1355 /* Converts abstract ofputil_packet_in 'pin' into an OFPT_PACKET_IN message
1356  * and returns the message.
1357  *
1358  * If 'rw_packet' is NULL, the caller takes ownership of the newly allocated
1359  * returned ofpbuf.
1360  *
1361  * If 'rw_packet' is nonnull, then it must contain the same data as
1362  * pin->packet.  'rw_packet' is allowed to be the same ofpbuf as pin->packet.
1363  * It is modified in-place into an OFPT_PACKET_IN message according to 'pin',
1364  * and then ofputil_encode_packet_in() returns 'rw_packet'.  If 'rw_packet' has
1365  * enough headroom to insert a "struct ofp_packet_in", this is more efficient
1366  * than ofputil_encode_packet_in() because it does not copy the packet
1367  * payload. */
1368 struct ofpbuf *
1369 ofputil_encode_packet_in(const struct ofputil_packet_in *pin,
1370                         struct ofpbuf *rw_packet)
1371 {
1372     int total_len = pin->packet->size;
1373     struct ofp_packet_in *opi;
1374
1375     if (rw_packet) {
1376         if (pin->send_len < rw_packet->size) {
1377             rw_packet->size = pin->send_len;
1378         }
1379     } else {
1380         rw_packet = ofpbuf_clone_data_with_headroom(
1381             pin->packet->data, MIN(pin->send_len, pin->packet->size),
1382             offsetof(struct ofp_packet_in, data));
1383     }
1384
1385     /* Add OFPT_PACKET_IN. */
1386     opi = ofpbuf_push_zeros(rw_packet, offsetof(struct ofp_packet_in, data));
1387     opi->header.version = OFP_VERSION;
1388     opi->header.type = OFPT_PACKET_IN;
1389     opi->total_len = htons(total_len);
1390     opi->in_port = htons(pin->in_port);
1391     opi->reason = pin->reason;
1392     opi->buffer_id = htonl(pin->buffer_id);
1393     update_openflow_length(rw_packet);
1394
1395     return rw_packet;
1396 }
1397
1398 /* Returns a string representing the message type of 'type'.  The string is the
1399  * enumeration constant for the type, e.g. "OFPT_HELLO".  For statistics
1400  * messages, the constant is followed by "request" or "reply",
1401  * e.g. "OFPST_AGGREGATE reply". */
1402 const char *
1403 ofputil_msg_type_name(const struct ofputil_msg_type *type)
1404 {
1405     return type->name;
1406 }
1407 \f
1408 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
1409  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
1410  * an arbitrary transaction id.  Allocated bytes beyond the header, if any, are
1411  * zeroed.
1412  *
1413  * The caller is responsible for freeing '*bufferp' when it is no longer
1414  * needed.
1415  *
1416  * The OpenFlow header length is initially set to 'openflow_len'; if the
1417  * message is later extended, the length should be updated with
1418  * update_openflow_length() before sending.
1419  *
1420  * Returns the header. */
1421 void *
1422 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp)
1423 {
1424     *bufferp = ofpbuf_new(openflow_len);
1425     return put_openflow_xid(openflow_len, type, alloc_xid(), *bufferp);
1426 }
1427
1428 /* Similar to make_openflow() but creates a Nicira vendor extension message
1429  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1430 void *
1431 make_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf **bufferp)
1432 {
1433     return make_nxmsg_xid(openflow_len, subtype, alloc_xid(), bufferp);
1434 }
1435
1436 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
1437  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
1438  * transaction id 'xid'.  Allocated bytes beyond the header, if any, are
1439  * zeroed.
1440  *
1441  * The caller is responsible for freeing '*bufferp' when it is no longer
1442  * needed.
1443  *
1444  * The OpenFlow header length is initially set to 'openflow_len'; if the
1445  * message is later extended, the length should be updated with
1446  * update_openflow_length() before sending.
1447  *
1448  * Returns the header. */
1449 void *
1450 make_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
1451                   struct ofpbuf **bufferp)
1452 {
1453     *bufferp = ofpbuf_new(openflow_len);
1454     return put_openflow_xid(openflow_len, type, xid, *bufferp);
1455 }
1456
1457 /* Similar to make_openflow_xid() but creates a Nicira vendor extension message
1458  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1459 void *
1460 make_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
1461                struct ofpbuf **bufferp)
1462 {
1463     *bufferp = ofpbuf_new(openflow_len);
1464     return put_nxmsg_xid(openflow_len, subtype, xid, *bufferp);
1465 }
1466
1467 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
1468  * with the given 'type' and an arbitrary transaction id.  Allocated bytes
1469  * beyond the header, if any, are zeroed.
1470  *
1471  * The OpenFlow header length is initially set to 'openflow_len'; if the
1472  * message is later extended, the length should be updated with
1473  * update_openflow_length() before sending.
1474  *
1475  * Returns the header. */
1476 void *
1477 put_openflow(size_t openflow_len, uint8_t type, struct ofpbuf *buffer)
1478 {
1479     return put_openflow_xid(openflow_len, type, alloc_xid(), buffer);
1480 }
1481
1482 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
1483  * with the given 'type' and an transaction id 'xid'.  Allocated bytes beyond
1484  * the header, if any, are zeroed.
1485  *
1486  * The OpenFlow header length is initially set to 'openflow_len'; if the
1487  * message is later extended, the length should be updated with
1488  * update_openflow_length() before sending.
1489  *
1490  * Returns the header. */
1491 void *
1492 put_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
1493                  struct ofpbuf *buffer)
1494 {
1495     struct ofp_header *oh;
1496
1497     assert(openflow_len >= sizeof *oh);
1498     assert(openflow_len <= UINT16_MAX);
1499
1500     oh = ofpbuf_put_uninit(buffer, openflow_len);
1501     oh->version = OFP_VERSION;
1502     oh->type = type;
1503     oh->length = htons(openflow_len);
1504     oh->xid = xid;
1505     memset(oh + 1, 0, openflow_len - sizeof *oh);
1506     return oh;
1507 }
1508
1509 /* Similar to put_openflow() but append a Nicira vendor extension message with
1510  * the specific 'subtype'.  'subtype' should be in host byte order. */
1511 void *
1512 put_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf *buffer)
1513 {
1514     return put_nxmsg_xid(openflow_len, subtype, alloc_xid(), buffer);
1515 }
1516
1517 /* Similar to put_openflow_xid() but append a Nicira vendor extension message
1518  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1519 void *
1520 put_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
1521               struct ofpbuf *buffer)
1522 {
1523     struct nicira_header *nxh;
1524
1525     nxh = put_openflow_xid(openflow_len, OFPT_VENDOR, xid, buffer);
1526     nxh->vendor = htonl(NX_VENDOR_ID);
1527     nxh->subtype = htonl(subtype);
1528     return nxh;
1529 }
1530
1531 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
1532  * 'buffer->size'. */
1533 void
1534 update_openflow_length(struct ofpbuf *buffer)
1535 {
1536     struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
1537     oh->length = htons(buffer->size);
1538 }
1539
1540 /* Creates an ofp_stats_request with the given 'type' and 'body_len' bytes of
1541  * space allocated for the 'body' member.  Returns the first byte of the 'body'
1542  * member. */
1543 void *
1544 ofputil_make_stats_request(size_t body_len, uint16_t type,
1545                            struct ofpbuf **bufferp)
1546 {
1547     struct ofp_stats_request *osr;
1548     osr = make_openflow((offsetof(struct ofp_stats_request, body)
1549                         + body_len), OFPT_STATS_REQUEST, bufferp);
1550     osr->type = htons(type);
1551     osr->flags = htons(0);
1552     return osr->body;
1553 }
1554
1555 /* Creates a stats request message with Nicira as vendor and the given
1556  * 'subtype', of total length 'openflow_len'.  Returns the message. */
1557 void *
1558 ofputil_make_nxstats_request(size_t openflow_len, uint32_t subtype,
1559                              struct ofpbuf **bufferp)
1560 {
1561     struct nicira_stats_msg *nsm;
1562
1563     nsm = make_openflow(openflow_len, OFPT_STATS_REQUEST, bufferp);
1564     nsm->type = htons(OFPST_VENDOR);
1565     nsm->flags = htons(0);
1566     nsm->vendor = htonl(NX_VENDOR_ID);
1567     nsm->subtype = htonl(subtype);
1568     return nsm;
1569 }
1570
1571 /* Returns the first byte of the 'body' member of the ofp_stats_request or
1572  * ofp_stats_reply in 'oh'. */
1573 const void *
1574 ofputil_stats_body(const struct ofp_header *oh)
1575 {
1576     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1577     return ((const struct ofp_stats_request *) oh)->body;
1578 }
1579
1580 /* Returns the length of the 'body' member of the ofp_stats_request or
1581  * ofp_stats_reply in 'oh'. */
1582 size_t
1583 ofputil_stats_body_len(const struct ofp_header *oh)
1584 {
1585     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1586     return ntohs(oh->length) - sizeof(struct ofp_stats_request);
1587 }
1588
1589 /* Returns the first byte of the body of the nicira_stats_msg in 'oh'. */
1590 const void *
1591 ofputil_nxstats_body(const struct ofp_header *oh)
1592 {
1593     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1594     return ((const struct nicira_stats_msg *) oh) + 1;
1595 }
1596
1597 /* Returns the length of the body of the nicira_stats_msg in 'oh'. */
1598 size_t
1599 ofputil_nxstats_body_len(const struct ofp_header *oh)
1600 {
1601     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1602     return ntohs(oh->length) - sizeof(struct nicira_stats_msg);
1603 }
1604
1605 struct ofpbuf *
1606 make_flow_mod(uint16_t command, const struct cls_rule *rule,
1607               size_t actions_len)
1608 {
1609     struct ofp_flow_mod *ofm;
1610     size_t size = sizeof *ofm + actions_len;
1611     struct ofpbuf *out = ofpbuf_new(size);
1612     ofm = ofpbuf_put_zeros(out, sizeof *ofm);
1613     ofm->header.version = OFP_VERSION;
1614     ofm->header.type = OFPT_FLOW_MOD;
1615     ofm->header.length = htons(size);
1616     ofm->cookie = 0;
1617     ofm->priority = htons(MIN(rule->priority, UINT16_MAX));
1618     ofputil_cls_rule_to_match(rule, &ofm->match);
1619     ofm->command = htons(command);
1620     return out;
1621 }
1622
1623 struct ofpbuf *
1624 make_add_flow(const struct cls_rule *rule, uint32_t buffer_id,
1625               uint16_t idle_timeout, size_t actions_len)
1626 {
1627     struct ofpbuf *out = make_flow_mod(OFPFC_ADD, rule, actions_len);
1628     struct ofp_flow_mod *ofm = out->data;
1629     ofm->idle_timeout = htons(idle_timeout);
1630     ofm->hard_timeout = htons(OFP_FLOW_PERMANENT);
1631     ofm->buffer_id = htonl(buffer_id);
1632     return out;
1633 }
1634
1635 struct ofpbuf *
1636 make_del_flow(const struct cls_rule *rule)
1637 {
1638     struct ofpbuf *out = make_flow_mod(OFPFC_DELETE_STRICT, rule, 0);
1639     struct ofp_flow_mod *ofm = out->data;
1640     ofm->out_port = htons(OFPP_NONE);
1641     return out;
1642 }
1643
1644 struct ofpbuf *
1645 make_add_simple_flow(const struct cls_rule *rule,
1646                      uint32_t buffer_id, uint16_t out_port,
1647                      uint16_t idle_timeout)
1648 {
1649     if (out_port != OFPP_NONE) {
1650         struct ofp_action_output *oao;
1651         struct ofpbuf *buffer;
1652
1653         buffer = make_add_flow(rule, buffer_id, idle_timeout, sizeof *oao);
1654         oao = ofpbuf_put_zeros(buffer, sizeof *oao);
1655         oao->type = htons(OFPAT_OUTPUT);
1656         oao->len = htons(sizeof *oao);
1657         oao->port = htons(out_port);
1658         return buffer;
1659     } else {
1660         return make_add_flow(rule, buffer_id, idle_timeout, 0);
1661     }
1662 }
1663
1664 struct ofpbuf *
1665 make_packet_in(uint32_t buffer_id, uint16_t in_port, uint8_t reason,
1666                const struct ofpbuf *payload, int max_send_len)
1667 {
1668     struct ofp_packet_in *opi;
1669     struct ofpbuf *buf;
1670     int send_len;
1671
1672     send_len = MIN(max_send_len, payload->size);
1673     buf = ofpbuf_new(sizeof *opi + send_len);
1674     opi = put_openflow_xid(offsetof(struct ofp_packet_in, data),
1675                            OFPT_PACKET_IN, 0, buf);
1676     opi->buffer_id = htonl(buffer_id);
1677     opi->total_len = htons(payload->size);
1678     opi->in_port = htons(in_port);
1679     opi->reason = reason;
1680     ofpbuf_put(buf, payload->data, send_len);
1681     update_openflow_length(buf);
1682
1683     return buf;
1684 }
1685
1686 struct ofpbuf *
1687 make_packet_out(const struct ofpbuf *packet, uint32_t buffer_id,
1688                 uint16_t in_port,
1689                 const struct ofp_action_header *actions, size_t n_actions)
1690 {
1691     size_t actions_len = n_actions * sizeof *actions;
1692     struct ofp_packet_out *opo;
1693     size_t size = sizeof *opo + actions_len + (packet ? packet->size : 0);
1694     struct ofpbuf *out = ofpbuf_new(size);
1695
1696     opo = ofpbuf_put_uninit(out, sizeof *opo);
1697     opo->header.version = OFP_VERSION;
1698     opo->header.type = OFPT_PACKET_OUT;
1699     opo->header.length = htons(size);
1700     opo->header.xid = htonl(0);
1701     opo->buffer_id = htonl(buffer_id);
1702     opo->in_port = htons(in_port == ODPP_LOCAL ? OFPP_LOCAL : in_port);
1703     opo->actions_len = htons(actions_len);
1704     ofpbuf_put(out, actions, actions_len);
1705     if (packet) {
1706         ofpbuf_put(out, packet->data, packet->size);
1707     }
1708     return out;
1709 }
1710
1711 struct ofpbuf *
1712 make_unbuffered_packet_out(const struct ofpbuf *packet,
1713                            uint16_t in_port, uint16_t out_port)
1714 {
1715     struct ofp_action_output action;
1716     action.type = htons(OFPAT_OUTPUT);
1717     action.len = htons(sizeof action);
1718     action.port = htons(out_port);
1719     return make_packet_out(packet, UINT32_MAX, in_port,
1720                            (struct ofp_action_header *) &action, 1);
1721 }
1722
1723 struct ofpbuf *
1724 make_buffered_packet_out(uint32_t buffer_id,
1725                          uint16_t in_port, uint16_t out_port)
1726 {
1727     if (out_port != OFPP_NONE) {
1728         struct ofp_action_output action;
1729         action.type = htons(OFPAT_OUTPUT);
1730         action.len = htons(sizeof action);
1731         action.port = htons(out_port);
1732         return make_packet_out(NULL, buffer_id, in_port,
1733                                (struct ofp_action_header *) &action, 1);
1734     } else {
1735         return make_packet_out(NULL, buffer_id, in_port, NULL, 0);
1736     }
1737 }
1738
1739 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
1740 struct ofpbuf *
1741 make_echo_request(void)
1742 {
1743     struct ofp_header *rq;
1744     struct ofpbuf *out = ofpbuf_new(sizeof *rq);
1745     rq = ofpbuf_put_uninit(out, sizeof *rq);
1746     rq->version = OFP_VERSION;
1747     rq->type = OFPT_ECHO_REQUEST;
1748     rq->length = htons(sizeof *rq);
1749     rq->xid = htonl(0);
1750     return out;
1751 }
1752
1753 /* Creates and returns an OFPT_ECHO_REPLY message matching the
1754  * OFPT_ECHO_REQUEST message in 'rq'. */
1755 struct ofpbuf *
1756 make_echo_reply(const struct ofp_header *rq)
1757 {
1758     size_t size = ntohs(rq->length);
1759     struct ofpbuf *out = ofpbuf_new(size);
1760     struct ofp_header *reply = ofpbuf_put(out, rq, size);
1761     reply->type = OFPT_ECHO_REPLY;
1762     return out;
1763 }
1764
1765 static int
1766 check_action_exact_len(const union ofp_action *a, unsigned int len,
1767                        unsigned int required_len)
1768 {
1769     if (len != required_len) {
1770         VLOG_WARN_RL(&bad_ofmsg_rl, "action %"PRIu16" has invalid length "
1771                      "%"PRIu16" (must be %u)\n",
1772                      ntohs(a->type), ntohs(a->header.len), required_len);
1773         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1774     }
1775     return 0;
1776 }
1777
1778 static int
1779 check_nx_action_exact_len(const struct nx_action_header *a,
1780                           unsigned int len, unsigned int required_len)
1781 {
1782     if (len != required_len) {
1783         VLOG_WARN_RL(&bad_ofmsg_rl,
1784                      "Nicira action %"PRIu16" has invalid length %"PRIu16" "
1785                      "(must be %u)\n",
1786                      ntohs(a->subtype), ntohs(a->len), required_len);
1787         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1788     }
1789     return 0;
1790 }
1791
1792 /* Checks that 'port' is a valid output port for the OFPAT_OUTPUT action, given
1793  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
1794  * 'port' is valid, otherwise an ofp_mkerr() return code. */
1795 static int
1796 check_output_port(uint16_t port, int max_ports)
1797 {
1798     switch (port) {
1799     case OFPP_IN_PORT:
1800     case OFPP_TABLE:
1801     case OFPP_NORMAL:
1802     case OFPP_FLOOD:
1803     case OFPP_ALL:
1804     case OFPP_CONTROLLER:
1805     case OFPP_LOCAL:
1806         return 0;
1807
1808     default:
1809         if (port < max_ports) {
1810             return 0;
1811         }
1812         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown output port %x", port);
1813         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
1814     }
1815 }
1816
1817 /* Checks that 'action' is a valid OFPAT_ENQUEUE action, given that the switch
1818  * will never have more than 'max_ports' ports.  Returns 0 if 'port' is valid,
1819  * otherwise an ofp_mkerr() return code. */
1820 static int
1821 check_enqueue_action(const union ofp_action *a, unsigned int len,
1822                      int max_ports)
1823 {
1824     const struct ofp_action_enqueue *oae;
1825     uint16_t port;
1826     int error;
1827
1828     error = check_action_exact_len(a, len, 16);
1829     if (error) {
1830         return error;
1831     }
1832
1833     oae = (const struct ofp_action_enqueue *) a;
1834     port = ntohs(oae->port);
1835     if (port < max_ports || port == OFPP_IN_PORT) {
1836         return 0;
1837     }
1838     VLOG_WARN_RL(&bad_ofmsg_rl, "unknown enqueue port %x", port);
1839     return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
1840 }
1841
1842 static int
1843 check_nicira_action(const union ofp_action *a, unsigned int len,
1844                     const struct flow *flow)
1845 {
1846     const struct nx_action_header *nah;
1847     int subtype;
1848     int error;
1849
1850     if (len < 16) {
1851         VLOG_WARN_RL(&bad_ofmsg_rl,
1852                      "Nicira vendor action only %u bytes", len);
1853         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1854     }
1855     nah = (const struct nx_action_header *) a;
1856
1857     subtype = ntohs(nah->subtype);
1858     if (subtype > TYPE_MAXIMUM(enum nx_action_subtype)) {
1859         /* This is necessary because enum nx_action_subtype may be an
1860          * 8-bit type, so the cast below throws away the top 8 bits. */
1861         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR_TYPE);
1862     }
1863
1864     switch ((enum nx_action_subtype) subtype) {
1865     case NXAST_RESUBMIT:
1866     case NXAST_SET_TUNNEL:
1867     case NXAST_DROP_SPOOFED_ARP:
1868     case NXAST_SET_QUEUE:
1869     case NXAST_POP_QUEUE:
1870         return check_nx_action_exact_len(nah, len, 16);
1871
1872     case NXAST_REG_MOVE:
1873         error = check_nx_action_exact_len(nah, len,
1874                                           sizeof(struct nx_action_reg_move));
1875         if (error) {
1876             return error;
1877         }
1878         return nxm_check_reg_move((const struct nx_action_reg_move *) a, flow);
1879
1880     case NXAST_REG_LOAD:
1881         error = check_nx_action_exact_len(nah, len,
1882                                           sizeof(struct nx_action_reg_load));
1883         if (error) {
1884             return error;
1885         }
1886         return nxm_check_reg_load((const struct nx_action_reg_load *) a, flow);
1887
1888     case NXAST_NOTE:
1889         return 0;
1890
1891     case NXAST_SET_TUNNEL64:
1892         return check_nx_action_exact_len(
1893             nah, len, sizeof(struct nx_action_set_tunnel64));
1894
1895     case NXAST_MULTIPATH:
1896         error = check_nx_action_exact_len(
1897             nah, len, sizeof(struct nx_action_multipath));
1898         if (error) {
1899             return error;
1900         }
1901         return multipath_check((const struct nx_action_multipath *) a);
1902
1903     case NXAST_AUTOPATH:
1904         error = check_nx_action_exact_len(
1905             nah, len, sizeof(struct nx_action_autopath));
1906         if (error) {
1907             return error;
1908         }
1909         return autopath_check((const struct nx_action_autopath *) a);
1910
1911     case NXAST_SNAT__OBSOLETE:
1912     default:
1913         VLOG_WARN_RL(&bad_ofmsg_rl,
1914                      "unknown Nicira vendor action subtype %d", subtype);
1915         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR_TYPE);
1916     }
1917 }
1918
1919 static int
1920 check_action(const union ofp_action *a, unsigned int len,
1921              const struct flow *flow, int max_ports)
1922 {
1923     enum ofp_action_type type = ntohs(a->type);
1924     int error;
1925
1926     switch (type) {
1927     case OFPAT_OUTPUT:
1928         error = check_action_exact_len(a, len, 8);
1929         if (error) {
1930             return error;
1931         }
1932         return check_output_port(ntohs(a->output.port), max_ports);
1933
1934     case OFPAT_SET_VLAN_VID:
1935         error = check_action_exact_len(a, len, 8);
1936         if (error) {
1937             return error;
1938         }
1939         if (a->vlan_vid.vlan_vid & ~htons(0xfff)) {
1940             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
1941         }
1942         return 0;
1943
1944     case OFPAT_SET_VLAN_PCP:
1945         error = check_action_exact_len(a, len, 8);
1946         if (error) {
1947             return error;
1948         }
1949         if (a->vlan_pcp.vlan_pcp & ~7) {
1950             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
1951         }
1952         return 0;
1953
1954     case OFPAT_STRIP_VLAN:
1955     case OFPAT_SET_NW_SRC:
1956     case OFPAT_SET_NW_DST:
1957     case OFPAT_SET_NW_TOS:
1958     case OFPAT_SET_TP_SRC:
1959     case OFPAT_SET_TP_DST:
1960         return check_action_exact_len(a, len, 8);
1961
1962     case OFPAT_SET_DL_SRC:
1963     case OFPAT_SET_DL_DST:
1964         return check_action_exact_len(a, len, 16);
1965
1966     case OFPAT_VENDOR:
1967         return (a->vendor.vendor == htonl(NX_VENDOR_ID)
1968                 ? check_nicira_action(a, len, flow)
1969                 : ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR));
1970
1971     case OFPAT_ENQUEUE:
1972         return check_enqueue_action(a, len, max_ports);
1973
1974     default:
1975         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown action type %d", (int) type);
1976         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_TYPE);
1977     }
1978 }
1979
1980 int
1981 validate_actions(const union ofp_action *actions, size_t n_actions,
1982                  const struct flow *flow, int max_ports)
1983 {
1984     size_t i;
1985
1986     for (i = 0; i < n_actions; ) {
1987         const union ofp_action *a = &actions[i];
1988         unsigned int len = ntohs(a->header.len);
1989         unsigned int n_slots = len / OFP_ACTION_ALIGN;
1990         unsigned int slots_left = &actions[n_actions] - a;
1991         int error;
1992
1993         if (n_slots > slots_left) {
1994             VLOG_WARN_RL(&bad_ofmsg_rl,
1995                          "action requires %u slots but only %u remain",
1996                          n_slots, slots_left);
1997             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1998         } else if (!len) {
1999             VLOG_WARN_RL(&bad_ofmsg_rl, "action has invalid length 0");
2000             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
2001         } else if (len % OFP_ACTION_ALIGN) {
2002             VLOG_WARN_RL(&bad_ofmsg_rl, "action length %u is not a multiple "
2003                          "of %d", len, OFP_ACTION_ALIGN);
2004             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
2005         }
2006
2007         error = check_action(a, len, flow, max_ports);
2008         if (error) {
2009             return error;
2010         }
2011         i += n_slots;
2012     }
2013     return 0;
2014 }
2015
2016 /* Returns true if 'action' outputs to 'port', false otherwise. */
2017 bool
2018 action_outputs_to_port(const union ofp_action *action, ovs_be16 port)
2019 {
2020     switch (ntohs(action->type)) {
2021     case OFPAT_OUTPUT:
2022         return action->output.port == port;
2023     case OFPAT_ENQUEUE:
2024         return ((const struct ofp_action_enqueue *) action)->port == port;
2025     default:
2026         return false;
2027     }
2028 }
2029
2030 /* The set of actions must either come from a trusted source or have been
2031  * previously validated with validate_actions(). */
2032 const union ofp_action *
2033 actions_first(struct actions_iterator *iter,
2034               const union ofp_action *oa, size_t n_actions)
2035 {
2036     iter->pos = oa;
2037     iter->end = oa + n_actions;
2038     return actions_next(iter);
2039 }
2040
2041 const union ofp_action *
2042 actions_next(struct actions_iterator *iter)
2043 {
2044     if (iter->pos != iter->end) {
2045         const union ofp_action *a = iter->pos;
2046         unsigned int len = ntohs(a->header.len);
2047         iter->pos += len / OFP_ACTION_ALIGN;
2048         return a;
2049     } else {
2050         return NULL;
2051     }
2052 }
2053
2054 /* "Normalizes" the wildcards in 'rule'.  That means:
2055  *
2056  *    1. If the type of level N is known, then only the valid fields for that
2057  *       level may be specified.  For example, ARP does not have a TOS field,
2058  *       so nw_tos must be wildcarded if 'rule' specifies an ARP flow.
2059  *       Similarly, IPv4 does not have any IPv6 addresses, so ipv6_src and
2060  *       ipv6_dst (and other fields) must be wildcarded if 'rule' specifies an
2061  *       IPv4 flow.
2062  *
2063  *    2. If the type of level N is not known (or not understood by Open
2064  *       vSwitch), then no fields at all for that level may be specified.  For
2065  *       example, Open vSwitch does not understand SCTP, an L4 protocol, so the
2066  *       L4 fields tp_src and tp_dst must be wildcarded if 'rule' specifies an
2067  *       SCTP flow.
2068  *
2069  * 'flow_format' specifies the format of the flow as received or as intended to
2070  * be sent.  This is important for IPv6 and ARP, for which NXM supports more
2071  * detailed matching. */
2072 void
2073 ofputil_normalize_rule(struct cls_rule *rule, enum nx_flow_format flow_format)
2074 {
2075     enum {
2076         MAY_NW_ADDR     = 1 << 0, /* nw_src, nw_dst */
2077         MAY_TP_ADDR     = 1 << 1, /* tp_src, tp_dst */
2078         MAY_NW_PROTO    = 1 << 2, /* nw_proto */
2079         MAY_NW_TOS      = 1 << 3, /* nw_tos */
2080         MAY_ARP_SHA     = 1 << 4, /* arp_sha */
2081         MAY_ARP_THA     = 1 << 5, /* arp_tha */
2082         MAY_IPV6_ADDR   = 1 << 6, /* ipv6_src, ipv6_dst */
2083         MAY_ND_TARGET   = 1 << 7  /* nd_target */
2084     } may_match;
2085
2086     struct flow_wildcards wc;
2087
2088     /* Figure out what fields may be matched. */
2089     if (rule->flow.dl_type == htons(ETH_TYPE_IP)) {
2090         may_match = MAY_NW_PROTO | MAY_NW_TOS | MAY_NW_ADDR;
2091         if (rule->flow.nw_proto == IPPROTO_TCP ||
2092             rule->flow.nw_proto == IPPROTO_UDP ||
2093             rule->flow.nw_proto == IPPROTO_ICMP) {
2094             may_match |= MAY_TP_ADDR;
2095         }
2096     } else if (rule->flow.dl_type == htons(ETH_TYPE_IPV6)
2097                && flow_format == NXFF_NXM) {
2098         may_match = MAY_NW_PROTO | MAY_NW_TOS | MAY_IPV6_ADDR;
2099         if (rule->flow.nw_proto == IPPROTO_TCP ||
2100             rule->flow.nw_proto == IPPROTO_UDP) {
2101             may_match |= MAY_TP_ADDR;
2102         } else if (rule->flow.nw_proto == IPPROTO_ICMPV6) {
2103             may_match |= MAY_TP_ADDR;
2104             if (rule->flow.tp_src == htons(ND_NEIGHBOR_SOLICIT)) {
2105                 may_match |= MAY_ND_TARGET | MAY_ARP_SHA;
2106             } else if (rule->flow.tp_src == htons(ND_NEIGHBOR_ADVERT)) {
2107                 may_match |= MAY_ND_TARGET | MAY_ARP_THA;
2108             }
2109         }
2110     } else if (rule->flow.dl_type == htons(ETH_TYPE_ARP)) {
2111         may_match = MAY_NW_PROTO | MAY_NW_ADDR;
2112         if (flow_format == NXFF_NXM) {
2113             may_match |= MAY_ARP_SHA | MAY_ARP_THA;
2114         }
2115     } else {
2116         may_match = 0;
2117     }
2118
2119     /* Clear the fields that may not be matched. */
2120     wc = rule->wc;
2121     if (!(may_match & MAY_NW_ADDR)) {
2122         wc.nw_src_mask = wc.nw_dst_mask = htonl(0);
2123     }
2124     if (!(may_match & MAY_TP_ADDR)) {
2125         wc.wildcards |= FWW_TP_SRC | FWW_TP_DST;
2126     }
2127     if (!(may_match & MAY_NW_PROTO)) {
2128         wc.wildcards |= FWW_NW_PROTO;
2129     }
2130     if (!(may_match & MAY_NW_TOS)) {
2131         wc.wildcards |= FWW_NW_TOS;
2132     }
2133     if (!(may_match & MAY_ARP_SHA)) {
2134         wc.wildcards |= FWW_ARP_SHA;
2135     }
2136     if (!(may_match & MAY_ARP_THA)) {
2137         wc.wildcards |= FWW_ARP_THA;
2138     }
2139     if (!(may_match & MAY_IPV6_ADDR)) {
2140         wc.ipv6_src_mask = wc.ipv6_dst_mask = in6addr_any;
2141     }
2142     if (!(may_match & MAY_ND_TARGET)) {
2143         wc.wildcards |= FWW_ND_TARGET;
2144     }
2145
2146     /* Log any changes. */
2147     if (!flow_wildcards_equal(&wc, &rule->wc)) {
2148         bool log = !VLOG_DROP_INFO(&bad_ofmsg_rl);
2149         char *pre = log ? cls_rule_to_string(rule) : NULL;
2150
2151         rule->wc = wc;
2152         cls_rule_zero_wildcarded_fields(rule);
2153
2154         if (log) {
2155             char *post = cls_rule_to_string(rule);
2156             VLOG_INFO("normalization changed ofp_match, details:");
2157             VLOG_INFO(" pre: %s", pre);
2158             VLOG_INFO("post: %s", post);
2159             free(pre);
2160             free(post);
2161         }
2162     }
2163 }
2164
2165 static uint32_t
2166 vendor_code_to_id(uint8_t code)
2167 {
2168     switch (code) {
2169 #define OFPUTIL_VENDOR(NAME, VENDOR_ID) case NAME: return VENDOR_ID;
2170         OFPUTIL_VENDORS
2171 #undef OFPUTIL_VENDOR
2172     default:
2173         return UINT32_MAX;
2174     }
2175 }
2176
2177 static int
2178 vendor_id_to_code(uint32_t id)
2179 {
2180     switch (id) {
2181 #define OFPUTIL_VENDOR(NAME, VENDOR_ID) case VENDOR_ID: return NAME;
2182         OFPUTIL_VENDORS
2183 #undef OFPUTIL_VENDOR
2184     default:
2185         return -1;
2186     }
2187 }
2188
2189 /* Creates and returns an OpenFlow message of type OFPT_ERROR with the error
2190  * information taken from 'error', whose encoding must be as described in the
2191  * large comment in ofp-util.h.  If 'oh' is nonnull, then the error will use
2192  * oh->xid as its transaction ID, and it will include up to the first 64 bytes
2193  * of 'oh'.
2194  *
2195  * Returns NULL if 'error' is not an OpenFlow error code. */
2196 struct ofpbuf *
2197 ofputil_encode_error_msg(int error, const struct ofp_header *oh)
2198 {
2199     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2200
2201     struct ofpbuf *buf;
2202     const void *data;
2203     size_t len;
2204     uint8_t vendor;
2205     uint16_t type;
2206     uint16_t code;
2207     ovs_be32 xid;
2208
2209     if (!is_ofp_error(error)) {
2210         /* We format 'error' with strerror() here since it seems likely to be
2211          * a system errno value. */
2212         VLOG_WARN_RL(&rl, "invalid OpenFlow error code %d (%s)",
2213                      error, strerror(error));
2214         return NULL;
2215     }
2216
2217     if (oh) {
2218         xid = oh->xid;
2219         data = oh;
2220         len = ntohs(oh->length);
2221         if (len > 64) {
2222             len = 64;
2223         }
2224     } else {
2225         xid = 0;
2226         data = NULL;
2227         len = 0;
2228     }
2229
2230     vendor = get_ofp_err_vendor(error);
2231     type = get_ofp_err_type(error);
2232     code = get_ofp_err_code(error);
2233     if (vendor == OFPUTIL_VENDOR_OPENFLOW) {
2234         struct ofp_error_msg *oem;
2235
2236         oem = make_openflow_xid(len + sizeof *oem, OFPT_ERROR, xid, &buf);
2237         oem->type = htons(type);
2238         oem->code = htons(code);
2239     } else {
2240         struct ofp_error_msg *oem;
2241         struct nx_vendor_error *nve;
2242         uint32_t vendor_id;
2243
2244         vendor_id = vendor_code_to_id(vendor);
2245         if (vendor_id == UINT32_MAX) {
2246             VLOG_WARN_RL(&rl, "error %x contains invalid vendor code %d",
2247                          error, vendor);
2248             return NULL;
2249         }
2250
2251         oem = make_openflow_xid(len + sizeof *oem + sizeof *nve,
2252                                 OFPT_ERROR, xid, &buf);
2253         oem->type = htons(NXET_VENDOR);
2254         oem->code = htons(NXVC_VENDOR_ERROR);
2255
2256         nve = (struct nx_vendor_error *)oem->data;
2257         nve->vendor = htonl(vendor_id);
2258         nve->type = htons(type);
2259         nve->code = htons(code);
2260     }
2261
2262     if (len) {
2263         buf->size -= len;
2264         ofpbuf_put(buf, data, len);
2265     }
2266
2267     return buf;
2268 }
2269
2270 /* Decodes 'oh', which should be an OpenFlow OFPT_ERROR message, and returns an
2271  * Open vSwitch internal error code in the format described in the large
2272  * comment in ofp-util.h.
2273  *
2274  * If 'payload_ofs' is nonnull, on success '*payload_ofs' is set to the offset
2275  * to the payload starting from 'oh' and on failure it is set to 0. */
2276 int
2277 ofputil_decode_error_msg(const struct ofp_header *oh, size_t *payload_ofs)
2278 {
2279     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2280
2281     const struct ofp_error_msg *oem;
2282     uint16_t type, code;
2283     struct ofpbuf b;
2284     int vendor;
2285
2286     if (payload_ofs) {
2287         *payload_ofs = 0;
2288     }
2289     if (oh->type != OFPT_ERROR) {
2290         return EPROTO;
2291     }
2292
2293     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2294     oem = ofpbuf_try_pull(&b, sizeof *oem);
2295     if (!oem) {
2296         return EPROTO;
2297     }
2298
2299     type = ntohs(oem->type);
2300     code = ntohs(oem->code);
2301     if (type == NXET_VENDOR && code == NXVC_VENDOR_ERROR) {
2302         const struct nx_vendor_error *nve = ofpbuf_try_pull(&b, sizeof *nve);
2303         if (!nve) {
2304             return EPROTO;
2305         }
2306
2307         vendor = vendor_id_to_code(ntohl(nve->vendor));
2308         if (vendor < 0) {
2309             VLOG_WARN_RL(&rl, "error contains unknown vendor ID %#"PRIx32,
2310                          ntohl(nve->vendor));
2311             return EPROTO;
2312         }
2313         type = ntohs(nve->type);
2314         code = ntohs(nve->code);
2315     } else {
2316         vendor = OFPUTIL_VENDOR_OPENFLOW;
2317     }
2318
2319     if (type >= 1024) {
2320         VLOG_WARN_RL(&rl, "error contains type %"PRIu16" greater than "
2321                      "supported maximum value 1023", type);
2322         return EPROTO;
2323     }
2324
2325     if (payload_ofs) {
2326         *payload_ofs = (uint8_t *) b.data - (uint8_t *) oh;
2327     }
2328     return ofp_mkerr_vendor(vendor, type, code);
2329 }
2330
2331 void
2332 ofputil_format_error(struct ds *s, int error)
2333 {
2334     if (is_errno(error)) {
2335         ds_put_cstr(s, strerror(error));
2336     } else {
2337         uint16_t type = get_ofp_err_type(error);
2338         uint16_t code = get_ofp_err_code(error);
2339         const char *type_s = ofp_error_type_to_string(type);
2340         const char *code_s = ofp_error_code_to_string(type, code);
2341
2342         ds_put_format(s, "type ");
2343         if (type_s) {
2344             ds_put_cstr(s, type_s);
2345         } else {
2346             ds_put_format(s, "%"PRIu16, type);
2347         }
2348
2349         ds_put_cstr(s, ", code ");
2350         if (code_s) {
2351             ds_put_cstr(s, code_s);
2352         } else {
2353             ds_put_format(s, "%"PRIu16, code);
2354         }
2355     }
2356 }
2357
2358 char *
2359 ofputil_error_to_string(int error)
2360 {
2361     struct ds s = DS_EMPTY_INITIALIZER;
2362     ofputil_format_error(&s, error);
2363     return ds_steal_cstr(&s);
2364 }
2365
2366 /* Attempts to pull 'actions_len' bytes from the front of 'b'.  Returns 0 if
2367  * successful, otherwise an OpenFlow error.
2368  *
2369  * If successful, the first action is stored in '*actionsp' and the number of
2370  * "union ofp_action" size elements into '*n_actionsp'.  Otherwise NULL and 0
2371  * are stored, respectively.
2372  *
2373  * This function does not check that the actions are valid (the caller should
2374  * do so, with validate_actions()).  The caller is also responsible for making
2375  * sure that 'b->data' is initially aligned appropriately for "union
2376  * ofp_action". */
2377 int
2378 ofputil_pull_actions(struct ofpbuf *b, unsigned int actions_len,
2379                      union ofp_action **actionsp, size_t *n_actionsp)
2380 {
2381     if (actions_len % OFP_ACTION_ALIGN != 0) {
2382         VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
2383                      "is not a multiple of %d", actions_len, OFP_ACTION_ALIGN);
2384         goto error;
2385     }
2386
2387     *actionsp = ofpbuf_try_pull(b, actions_len);
2388     if (*actionsp == NULL) {
2389         VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
2390                      "exceeds remaining message length (%zu)",
2391                      actions_len, b->size);
2392         goto error;
2393     }
2394
2395     *n_actionsp = actions_len / OFP_ACTION_ALIGN;
2396     return 0;
2397
2398 error:
2399     *actionsp = NULL;
2400     *n_actionsp = 0;
2401     return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
2402 }