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