ofp-util: Export (again) a generalized function for normalizing rules.
[sliver-openvswitch.git] / lib / ofp-util.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "ofp-print.h"
19 #include <errno.h>
20 #include <inttypes.h>
21 #include <netinet/icmp6.h>
22 #include <stdlib.h>
23 #include "autopath.h"
24 #include "byte-order.h"
25 #include "classifier.h"
26 #include "dynamic-string.h"
27 #include "multipath.h"
28 #include "nx-match.h"
29 #include "ofp-errors.h"
30 #include "ofp-util.h"
31 #include "ofpbuf.h"
32 #include "packets.h"
33 #include "random.h"
34 #include "unaligned.h"
35 #include "type-props.h"
36 #include "vlog.h"
37
38 VLOG_DEFINE_THIS_MODULE(ofp_util);
39
40 /* Rate limit for OpenFlow message parse errors.  These always indicate a bug
41  * in the peer and so there's not much point in showing a lot of them. */
42 static struct vlog_rate_limit bad_ofmsg_rl = VLOG_RATE_LIMIT_INIT(1, 5);
43
44 /* Given the wildcard bit count in the least-significant 6 of 'wcbits', returns
45  * an IP netmask with a 1 in each bit that must match and a 0 in each bit that
46  * is wildcarded.
47  *
48  * The bits in 'wcbits' are in the format used in enum ofp_flow_wildcards: 0
49  * is exact match, 1 ignores the LSB, 2 ignores the 2 least-significant bits,
50  * ..., 32 and higher wildcard the entire field.  This is the *opposite* of the
51  * usual convention where e.g. /24 indicates that 8 bits (not 24 bits) are
52  * wildcarded. */
53 ovs_be32
54 ofputil_wcbits_to_netmask(int wcbits)
55 {
56     wcbits &= 0x3f;
57     return wcbits < 32 ? htonl(~((1u << wcbits) - 1)) : 0;
58 }
59
60 /* Given the IP netmask 'netmask', returns the number of bits of the IP address
61  * that it wildcards.  'netmask' must be a CIDR netmask (see ip_is_cidr()). */
62 int
63 ofputil_netmask_to_wcbits(ovs_be32 netmask)
64 {
65     assert(ip_is_cidr(netmask));
66 #if __GNUC__ >= 4
67     return netmask == htonl(0) ? 32 : __builtin_ctz(ntohl(netmask));
68 #else
69     int wcbits;
70
71     for (wcbits = 32; netmask; wcbits--) {
72         netmask &= netmask - 1;
73     }
74
75     return wcbits;
76 #endif
77 }
78
79 /* A list of the FWW_* and OFPFW_ bits that have the same value, meaning, and
80  * name. */
81 #define WC_INVARIANT_LIST \
82     WC_INVARIANT_BIT(IN_PORT) \
83     WC_INVARIANT_BIT(DL_SRC) \
84     WC_INVARIANT_BIT(DL_DST) \
85     WC_INVARIANT_BIT(DL_TYPE) \
86     WC_INVARIANT_BIT(NW_PROTO) \
87     WC_INVARIANT_BIT(TP_SRC) \
88     WC_INVARIANT_BIT(TP_DST)
89
90 /* Verify that all of the invariant bits (as defined on WC_INVARIANT_LIST)
91  * actually have the same names and values. */
92 #define WC_INVARIANT_BIT(NAME) BUILD_ASSERT_DECL(FWW_##NAME == OFPFW_##NAME);
93     WC_INVARIANT_LIST
94 #undef WC_INVARIANT_BIT
95
96 /* WC_INVARIANTS is the invariant bits (as defined on WC_INVARIANT_LIST) all
97  * OR'd together. */
98 static const flow_wildcards_t WC_INVARIANTS = 0
99 #define WC_INVARIANT_BIT(NAME) | FWW_##NAME
100     WC_INVARIANT_LIST
101 #undef WC_INVARIANT_BIT
102 ;
103
104 /* Converts the 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     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 = (OVS_FORCE flow_wildcards_t) 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     uint32_t ofpfw;
203
204     /* Figure out most OpenFlow wildcards. */
205     ofpfw = (OVS_FORCE uint32_t) (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
343     for (type = cat->types; type < &cat->types[cat->n_types]; type++) {
344         if (type->value == value) {
345             if (!ofputil_length_ok(cat, type, size)) {
346                 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
347             }
348             *typep = type;
349             return 0;
350         }
351     }
352
353     VLOG_WARN_RL(&bad_ofmsg_rl, "received %s of unknown type %"PRIu32,
354                  cat->name, value);
355     return cat->missing_error;
356 }
357
358 static int
359 ofputil_decode_vendor(const struct ofp_header *oh,
360                       const struct ofputil_msg_type **typep)
361 {
362     BUILD_ASSERT_DECL(sizeof(struct nxt_set_flow_format)
363                       != sizeof(struct nxt_flow_mod_table_id));
364
365     static const struct ofputil_msg_type nxt_messages[] = {
366         { OFPUTIL_NXT_ROLE_REQUEST,
367           NXT_ROLE_REQUEST, "NXT_ROLE_REQUEST",
368           sizeof(struct nx_role_request), 0 },
369
370         { OFPUTIL_NXT_ROLE_REPLY,
371           NXT_ROLE_REPLY, "NXT_ROLE_REPLY",
372           sizeof(struct nx_role_request), 0 },
373
374         { OFPUTIL_NXT_SET_FLOW_FORMAT,
375           NXT_SET_FLOW_FORMAT, "NXT_SET_FLOW_FORMAT",
376           sizeof(struct nxt_set_flow_format), 0 },
377
378         { OFPUTIL_NXT_FLOW_MOD,
379           NXT_FLOW_MOD, "NXT_FLOW_MOD",
380           sizeof(struct nx_flow_mod), 8 },
381
382         { OFPUTIL_NXT_FLOW_REMOVED,
383           NXT_FLOW_REMOVED, "NXT_FLOW_REMOVED",
384           sizeof(struct nx_flow_removed), 8 },
385     };
386
387     static const struct ofputil_msg_category nxt_category = {
388         "Nicira extension message",
389         nxt_messages, ARRAY_SIZE(nxt_messages),
390         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE)
391     };
392
393     const struct ofp_vendor_header *ovh;
394     const struct nicira_header *nh;
395
396     ovh = (const struct ofp_vendor_header *) oh;
397     if (ovh->vendor != htonl(NX_VENDOR_ID)) {
398         VLOG_WARN_RL(&bad_ofmsg_rl, "received vendor message for unknown "
399                      "vendor %"PRIx32, ntohl(ovh->vendor));
400         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_VENDOR);
401     }
402
403     if (ntohs(ovh->header.length) < sizeof(struct nicira_header)) {
404         VLOG_WARN_RL(&bad_ofmsg_rl, "received Nicira vendor message of "
405                      "length %u (expected at least %zu)",
406                      ntohs(ovh->header.length), sizeof(struct nicira_header));
407         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
408     }
409
410     nh = (const struct nicira_header *) oh;
411
412     if (nh->subtype == htonl(NXT_FLOW_MOD_TABLE_ID)
413         && oh->length == htons(sizeof(struct nxt_flow_mod_table_id))) {
414         /* NXT_SET_FLOW_FORMAT and NXT_FLOW_MOD_TABLE_ID accidentally have the
415          * same value but different lengths.  ofputil_lookup_openflow_message()
416          * doesn't support this case, so special case it here. */
417         static const struct ofputil_msg_type nxt_flow_mod_table_id =
418             { OFPUTIL_NXT_FLOW_MOD_TABLE_ID,
419               NXT_FLOW_MOD_TABLE_ID, "NXT_FLOW_MOD_TABLE_ID",
420               sizeof(struct nxt_flow_mod_table_id), 0 };
421
422         *typep = &nxt_flow_mod_table_id;
423         return 0;
424     }
425
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         const struct ofp_flow_mod *ofm;
906         uint16_t priority;
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         /* Set priority based on original wildcards.  Normally we'd allow
917          * ofputil_cls_rule_from_match() to do this for us, but
918          * ofputil_normalize_rule() can put wildcards where the original flow
919          * didn't have them. */
920         priority = ntohs(ofm->priority);
921         if (!(ofm->match.wildcards & htonl(OFPFW_ALL))) {
922             priority = UINT16_MAX;
923         }
924
925         /* Translate the rule. */
926         ofputil_cls_rule_from_match(&ofm->match, priority, &fm->cr);
927         ofputil_normalize_rule(&fm->cr, NXFF_OPENFLOW10);
928
929         /* Translate the message. */
930         fm->cookie = ofm->cookie;
931         command = ntohs(ofm->command);
932         fm->idle_timeout = ntohs(ofm->idle_timeout);
933         fm->hard_timeout = ntohs(ofm->hard_timeout);
934         fm->buffer_id = ntohl(ofm->buffer_id);
935         fm->out_port = ntohs(ofm->out_port);
936         fm->flags = ntohs(ofm->flags);
937     } else if (ofputil_msg_type_code(type) == OFPUTIL_NXT_FLOW_MOD) {
938         /* Nicira extended flow_mod. */
939         const struct nx_flow_mod *nfm;
940         int error;
941
942         /* Dissect the message. */
943         nfm = ofpbuf_pull(&b, sizeof *nfm);
944         error = nx_pull_match(&b, ntohs(nfm->match_len), ntohs(nfm->priority),
945                               &fm->cr);
946         if (error) {
947             return error;
948         }
949         error = ofputil_pull_actions(&b, b.size, &fm->actions, &fm->n_actions);
950         if (error) {
951             return error;
952         }
953
954         /* Translate the message. */
955         fm->cookie = nfm->cookie;
956         command = ntohs(nfm->command);
957         fm->idle_timeout = ntohs(nfm->idle_timeout);
958         fm->hard_timeout = ntohs(nfm->hard_timeout);
959         fm->buffer_id = ntohl(nfm->buffer_id);
960         fm->out_port = ntohs(nfm->out_port);
961         fm->flags = ntohs(nfm->flags);
962     } else {
963         NOT_REACHED();
964     }
965
966     if (flow_mod_table_id) {
967         fm->command = command & 0xff;
968         fm->table_id = command >> 8;
969     } else {
970         fm->command = command;
971         fm->table_id = 0xff;
972     }
973
974     return 0;
975 }
976
977 /* Converts 'fm' into an OFPT_FLOW_MOD or NXT_FLOW_MOD message according to
978  * 'flow_format' and returns the message.
979  *
980  * 'flow_mod_table_id' should be true if the NXT_FLOW_MOD_TABLE_ID extension is
981  * enabled, false otherwise. */
982 struct ofpbuf *
983 ofputil_encode_flow_mod(const struct flow_mod *fm,
984                         enum nx_flow_format flow_format,
985                         bool flow_mod_table_id)
986 {
987     size_t actions_len = fm->n_actions * sizeof *fm->actions;
988     struct ofpbuf *msg;
989     uint16_t command;
990
991     command = (flow_mod_table_id
992                ? (fm->command & 0xff) | (fm->table_id << 8)
993                : fm->command);
994
995     if (flow_format == NXFF_OPENFLOW10) {
996         struct ofp_flow_mod *ofm;
997
998         msg = ofpbuf_new(sizeof *ofm + actions_len);
999         ofm = put_openflow(sizeof *ofm, OFPT_FLOW_MOD, msg);
1000         ofputil_cls_rule_to_match(&fm->cr, &ofm->match);
1001         ofm->cookie = fm->cookie;
1002         ofm->command = htons(fm->command);
1003         ofm->idle_timeout = htons(fm->idle_timeout);
1004         ofm->hard_timeout = htons(fm->hard_timeout);
1005         ofm->priority = htons(fm->cr.priority);
1006         ofm->buffer_id = htonl(fm->buffer_id);
1007         ofm->out_port = htons(fm->out_port);
1008         ofm->flags = htons(fm->flags);
1009     } else if (flow_format == NXFF_NXM) {
1010         struct nx_flow_mod *nfm;
1011         int match_len;
1012
1013         msg = ofpbuf_new(sizeof *nfm + NXM_TYPICAL_LEN + actions_len);
1014         put_nxmsg(sizeof *nfm, NXT_FLOW_MOD, msg);
1015         match_len = nx_put_match(msg, &fm->cr);
1016
1017         nfm = msg->data;
1018         nfm->cookie = fm->cookie;
1019         nfm->command = htons(command);
1020         nfm->idle_timeout = htons(fm->idle_timeout);
1021         nfm->hard_timeout = htons(fm->hard_timeout);
1022         nfm->priority = htons(fm->cr.priority);
1023         nfm->buffer_id = htonl(fm->buffer_id);
1024         nfm->out_port = htons(fm->out_port);
1025         nfm->flags = htons(fm->flags);
1026         nfm->match_len = htons(match_len);
1027     } else {
1028         NOT_REACHED();
1029     }
1030
1031     ofpbuf_put(msg, fm->actions, actions_len);
1032     update_openflow_length(msg);
1033     return msg;
1034 }
1035
1036 static int
1037 ofputil_decode_ofpst_flow_request(struct flow_stats_request *fsr,
1038                                   const struct ofp_header *oh,
1039                                   bool aggregate)
1040 {
1041     const struct ofp_flow_stats_request *ofsr = ofputil_stats_body(oh);
1042
1043     fsr->aggregate = aggregate;
1044     ofputil_cls_rule_from_match(&ofsr->match, 0, &fsr->match);
1045     fsr->out_port = ntohs(ofsr->out_port);
1046     fsr->table_id = ofsr->table_id;
1047
1048     return 0;
1049 }
1050
1051 static int
1052 ofputil_decode_nxst_flow_request(struct flow_stats_request *fsr,
1053                                  const struct ofp_header *oh,
1054                                  bool aggregate)
1055 {
1056     const struct nx_flow_stats_request *nfsr;
1057     struct ofpbuf b;
1058     int error;
1059
1060     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1061
1062     nfsr = ofpbuf_pull(&b, sizeof *nfsr);
1063     error = nx_pull_match(&b, ntohs(nfsr->match_len), 0, &fsr->match);
1064     if (error) {
1065         return error;
1066     }
1067     if (b.size) {
1068         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1069     }
1070
1071     fsr->aggregate = aggregate;
1072     fsr->out_port = ntohs(nfsr->out_port);
1073     fsr->table_id = nfsr->table_id;
1074
1075     return 0;
1076 }
1077
1078 /* Converts an OFPST_FLOW, OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE
1079  * request 'oh', into an abstract flow_stats_request in 'fsr'.  Returns 0 if
1080  * successful, otherwise an OpenFlow error code. */
1081 int
1082 ofputil_decode_flow_stats_request(struct flow_stats_request *fsr,
1083                                   const struct ofp_header *oh)
1084 {
1085     const struct ofputil_msg_type *type;
1086     struct ofpbuf b;
1087     int code;
1088
1089     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1090
1091     ofputil_decode_msg_type(oh, &type);
1092     code = ofputil_msg_type_code(type);
1093     switch (code) {
1094     case OFPUTIL_OFPST_FLOW_REQUEST:
1095         return ofputil_decode_ofpst_flow_request(fsr, oh, false);
1096
1097     case OFPUTIL_OFPST_AGGREGATE_REQUEST:
1098         return ofputil_decode_ofpst_flow_request(fsr, oh, true);
1099
1100     case OFPUTIL_NXST_FLOW_REQUEST:
1101         return ofputil_decode_nxst_flow_request(fsr, oh, false);
1102
1103     case OFPUTIL_NXST_AGGREGATE_REQUEST:
1104         return ofputil_decode_nxst_flow_request(fsr, oh, true);
1105
1106     default:
1107         /* Hey, the caller lied. */
1108         NOT_REACHED();
1109     }
1110 }
1111
1112 /* Converts abstract flow_stats_request 'fsr' into an OFPST_FLOW,
1113  * OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE request 'oh' according to
1114  * 'flow_format', and returns the message. */
1115 struct ofpbuf *
1116 ofputil_encode_flow_stats_request(const struct flow_stats_request *fsr,
1117                                   enum nx_flow_format flow_format)
1118 {
1119     struct ofpbuf *msg;
1120
1121     if (flow_format == NXFF_OPENFLOW10) {
1122         struct ofp_flow_stats_request *ofsr;
1123         int type;
1124
1125         BUILD_ASSERT_DECL(sizeof(struct ofp_flow_stats_request)
1126                           == sizeof(struct ofp_aggregate_stats_request));
1127
1128         type = fsr->aggregate ? OFPST_AGGREGATE : OFPST_FLOW;
1129         ofsr = ofputil_make_stats_request(sizeof *ofsr, type, &msg);
1130         ofputil_cls_rule_to_match(&fsr->match, &ofsr->match);
1131         ofsr->table_id = fsr->table_id;
1132         ofsr->out_port = htons(fsr->out_port);
1133     } else if (flow_format == NXFF_NXM) {
1134         struct nx_flow_stats_request *nfsr;
1135         int match_len;
1136         int subtype;
1137
1138         subtype = fsr->aggregate ? NXST_AGGREGATE : NXST_FLOW;
1139         ofputil_make_nxstats_request(sizeof *nfsr, subtype, &msg);
1140         match_len = nx_put_match(msg, &fsr->match);
1141
1142         nfsr = msg->data;
1143         nfsr->out_port = htons(fsr->out_port);
1144         nfsr->match_len = htons(match_len);
1145         nfsr->table_id = fsr->table_id;
1146     } else {
1147         NOT_REACHED();
1148     }
1149
1150     return msg;
1151 }
1152
1153 /* Converts an OFPST_FLOW or NXST_FLOW reply in 'msg' into an abstract
1154  * ofputil_flow_stats in 'fs'.
1155  *
1156  * Multiple OFPST_FLOW or NXST_FLOW replies can be packed into a single
1157  * OpenFlow message.  Calling this function multiple times for a single 'msg'
1158  * iterates through the replies.  The caller must initially leave 'msg''s layer
1159  * pointers null and not modify them between calls.
1160  *
1161  * Returns 0 if successful, EOF if no replies were left in this 'msg',
1162  * otherwise a positive errno value. */
1163 int
1164 ofputil_decode_flow_stats_reply(struct ofputil_flow_stats *fs,
1165                                 struct ofpbuf *msg)
1166 {
1167     const struct ofputil_msg_type *type;
1168     int code;
1169
1170     ofputil_decode_msg_type(msg->l2 ? msg->l2 : msg->data, &type);
1171     code = ofputil_msg_type_code(type);
1172     if (!msg->l2) {
1173         msg->l2 = msg->data;
1174         if (code == OFPUTIL_OFPST_FLOW_REPLY) {
1175             ofpbuf_pull(msg, sizeof(struct ofp_stats_reply));
1176         } else if (code == OFPUTIL_NXST_FLOW_REPLY) {
1177             ofpbuf_pull(msg, sizeof(struct nicira_stats_msg));
1178         } else {
1179             NOT_REACHED();
1180         }
1181     }
1182
1183     if (!msg->size) {
1184         return EOF;
1185     } else if (code == OFPUTIL_OFPST_FLOW_REPLY) {
1186         const struct ofp_flow_stats *ofs;
1187         size_t length;
1188
1189         ofs = ofpbuf_try_pull(msg, sizeof *ofs);
1190         if (!ofs) {
1191             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply has %zu leftover "
1192                          "bytes at end", msg->size);
1193             return EINVAL;
1194         }
1195
1196         length = ntohs(ofs->length);
1197         if (length < sizeof *ofs) {
1198             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply claims invalid "
1199                          "length %zu", length);
1200             return EINVAL;
1201         }
1202
1203         if (ofputil_pull_actions(msg, length - sizeof *ofs,
1204                                  &fs->actions, &fs->n_actions)) {
1205             return EINVAL;
1206         }
1207
1208         fs->cookie = get_32aligned_be64(&ofs->cookie);
1209         ofputil_cls_rule_from_match(&ofs->match, ntohs(ofs->priority),
1210                                     &fs->rule);
1211         fs->table_id = ofs->table_id;
1212         fs->duration_sec = ntohl(ofs->duration_sec);
1213         fs->duration_nsec = ntohl(ofs->duration_nsec);
1214         fs->idle_timeout = ntohs(ofs->idle_timeout);
1215         fs->hard_timeout = ntohs(ofs->hard_timeout);
1216         fs->packet_count = ntohll(get_32aligned_be64(&ofs->packet_count));
1217         fs->byte_count = ntohll(get_32aligned_be64(&ofs->byte_count));
1218     } else if (code == OFPUTIL_NXST_FLOW_REPLY) {
1219         const struct nx_flow_stats *nfs;
1220         size_t match_len, length;
1221
1222         nfs = ofpbuf_try_pull(msg, sizeof *nfs);
1223         if (!nfs) {
1224             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply has %zu leftover "
1225                          "bytes at end", msg->size);
1226             return EINVAL;
1227         }
1228
1229         length = ntohs(nfs->length);
1230         match_len = ntohs(nfs->match_len);
1231         if (length < sizeof *nfs + ROUND_UP(match_len, 8)) {
1232             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply with match_len=%zu "
1233                          "claims invalid length %zu", match_len, length);
1234             return EINVAL;
1235         }
1236         if (nx_pull_match(msg, match_len, ntohs(nfs->priority), &fs->rule)) {
1237             return EINVAL;
1238         }
1239
1240         if (ofputil_pull_actions(msg,
1241                                  length - sizeof *nfs - ROUND_UP(match_len, 8),
1242                                  &fs->actions, &fs->n_actions)) {
1243             return EINVAL;
1244         }
1245
1246         fs->cookie = nfs->cookie;
1247         fs->table_id = nfs->table_id;
1248         fs->duration_sec = ntohl(nfs->duration_sec);
1249         fs->duration_nsec = ntohl(nfs->duration_nsec);
1250         fs->idle_timeout = ntohs(nfs->idle_timeout);
1251         fs->hard_timeout = ntohs(nfs->hard_timeout);
1252         fs->packet_count = ntohll(nfs->packet_count);
1253         fs->byte_count = ntohll(nfs->byte_count);
1254     } else {
1255         NOT_REACHED();
1256     }
1257
1258     return 0;
1259 }
1260
1261 /* Converts an OFPT_FLOW_REMOVED or NXT_FLOW_REMOVED message 'oh' into an
1262  * abstract ofputil_flow_removed in 'fr'.  Returns 0 if successful, otherwise
1263  * an OpenFlow error code. */
1264 int
1265 ofputil_decode_flow_removed(struct ofputil_flow_removed *fr,
1266                             const struct ofp_header *oh)
1267 {
1268     const struct ofputil_msg_type *type;
1269     enum ofputil_msg_code code;
1270
1271     ofputil_decode_msg_type(oh, &type);
1272     code = ofputil_msg_type_code(type);
1273     if (code == OFPUTIL_OFPT_FLOW_REMOVED) {
1274         const struct ofp_flow_removed *ofr;
1275
1276         ofr = (const struct ofp_flow_removed *) oh;
1277         ofputil_cls_rule_from_match(&ofr->match, ntohs(ofr->priority),
1278                                     &fr->rule);
1279         fr->cookie = ofr->cookie;
1280         fr->reason = ofr->reason;
1281         fr->duration_sec = ntohl(ofr->duration_sec);
1282         fr->duration_nsec = ntohl(ofr->duration_nsec);
1283         fr->idle_timeout = ntohs(ofr->idle_timeout);
1284         fr->packet_count = ntohll(ofr->packet_count);
1285         fr->byte_count = ntohll(ofr->byte_count);
1286     } else if (code == OFPUTIL_NXT_FLOW_REMOVED) {
1287         struct nx_flow_removed *nfr;
1288         struct ofpbuf b;
1289         int error;
1290
1291         ofpbuf_use_const(&b, oh, ntohs(oh->length));
1292
1293         nfr = ofpbuf_pull(&b, sizeof *nfr);
1294         error = nx_pull_match(&b, ntohs(nfr->match_len), ntohs(nfr->priority),
1295                               &fr->rule);
1296         if (error) {
1297             return error;
1298         }
1299         if (b.size) {
1300             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1301         }
1302
1303         fr->cookie = nfr->cookie;
1304         fr->reason = nfr->reason;
1305         fr->duration_sec = ntohl(nfr->duration_sec);
1306         fr->duration_nsec = ntohl(nfr->duration_nsec);
1307         fr->idle_timeout = ntohs(nfr->idle_timeout);
1308         fr->packet_count = ntohll(nfr->packet_count);
1309         fr->byte_count = ntohll(nfr->byte_count);
1310     } else {
1311         NOT_REACHED();
1312     }
1313
1314     return 0;
1315 }
1316
1317 /* Converts abstract ofputil_flow_removed 'fr' into an OFPT_FLOW_REMOVED or
1318  * NXT_FLOW_REMOVED message 'oh' according to 'flow_format', and returns the
1319  * message. */
1320 struct ofpbuf *
1321 ofputil_encode_flow_removed(const struct ofputil_flow_removed *fr,
1322                             enum nx_flow_format flow_format)
1323 {
1324     struct ofpbuf *msg;
1325
1326     if (flow_format == NXFF_OPENFLOW10) {
1327         struct ofp_flow_removed *ofr;
1328
1329         ofr = make_openflow_xid(sizeof *ofr, OFPT_FLOW_REMOVED, htonl(0),
1330                                 &msg);
1331         ofputil_cls_rule_to_match(&fr->rule, &ofr->match);
1332         ofr->cookie = fr->cookie;
1333         ofr->priority = htons(fr->rule.priority);
1334         ofr->reason = fr->reason;
1335         ofr->duration_sec = htonl(fr->duration_sec);
1336         ofr->duration_nsec = htonl(fr->duration_nsec);
1337         ofr->idle_timeout = htons(fr->idle_timeout);
1338         ofr->packet_count = htonll(fr->packet_count);
1339         ofr->byte_count = htonll(fr->byte_count);
1340     } else if (flow_format == NXFF_NXM) {
1341         struct nx_flow_removed *nfr;
1342         int match_len;
1343
1344         make_nxmsg_xid(sizeof *nfr, NXT_FLOW_REMOVED, htonl(0), &msg);
1345         match_len = nx_put_match(msg, &fr->rule);
1346
1347         nfr = msg->data;
1348         nfr->cookie = fr->cookie;
1349         nfr->priority = htons(fr->rule.priority);
1350         nfr->reason = fr->reason;
1351         nfr->duration_sec = htonl(fr->duration_sec);
1352         nfr->duration_nsec = htonl(fr->duration_nsec);
1353         nfr->idle_timeout = htons(fr->idle_timeout);
1354         nfr->match_len = htons(match_len);
1355         nfr->packet_count = htonll(fr->packet_count);
1356         nfr->byte_count = htonll(fr->byte_count);
1357     } else {
1358         NOT_REACHED();
1359     }
1360
1361     return msg;
1362 }
1363
1364 /* Converts abstract ofputil_packet_in 'pin' into an OFPT_PACKET_IN message
1365  * and returns the message.
1366  *
1367  * If 'rw_packet' is NULL, the caller takes ownership of the newly allocated
1368  * returned ofpbuf.
1369  *
1370  * If 'rw_packet' is nonnull, then it must contain the same data as
1371  * pin->packet.  'rw_packet' is allowed to be the same ofpbuf as pin->packet.
1372  * It is modified in-place into an OFPT_PACKET_IN message according to 'pin',
1373  * and then ofputil_encode_packet_in() returns 'rw_packet'.  If 'rw_packet' has
1374  * enough headroom to insert a "struct ofp_packet_in", this is more efficient
1375  * than ofputil_encode_packet_in() because it does not copy the packet
1376  * payload. */
1377 struct ofpbuf *
1378 ofputil_encode_packet_in(const struct ofputil_packet_in *pin,
1379                         struct ofpbuf *rw_packet)
1380 {
1381     int total_len = pin->packet->size;
1382     struct ofp_packet_in *opi;
1383
1384     if (rw_packet) {
1385         if (pin->send_len < rw_packet->size) {
1386             rw_packet->size = pin->send_len;
1387         }
1388     } else {
1389         rw_packet = ofpbuf_clone_data_with_headroom(
1390             pin->packet->data, MIN(pin->send_len, pin->packet->size),
1391             offsetof(struct ofp_packet_in, data));
1392     }
1393
1394     /* Add OFPT_PACKET_IN. */
1395     opi = ofpbuf_push_zeros(rw_packet, offsetof(struct ofp_packet_in, data));
1396     opi->header.version = OFP_VERSION;
1397     opi->header.type = OFPT_PACKET_IN;
1398     opi->total_len = htons(total_len);
1399     opi->in_port = htons(pin->in_port);
1400     opi->reason = pin->reason;
1401     opi->buffer_id = htonl(pin->buffer_id);
1402     update_openflow_length(rw_packet);
1403
1404     return rw_packet;
1405 }
1406
1407 /* Returns a string representing the message type of 'type'.  The string is the
1408  * enumeration constant for the type, e.g. "OFPT_HELLO".  For statistics
1409  * messages, the constant is followed by "request" or "reply",
1410  * e.g. "OFPST_AGGREGATE reply". */
1411 const char *
1412 ofputil_msg_type_name(const struct ofputil_msg_type *type)
1413 {
1414     return type->name;
1415 }
1416 \f
1417 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
1418  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
1419  * an arbitrary transaction id.  Allocated bytes beyond the header, if any, are
1420  * zeroed.
1421  *
1422  * The caller is responsible for freeing '*bufferp' when it is no longer
1423  * needed.
1424  *
1425  * The OpenFlow header length is initially set to 'openflow_len'; if the
1426  * message is later extended, the length should be updated with
1427  * update_openflow_length() before sending.
1428  *
1429  * Returns the header. */
1430 void *
1431 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp)
1432 {
1433     *bufferp = ofpbuf_new(openflow_len);
1434     return put_openflow_xid(openflow_len, type, alloc_xid(), *bufferp);
1435 }
1436
1437 /* Similar to make_openflow() but creates a Nicira vendor extension message
1438  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1439 void *
1440 make_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf **bufferp)
1441 {
1442     return make_nxmsg_xid(openflow_len, subtype, alloc_xid(), bufferp);
1443 }
1444
1445 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
1446  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
1447  * transaction id 'xid'.  Allocated bytes beyond the header, if any, are
1448  * zeroed.
1449  *
1450  * The caller is responsible for freeing '*bufferp' when it is no longer
1451  * needed.
1452  *
1453  * The OpenFlow header length is initially set to 'openflow_len'; if the
1454  * message is later extended, the length should be updated with
1455  * update_openflow_length() before sending.
1456  *
1457  * Returns the header. */
1458 void *
1459 make_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
1460                   struct ofpbuf **bufferp)
1461 {
1462     *bufferp = ofpbuf_new(openflow_len);
1463     return put_openflow_xid(openflow_len, type, xid, *bufferp);
1464 }
1465
1466 /* Similar to make_openflow_xid() but creates a Nicira vendor extension message
1467  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1468 void *
1469 make_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
1470                struct ofpbuf **bufferp)
1471 {
1472     *bufferp = ofpbuf_new(openflow_len);
1473     return put_nxmsg_xid(openflow_len, subtype, xid, *bufferp);
1474 }
1475
1476 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
1477  * with the given 'type' and an arbitrary transaction id.  Allocated bytes
1478  * beyond the header, if any, are zeroed.
1479  *
1480  * The OpenFlow header length is initially set to 'openflow_len'; if the
1481  * message is later extended, the length should be updated with
1482  * update_openflow_length() before sending.
1483  *
1484  * Returns the header. */
1485 void *
1486 put_openflow(size_t openflow_len, uint8_t type, struct ofpbuf *buffer)
1487 {
1488     return put_openflow_xid(openflow_len, type, alloc_xid(), buffer);
1489 }
1490
1491 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
1492  * with the given 'type' and an transaction id 'xid'.  Allocated bytes beyond
1493  * the header, if any, are zeroed.
1494  *
1495  * The OpenFlow header length is initially set to 'openflow_len'; if the
1496  * message is later extended, the length should be updated with
1497  * update_openflow_length() before sending.
1498  *
1499  * Returns the header. */
1500 void *
1501 put_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
1502                  struct ofpbuf *buffer)
1503 {
1504     struct ofp_header *oh;
1505
1506     assert(openflow_len >= sizeof *oh);
1507     assert(openflow_len <= UINT16_MAX);
1508
1509     oh = ofpbuf_put_uninit(buffer, openflow_len);
1510     oh->version = OFP_VERSION;
1511     oh->type = type;
1512     oh->length = htons(openflow_len);
1513     oh->xid = xid;
1514     memset(oh + 1, 0, openflow_len - sizeof *oh);
1515     return oh;
1516 }
1517
1518 /* Similar to put_openflow() but append a Nicira vendor extension message with
1519  * the specific 'subtype'.  'subtype' should be in host byte order. */
1520 void *
1521 put_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf *buffer)
1522 {
1523     return put_nxmsg_xid(openflow_len, subtype, alloc_xid(), buffer);
1524 }
1525
1526 /* Similar to put_openflow_xid() but append a Nicira vendor extension message
1527  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1528 void *
1529 put_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
1530               struct ofpbuf *buffer)
1531 {
1532     struct nicira_header *nxh;
1533
1534     nxh = put_openflow_xid(openflow_len, OFPT_VENDOR, xid, buffer);
1535     nxh->vendor = htonl(NX_VENDOR_ID);
1536     nxh->subtype = htonl(subtype);
1537     return nxh;
1538 }
1539
1540 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
1541  * 'buffer->size'. */
1542 void
1543 update_openflow_length(struct ofpbuf *buffer)
1544 {
1545     struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
1546     oh->length = htons(buffer->size);
1547 }
1548
1549 /* Creates an ofp_stats_request with the given 'type' and 'body_len' bytes of
1550  * space allocated for the 'body' member.  Returns the first byte of the 'body'
1551  * member. */
1552 void *
1553 ofputil_make_stats_request(size_t body_len, uint16_t type,
1554                            struct ofpbuf **bufferp)
1555 {
1556     struct ofp_stats_request *osr;
1557     osr = make_openflow((offsetof(struct ofp_stats_request, body)
1558                         + body_len), OFPT_STATS_REQUEST, bufferp);
1559     osr->type = htons(type);
1560     osr->flags = htons(0);
1561     return osr->body;
1562 }
1563
1564 /* Creates a stats request message with Nicira as vendor and the given
1565  * 'subtype', of total length 'openflow_len'.  Returns the message. */
1566 void *
1567 ofputil_make_nxstats_request(size_t openflow_len, uint32_t subtype,
1568                              struct ofpbuf **bufferp)
1569 {
1570     struct nicira_stats_msg *nsm;
1571
1572     nsm = make_openflow(openflow_len, OFPT_STATS_REQUEST, bufferp);
1573     nsm->type = htons(OFPST_VENDOR);
1574     nsm->flags = htons(0);
1575     nsm->vendor = htonl(NX_VENDOR_ID);
1576     nsm->subtype = htonl(subtype);
1577     return nsm;
1578 }
1579
1580 /* Returns the first byte of the 'body' member of the ofp_stats_request or
1581  * ofp_stats_reply in 'oh'. */
1582 const void *
1583 ofputil_stats_body(const struct ofp_header *oh)
1584 {
1585     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1586     return ((const struct ofp_stats_request *) oh)->body;
1587 }
1588
1589 /* Returns the length of the 'body' member of the ofp_stats_request or
1590  * ofp_stats_reply in 'oh'. */
1591 size_t
1592 ofputil_stats_body_len(const struct ofp_header *oh)
1593 {
1594     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1595     return ntohs(oh->length) - sizeof(struct ofp_stats_request);
1596 }
1597
1598 /* Returns the first byte of the body of the nicira_stats_msg in 'oh'. */
1599 const void *
1600 ofputil_nxstats_body(const struct ofp_header *oh)
1601 {
1602     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1603     return ((const struct nicira_stats_msg *) oh) + 1;
1604 }
1605
1606 /* Returns the length of the body of the nicira_stats_msg in 'oh'. */
1607 size_t
1608 ofputil_nxstats_body_len(const struct ofp_header *oh)
1609 {
1610     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1611     return ntohs(oh->length) - sizeof(struct nicira_stats_msg);
1612 }
1613
1614 struct ofpbuf *
1615 make_flow_mod(uint16_t command, const struct cls_rule *rule,
1616               size_t actions_len)
1617 {
1618     struct ofp_flow_mod *ofm;
1619     size_t size = sizeof *ofm + actions_len;
1620     struct ofpbuf *out = ofpbuf_new(size);
1621     ofm = ofpbuf_put_zeros(out, sizeof *ofm);
1622     ofm->header.version = OFP_VERSION;
1623     ofm->header.type = OFPT_FLOW_MOD;
1624     ofm->header.length = htons(size);
1625     ofm->cookie = 0;
1626     ofm->priority = htons(MIN(rule->priority, UINT16_MAX));
1627     ofputil_cls_rule_to_match(rule, &ofm->match);
1628     ofm->command = htons(command);
1629     return out;
1630 }
1631
1632 struct ofpbuf *
1633 make_add_flow(const struct cls_rule *rule, uint32_t buffer_id,
1634               uint16_t idle_timeout, size_t actions_len)
1635 {
1636     struct ofpbuf *out = make_flow_mod(OFPFC_ADD, rule, actions_len);
1637     struct ofp_flow_mod *ofm = out->data;
1638     ofm->idle_timeout = htons(idle_timeout);
1639     ofm->hard_timeout = htons(OFP_FLOW_PERMANENT);
1640     ofm->buffer_id = htonl(buffer_id);
1641     return out;
1642 }
1643
1644 struct ofpbuf *
1645 make_del_flow(const struct cls_rule *rule)
1646 {
1647     struct ofpbuf *out = make_flow_mod(OFPFC_DELETE_STRICT, rule, 0);
1648     struct ofp_flow_mod *ofm = out->data;
1649     ofm->out_port = htons(OFPP_NONE);
1650     return out;
1651 }
1652
1653 struct ofpbuf *
1654 make_add_simple_flow(const struct cls_rule *rule,
1655                      uint32_t buffer_id, uint16_t out_port,
1656                      uint16_t idle_timeout)
1657 {
1658     if (out_port != OFPP_NONE) {
1659         struct ofp_action_output *oao;
1660         struct ofpbuf *buffer;
1661
1662         buffer = make_add_flow(rule, buffer_id, idle_timeout, sizeof *oao);
1663         oao = ofpbuf_put_zeros(buffer, sizeof *oao);
1664         oao->type = htons(OFPAT_OUTPUT);
1665         oao->len = htons(sizeof *oao);
1666         oao->port = htons(out_port);
1667         return buffer;
1668     } else {
1669         return make_add_flow(rule, buffer_id, idle_timeout, 0);
1670     }
1671 }
1672
1673 struct ofpbuf *
1674 make_packet_in(uint32_t buffer_id, uint16_t in_port, uint8_t reason,
1675                const struct ofpbuf *payload, int max_send_len)
1676 {
1677     struct ofp_packet_in *opi;
1678     struct ofpbuf *buf;
1679     int send_len;
1680
1681     send_len = MIN(max_send_len, payload->size);
1682     buf = ofpbuf_new(sizeof *opi + send_len);
1683     opi = put_openflow_xid(offsetof(struct ofp_packet_in, data),
1684                            OFPT_PACKET_IN, 0, buf);
1685     opi->buffer_id = htonl(buffer_id);
1686     opi->total_len = htons(payload->size);
1687     opi->in_port = htons(in_port);
1688     opi->reason = reason;
1689     ofpbuf_put(buf, payload->data, send_len);
1690     update_openflow_length(buf);
1691
1692     return buf;
1693 }
1694
1695 struct ofpbuf *
1696 make_packet_out(const struct ofpbuf *packet, uint32_t buffer_id,
1697                 uint16_t in_port,
1698                 const struct ofp_action_header *actions, size_t n_actions)
1699 {
1700     size_t actions_len = n_actions * sizeof *actions;
1701     struct ofp_packet_out *opo;
1702     size_t size = sizeof *opo + actions_len + (packet ? packet->size : 0);
1703     struct ofpbuf *out = ofpbuf_new(size);
1704
1705     opo = ofpbuf_put_uninit(out, sizeof *opo);
1706     opo->header.version = OFP_VERSION;
1707     opo->header.type = OFPT_PACKET_OUT;
1708     opo->header.length = htons(size);
1709     opo->header.xid = htonl(0);
1710     opo->buffer_id = htonl(buffer_id);
1711     opo->in_port = htons(in_port == ODPP_LOCAL ? OFPP_LOCAL : in_port);
1712     opo->actions_len = htons(actions_len);
1713     ofpbuf_put(out, actions, actions_len);
1714     if (packet) {
1715         ofpbuf_put(out, packet->data, packet->size);
1716     }
1717     return out;
1718 }
1719
1720 struct ofpbuf *
1721 make_unbuffered_packet_out(const struct ofpbuf *packet,
1722                            uint16_t in_port, uint16_t out_port)
1723 {
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(packet, UINT32_MAX, in_port,
1729                            (struct ofp_action_header *) &action, 1);
1730 }
1731
1732 struct ofpbuf *
1733 make_buffered_packet_out(uint32_t buffer_id,
1734                          uint16_t in_port, uint16_t out_port)
1735 {
1736     if (out_port != OFPP_NONE) {
1737         struct ofp_action_output action;
1738         action.type = htons(OFPAT_OUTPUT);
1739         action.len = htons(sizeof action);
1740         action.port = htons(out_port);
1741         return make_packet_out(NULL, buffer_id, in_port,
1742                                (struct ofp_action_header *) &action, 1);
1743     } else {
1744         return make_packet_out(NULL, buffer_id, in_port, NULL, 0);
1745     }
1746 }
1747
1748 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
1749 struct ofpbuf *
1750 make_echo_request(void)
1751 {
1752     struct ofp_header *rq;
1753     struct ofpbuf *out = ofpbuf_new(sizeof *rq);
1754     rq = ofpbuf_put_uninit(out, sizeof *rq);
1755     rq->version = OFP_VERSION;
1756     rq->type = OFPT_ECHO_REQUEST;
1757     rq->length = htons(sizeof *rq);
1758     rq->xid = htonl(0);
1759     return out;
1760 }
1761
1762 /* Creates and returns an OFPT_ECHO_REPLY message matching the
1763  * OFPT_ECHO_REQUEST message in 'rq'. */
1764 struct ofpbuf *
1765 make_echo_reply(const struct ofp_header *rq)
1766 {
1767     size_t size = ntohs(rq->length);
1768     struct ofpbuf *out = ofpbuf_new(size);
1769     struct ofp_header *reply = ofpbuf_put(out, rq, size);
1770     reply->type = OFPT_ECHO_REPLY;
1771     return out;
1772 }
1773
1774 static int
1775 check_action_exact_len(const union ofp_action *a, unsigned int len,
1776                        unsigned int required_len)
1777 {
1778     if (len != required_len) {
1779         VLOG_WARN_RL(&bad_ofmsg_rl, "action %"PRIu16" has invalid length "
1780                      "%"PRIu16" (must be %u)\n",
1781                      ntohs(a->type), ntohs(a->header.len), required_len);
1782         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1783     }
1784     return 0;
1785 }
1786
1787 static int
1788 check_nx_action_exact_len(const struct nx_action_header *a,
1789                           unsigned int len, unsigned int required_len)
1790 {
1791     if (len != required_len) {
1792         VLOG_WARN_RL(&bad_ofmsg_rl,
1793                      "Nicira action %"PRIu16" has invalid length %"PRIu16" "
1794                      "(must be %u)\n",
1795                      ntohs(a->subtype), ntohs(a->len), required_len);
1796         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1797     }
1798     return 0;
1799 }
1800
1801 /* Checks that 'port' is a valid output port for the OFPAT_OUTPUT action, given
1802  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
1803  * 'port' is valid, otherwise an ofp_mkerr() return code. */
1804 static int
1805 check_output_port(uint16_t port, int max_ports)
1806 {
1807     switch (port) {
1808     case OFPP_IN_PORT:
1809     case OFPP_TABLE:
1810     case OFPP_NORMAL:
1811     case OFPP_FLOOD:
1812     case OFPP_ALL:
1813     case OFPP_CONTROLLER:
1814     case OFPP_LOCAL:
1815         return 0;
1816
1817     default:
1818         if (port < max_ports) {
1819             return 0;
1820         }
1821         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown output port %x", port);
1822         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
1823     }
1824 }
1825
1826 /* Checks that 'action' is a valid OFPAT_ENQUEUE action, given that the switch
1827  * will never have more than 'max_ports' ports.  Returns 0 if 'port' is valid,
1828  * otherwise an ofp_mkerr() return code. */
1829 static int
1830 check_enqueue_action(const union ofp_action *a, unsigned int len,
1831                      int max_ports)
1832 {
1833     const struct ofp_action_enqueue *oae;
1834     uint16_t port;
1835     int error;
1836
1837     error = check_action_exact_len(a, len, 16);
1838     if (error) {
1839         return error;
1840     }
1841
1842     oae = (const struct ofp_action_enqueue *) a;
1843     port = ntohs(oae->port);
1844     if (port < max_ports || port == OFPP_IN_PORT) {
1845         return 0;
1846     }
1847     VLOG_WARN_RL(&bad_ofmsg_rl, "unknown enqueue port %x", port);
1848     return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
1849 }
1850
1851 static int
1852 check_nicira_action(const union ofp_action *a, unsigned int len,
1853                     const struct flow *flow)
1854 {
1855     const struct nx_action_header *nah;
1856     int subtype;
1857     int error;
1858
1859     if (len < 16) {
1860         VLOG_WARN_RL(&bad_ofmsg_rl,
1861                      "Nicira vendor action only %u bytes", len);
1862         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1863     }
1864     nah = (const struct nx_action_header *) a;
1865
1866     subtype = ntohs(nah->subtype);
1867     if (subtype > TYPE_MAXIMUM(enum nx_action_subtype)) {
1868         /* This is necessary because enum nx_action_subtype may be an
1869          * 8-bit type, so the cast below throws away the top 8 bits. */
1870         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR_TYPE);
1871     }
1872
1873     switch ((enum nx_action_subtype) subtype) {
1874     case NXAST_RESUBMIT:
1875     case NXAST_SET_TUNNEL:
1876     case NXAST_DROP_SPOOFED_ARP:
1877     case NXAST_SET_QUEUE:
1878     case NXAST_POP_QUEUE:
1879         return check_nx_action_exact_len(nah, len, 16);
1880
1881     case NXAST_REG_MOVE:
1882         error = check_nx_action_exact_len(nah, len,
1883                                           sizeof(struct nx_action_reg_move));
1884         if (error) {
1885             return error;
1886         }
1887         return nxm_check_reg_move((const struct nx_action_reg_move *) a, flow);
1888
1889     case NXAST_REG_LOAD:
1890         error = check_nx_action_exact_len(nah, len,
1891                                           sizeof(struct nx_action_reg_load));
1892         if (error) {
1893             return error;
1894         }
1895         return nxm_check_reg_load((const struct nx_action_reg_load *) a, flow);
1896
1897     case NXAST_NOTE:
1898         return 0;
1899
1900     case NXAST_SET_TUNNEL64:
1901         return check_nx_action_exact_len(
1902             nah, len, sizeof(struct nx_action_set_tunnel64));
1903
1904     case NXAST_MULTIPATH:
1905         error = check_nx_action_exact_len(
1906             nah, len, sizeof(struct nx_action_multipath));
1907         if (error) {
1908             return error;
1909         }
1910         return multipath_check((const struct nx_action_multipath *) a);
1911
1912     case NXAST_AUTOPATH:
1913         error = check_nx_action_exact_len(
1914             nah, len, sizeof(struct nx_action_autopath));
1915         if (error) {
1916             return error;
1917         }
1918         return autopath_check((const struct nx_action_autopath *) a);
1919
1920     case NXAST_SNAT__OBSOLETE:
1921     default:
1922         VLOG_WARN_RL(&bad_ofmsg_rl,
1923                      "unknown Nicira vendor action subtype %d", subtype);
1924         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR_TYPE);
1925     }
1926 }
1927
1928 static int
1929 check_action(const union ofp_action *a, unsigned int len,
1930              const struct flow *flow, int max_ports)
1931 {
1932     enum ofp_action_type type = ntohs(a->type);
1933     int error;
1934
1935     switch (type) {
1936     case OFPAT_OUTPUT:
1937         error = check_action_exact_len(a, len, 8);
1938         if (error) {
1939             return error;
1940         }
1941         return check_output_port(ntohs(a->output.port), max_ports);
1942
1943     case OFPAT_SET_VLAN_VID:
1944         error = check_action_exact_len(a, len, 8);
1945         if (error) {
1946             return error;
1947         }
1948         if (a->vlan_vid.vlan_vid & ~htons(0xfff)) {
1949             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
1950         }
1951         return 0;
1952
1953     case OFPAT_SET_VLAN_PCP:
1954         error = check_action_exact_len(a, len, 8);
1955         if (error) {
1956             return error;
1957         }
1958         if (a->vlan_pcp.vlan_pcp & ~7) {
1959             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
1960         }
1961         return 0;
1962
1963     case OFPAT_STRIP_VLAN:
1964     case OFPAT_SET_NW_SRC:
1965     case OFPAT_SET_NW_DST:
1966     case OFPAT_SET_NW_TOS:
1967     case OFPAT_SET_TP_SRC:
1968     case OFPAT_SET_TP_DST:
1969         return check_action_exact_len(a, len, 8);
1970
1971     case OFPAT_SET_DL_SRC:
1972     case OFPAT_SET_DL_DST:
1973         return check_action_exact_len(a, len, 16);
1974
1975     case OFPAT_VENDOR:
1976         return (a->vendor.vendor == htonl(NX_VENDOR_ID)
1977                 ? check_nicira_action(a, len, flow)
1978                 : ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR));
1979
1980     case OFPAT_ENQUEUE:
1981         return check_enqueue_action(a, len, max_ports);
1982
1983     default:
1984         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown action type %d", (int) type);
1985         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_TYPE);
1986     }
1987 }
1988
1989 int
1990 validate_actions(const union ofp_action *actions, size_t n_actions,
1991                  const struct flow *flow, int max_ports)
1992 {
1993     size_t i;
1994
1995     for (i = 0; i < n_actions; ) {
1996         const union ofp_action *a = &actions[i];
1997         unsigned int len = ntohs(a->header.len);
1998         unsigned int n_slots = len / OFP_ACTION_ALIGN;
1999         unsigned int slots_left = &actions[n_actions] - a;
2000         int error;
2001
2002         if (n_slots > slots_left) {
2003             VLOG_WARN_RL(&bad_ofmsg_rl,
2004                          "action requires %u slots but only %u remain",
2005                          n_slots, slots_left);
2006             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
2007         } else if (!len) {
2008             VLOG_WARN_RL(&bad_ofmsg_rl, "action has invalid length 0");
2009             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
2010         } else if (len % OFP_ACTION_ALIGN) {
2011             VLOG_WARN_RL(&bad_ofmsg_rl, "action length %u is not a multiple "
2012                          "of %d", len, OFP_ACTION_ALIGN);
2013             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
2014         }
2015
2016         error = check_action(a, len, flow, max_ports);
2017         if (error) {
2018             return error;
2019         }
2020         i += n_slots;
2021     }
2022     return 0;
2023 }
2024
2025 /* Returns true if 'action' outputs to 'port', false otherwise. */
2026 bool
2027 action_outputs_to_port(const union ofp_action *action, ovs_be16 port)
2028 {
2029     switch (ntohs(action->type)) {
2030     case OFPAT_OUTPUT:
2031         return action->output.port == port;
2032     case OFPAT_ENQUEUE:
2033         return ((const struct ofp_action_enqueue *) action)->port == port;
2034     default:
2035         return false;
2036     }
2037 }
2038
2039 /* The set of actions must either come from a trusted source or have been
2040  * previously validated with validate_actions(). */
2041 const union ofp_action *
2042 actions_first(struct actions_iterator *iter,
2043               const union ofp_action *oa, size_t n_actions)
2044 {
2045     iter->pos = oa;
2046     iter->end = oa + n_actions;
2047     return actions_next(iter);
2048 }
2049
2050 const union ofp_action *
2051 actions_next(struct actions_iterator *iter)
2052 {
2053     if (iter->pos != iter->end) {
2054         const union ofp_action *a = iter->pos;
2055         unsigned int len = ntohs(a->header.len);
2056         iter->pos += len / OFP_ACTION_ALIGN;
2057         return a;
2058     } else {
2059         return NULL;
2060     }
2061 }
2062
2063 /* "Normalizes" the wildcards in 'rule'.  That means:
2064  *
2065  *    1. If the type of level N is known, then only the valid fields for that
2066  *       level may be specified.  For example, ARP does not have a TOS field,
2067  *       so nw_tos must be wildcarded if 'rule' specifies an ARP flow.
2068  *       Similarly, IPv4 does not have any IPv6 addresses, so ipv6_src and
2069  *       ipv6_dst (and other fields) must be wildcarded if 'rule' specifies an
2070  *       IPv4 flow.
2071  *
2072  *    2. If the type of level N is not known (or not understood by Open
2073  *       vSwitch), then no fields at all for that level may be specified.  For
2074  *       example, Open vSwitch does not understand SCTP, an L4 protocol, so the
2075  *       L4 fields tp_src and tp_dst must be wildcarded if 'rule' specifies an
2076  *       SCTP flow.
2077  *
2078  * 'flow_format' specifies the format of the flow as received or as intended to
2079  * be sent.  This is important for IPv6 and ARP, for which NXM supports more
2080  * detailed matching. */
2081 void
2082 ofputil_normalize_rule(struct cls_rule *rule, enum nx_flow_format flow_format)
2083 {
2084     enum {
2085         MAY_NW_ADDR     = 1 << 0, /* nw_src, nw_dst */
2086         MAY_TP_ADDR     = 1 << 1, /* tp_src, tp_dst */
2087         MAY_NW_PROTO    = 1 << 2, /* nw_proto */
2088         MAY_NW_TOS      = 1 << 3, /* nw_tos */
2089         MAY_ARP_SHA     = 1 << 4, /* arp_sha */
2090         MAY_ARP_THA     = 1 << 5, /* arp_tha */
2091         MAY_IPV6_ADDR   = 1 << 6, /* ipv6_src, ipv6_dst */
2092         MAY_ND_TARGET   = 1 << 7  /* nd_target */
2093     } may_match;
2094
2095     struct flow_wildcards wc;
2096
2097     /* Figure out what fields may be matched. */
2098     if (rule->flow.dl_type == htons(ETH_TYPE_IP)) {
2099         may_match = MAY_NW_PROTO | MAY_NW_TOS | MAY_NW_ADDR;
2100         if (rule->flow.nw_proto == IPPROTO_TCP ||
2101             rule->flow.nw_proto == IPPROTO_UDP ||
2102             rule->flow.nw_proto == IPPROTO_ICMP) {
2103             may_match |= MAY_TP_ADDR;
2104         }
2105     } else if (rule->flow.dl_type == htons(ETH_TYPE_IPV6)
2106                && flow_format == NXFF_NXM) {
2107         may_match = MAY_NW_PROTO | MAY_NW_TOS | MAY_IPV6_ADDR;
2108         if (rule->flow.nw_proto == IPPROTO_TCP ||
2109             rule->flow.nw_proto == IPPROTO_UDP) {
2110             may_match |= MAY_TP_ADDR;
2111         } else if (rule->flow.nw_proto == IPPROTO_ICMPV6) {
2112             may_match |= MAY_TP_ADDR;
2113             if (rule->flow.tp_src == htons(ND_NEIGHBOR_SOLICIT)) {
2114                 may_match |= MAY_ND_TARGET | MAY_ARP_SHA;
2115             } else if (rule->flow.tp_src == htons(ND_NEIGHBOR_ADVERT)) {
2116                 may_match |= MAY_ND_TARGET | MAY_ARP_THA;
2117             }
2118         }
2119     } else if (rule->flow.dl_type == htons(ETH_TYPE_ARP)) {
2120         may_match = MAY_NW_PROTO | MAY_NW_ADDR;
2121         if (flow_format == NXFF_NXM) {
2122             may_match |= MAY_ARP_SHA | MAY_ARP_THA;
2123         }
2124     } else {
2125         may_match = 0;
2126     }
2127
2128     /* Clear the fields that may not be matched. */
2129     wc = rule->wc;
2130     if (!(may_match & MAY_NW_ADDR)) {
2131         wc.nw_src_mask = wc.nw_dst_mask = htonl(0);
2132     }
2133     if (!(may_match & MAY_TP_ADDR)) {
2134         wc.wildcards |= FWW_TP_SRC | FWW_TP_DST;
2135     }
2136     if (!(may_match & MAY_NW_PROTO)) {
2137         wc.wildcards |= FWW_NW_PROTO;
2138     }
2139     if (!(may_match & MAY_NW_TOS)) {
2140         wc.wildcards |= FWW_NW_TOS;
2141     }
2142     if (!(may_match & MAY_ARP_SHA)) {
2143         wc.wildcards |= FWW_ARP_SHA;
2144     }
2145     if (!(may_match & MAY_ARP_THA)) {
2146         wc.wildcards |= FWW_ARP_THA;
2147     }
2148     if (!(may_match & MAY_IPV6_ADDR)) {
2149         wc.ipv6_src_mask = wc.ipv6_dst_mask = in6addr_any;
2150     }
2151     if (!(may_match & MAY_ND_TARGET)) {
2152         wc.wildcards |= FWW_ND_TARGET;
2153     }
2154
2155     /* Log any changes. */
2156     if (!flow_wildcards_equal(&wc, &rule->wc)) {
2157         bool log = !VLOG_DROP_INFO(&bad_ofmsg_rl);
2158         char *pre = log ? cls_rule_to_string(rule) : NULL;
2159
2160         rule->wc = wc;
2161         cls_rule_zero_wildcarded_fields(rule);
2162
2163         if (log) {
2164             char *post = cls_rule_to_string(rule);
2165             VLOG_INFO("normalization changed ofp_match, details:");
2166             VLOG_INFO(" pre: %s", pre);
2167             VLOG_INFO("post: %s", post);
2168             free(pre);
2169             free(post);
2170         }
2171     }
2172 }
2173
2174 static uint32_t
2175 vendor_code_to_id(uint8_t code)
2176 {
2177     switch (code) {
2178 #define OFPUTIL_VENDOR(NAME, VENDOR_ID) case NAME: return VENDOR_ID;
2179         OFPUTIL_VENDORS
2180 #undef OFPUTIL_VENDOR
2181     default:
2182         return UINT32_MAX;
2183     }
2184 }
2185
2186 static int
2187 vendor_id_to_code(uint32_t id)
2188 {
2189     switch (id) {
2190 #define OFPUTIL_VENDOR(NAME, VENDOR_ID) case VENDOR_ID: return NAME;
2191         OFPUTIL_VENDORS
2192 #undef OFPUTIL_VENDOR
2193     default:
2194         return -1;
2195     }
2196 }
2197
2198 /* Creates and returns an OpenFlow message of type OFPT_ERROR with the error
2199  * information taken from 'error', whose encoding must be as described in the
2200  * large comment in ofp-util.h.  If 'oh' is nonnull, then the error will use
2201  * oh->xid as its transaction ID, and it will include up to the first 64 bytes
2202  * of 'oh'.
2203  *
2204  * Returns NULL if 'error' is not an OpenFlow error code. */
2205 struct ofpbuf *
2206 ofputil_encode_error_msg(int error, const struct ofp_header *oh)
2207 {
2208     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2209
2210     struct ofpbuf *buf;
2211     const void *data;
2212     size_t len;
2213     uint8_t vendor;
2214     uint16_t type;
2215     uint16_t code;
2216     ovs_be32 xid;
2217
2218     if (!is_ofp_error(error)) {
2219         /* We format 'error' with strerror() here since it seems likely to be
2220          * a system errno value. */
2221         VLOG_WARN_RL(&rl, "invalid OpenFlow error code %d (%s)",
2222                      error, strerror(error));
2223         return NULL;
2224     }
2225
2226     if (oh) {
2227         xid = oh->xid;
2228         data = oh;
2229         len = ntohs(oh->length);
2230         if (len > 64) {
2231             len = 64;
2232         }
2233     } else {
2234         xid = 0;
2235         data = NULL;
2236         len = 0;
2237     }
2238
2239     vendor = get_ofp_err_vendor(error);
2240     type = get_ofp_err_type(error);
2241     code = get_ofp_err_code(error);
2242     if (vendor == OFPUTIL_VENDOR_OPENFLOW) {
2243         struct ofp_error_msg *oem;
2244
2245         oem = make_openflow_xid(len + sizeof *oem, OFPT_ERROR, xid, &buf);
2246         oem->type = htons(type);
2247         oem->code = htons(code);
2248     } else {
2249         struct ofp_error_msg *oem;
2250         struct nx_vendor_error *nve;
2251         uint32_t vendor_id;
2252
2253         vendor_id = vendor_code_to_id(vendor);
2254         if (vendor_id == UINT32_MAX) {
2255             VLOG_WARN_RL(&rl, "error %x contains invalid vendor code %d",
2256                          error, vendor);
2257             return NULL;
2258         }
2259
2260         oem = make_openflow_xid(len + sizeof *oem + sizeof *nve,
2261                                 OFPT_ERROR, xid, &buf);
2262         oem->type = htons(NXET_VENDOR);
2263         oem->code = htons(NXVC_VENDOR_ERROR);
2264
2265         nve = (struct nx_vendor_error *)oem->data;
2266         nve->vendor = htonl(vendor_id);
2267         nve->type = htons(type);
2268         nve->code = htons(code);
2269     }
2270
2271     if (len) {
2272         buf->size -= len;
2273         ofpbuf_put(buf, data, len);
2274     }
2275
2276     return buf;
2277 }
2278
2279 /* Decodes 'oh', which should be an OpenFlow OFPT_ERROR message, and returns an
2280  * Open vSwitch internal error code in the format described in the large
2281  * comment in ofp-util.h.
2282  *
2283  * If 'payload_ofs' is nonnull, on success '*payload_ofs' is set to the offset
2284  * to the payload starting from 'oh' and on failure it is set to 0. */
2285 int
2286 ofputil_decode_error_msg(const struct ofp_header *oh, size_t *payload_ofs)
2287 {
2288     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2289
2290     const struct ofp_error_msg *oem;
2291     uint16_t type, code;
2292     struct ofpbuf b;
2293     int vendor;
2294
2295     if (payload_ofs) {
2296         *payload_ofs = 0;
2297     }
2298     if (oh->type != OFPT_ERROR) {
2299         return EPROTO;
2300     }
2301
2302     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2303     oem = ofpbuf_try_pull(&b, sizeof *oem);
2304     if (!oem) {
2305         return EPROTO;
2306     }
2307
2308     type = ntohs(oem->type);
2309     code = ntohs(oem->code);
2310     if (type == NXET_VENDOR && code == NXVC_VENDOR_ERROR) {
2311         const struct nx_vendor_error *nve = ofpbuf_try_pull(&b, sizeof *nve);
2312         if (!nve) {
2313             return EPROTO;
2314         }
2315
2316         vendor = vendor_id_to_code(ntohl(nve->vendor));
2317         if (vendor < 0) {
2318             VLOG_WARN_RL(&rl, "error contains unknown vendor ID %#"PRIx32,
2319                          ntohl(nve->vendor));
2320             return EPROTO;
2321         }
2322         type = ntohs(nve->type);
2323         code = ntohs(nve->code);
2324     } else {
2325         vendor = OFPUTIL_VENDOR_OPENFLOW;
2326     }
2327
2328     if (type >= 1024) {
2329         VLOG_WARN_RL(&rl, "error contains type %"PRIu16" greater than "
2330                      "supported maximum value 1023", type);
2331         return EPROTO;
2332     }
2333
2334     if (payload_ofs) {
2335         *payload_ofs = (uint8_t *) b.data - (uint8_t *) oh;
2336     }
2337     return ofp_mkerr_vendor(vendor, type, code);
2338 }
2339
2340 void
2341 ofputil_format_error(struct ds *s, int error)
2342 {
2343     if (is_errno(error)) {
2344         ds_put_cstr(s, strerror(error));
2345     } else {
2346         uint16_t type = get_ofp_err_type(error);
2347         uint16_t code = get_ofp_err_code(error);
2348         const char *type_s = ofp_error_type_to_string(type);
2349         const char *code_s = ofp_error_code_to_string(type, code);
2350
2351         ds_put_format(s, "type ");
2352         if (type_s) {
2353             ds_put_cstr(s, type_s);
2354         } else {
2355             ds_put_format(s, "%"PRIu16, type);
2356         }
2357
2358         ds_put_cstr(s, ", code ");
2359         if (code_s) {
2360             ds_put_cstr(s, code_s);
2361         } else {
2362             ds_put_format(s, "%"PRIu16, code);
2363         }
2364     }
2365 }
2366
2367 char *
2368 ofputil_error_to_string(int error)
2369 {
2370     struct ds s = DS_EMPTY_INITIALIZER;
2371     ofputil_format_error(&s, error);
2372     return ds_steal_cstr(&s);
2373 }
2374
2375 /* Attempts to pull 'actions_len' bytes from the front of 'b'.  Returns 0 if
2376  * successful, otherwise an OpenFlow error.
2377  *
2378  * If successful, the first action is stored in '*actionsp' and the number of
2379  * "union ofp_action" size elements into '*n_actionsp'.  Otherwise NULL and 0
2380  * are stored, respectively.
2381  *
2382  * This function does not check that the actions are valid (the caller should
2383  * do so, with validate_actions()).  The caller is also responsible for making
2384  * sure that 'b->data' is initially aligned appropriately for "union
2385  * ofp_action". */
2386 int
2387 ofputil_pull_actions(struct ofpbuf *b, unsigned int actions_len,
2388                      union ofp_action **actionsp, size_t *n_actionsp)
2389 {
2390     if (actions_len % OFP_ACTION_ALIGN != 0) {
2391         VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
2392                      "is not a multiple of %d", actions_len, OFP_ACTION_ALIGN);
2393         goto error;
2394     }
2395
2396     *actionsp = ofpbuf_try_pull(b, actions_len);
2397     if (*actionsp == NULL) {
2398         VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
2399                      "exceeds remaining message length (%zu)",
2400                      actions_len, b->size);
2401         goto error;
2402     }
2403
2404     *n_actionsp = actions_len / OFP_ACTION_ALIGN;
2405     return 0;
2406
2407 error:
2408     *actionsp = NULL;
2409     *n_actionsp = 0;
2410     return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
2411 }