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