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