ofp-util: Avoid misaligned memory access in ofputil_encode_packet_in().
[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     memset(&opi, 0, sizeof opi);
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     ofpbuf_push(rw_packet, &opi, offsetof(struct ofp_packet_in, data));
1481     update_openflow_length(rw_packet);
1482
1483     return rw_packet;
1484 }
1485
1486 /* Returns a string representing the message type of 'type'.  The string is the
1487  * enumeration constant for the type, e.g. "OFPT_HELLO".  For statistics
1488  * messages, the constant is followed by "request" or "reply",
1489  * e.g. "OFPST_AGGREGATE reply". */
1490 const char *
1491 ofputil_msg_type_name(const struct ofputil_msg_type *type)
1492 {
1493     return type->name;
1494 }
1495 \f
1496 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
1497  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
1498  * an arbitrary transaction id.  Allocated bytes beyond the header, if any, are
1499  * zeroed.
1500  *
1501  * The caller is responsible for freeing '*bufferp' when it is no longer
1502  * needed.
1503  *
1504  * The OpenFlow header length is initially set to 'openflow_len'; if the
1505  * message is later extended, the length should be updated with
1506  * update_openflow_length() before sending.
1507  *
1508  * Returns the header. */
1509 void *
1510 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp)
1511 {
1512     *bufferp = ofpbuf_new(openflow_len);
1513     return put_openflow_xid(openflow_len, type, alloc_xid(), *bufferp);
1514 }
1515
1516 /* Similar to make_openflow() but creates a Nicira vendor extension message
1517  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1518 void *
1519 make_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf **bufferp)
1520 {
1521     return make_nxmsg_xid(openflow_len, subtype, alloc_xid(), bufferp);
1522 }
1523
1524 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
1525  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
1526  * transaction id 'xid'.  Allocated bytes beyond the header, if any, are
1527  * zeroed.
1528  *
1529  * The caller is responsible for freeing '*bufferp' when it is no longer
1530  * needed.
1531  *
1532  * The OpenFlow header length is initially set to 'openflow_len'; if the
1533  * message is later extended, the length should be updated with
1534  * update_openflow_length() before sending.
1535  *
1536  * Returns the header. */
1537 void *
1538 make_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
1539                   struct ofpbuf **bufferp)
1540 {
1541     *bufferp = ofpbuf_new(openflow_len);
1542     return put_openflow_xid(openflow_len, type, xid, *bufferp);
1543 }
1544
1545 /* Similar to make_openflow_xid() but creates a Nicira vendor extension message
1546  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1547 void *
1548 make_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
1549                struct ofpbuf **bufferp)
1550 {
1551     *bufferp = ofpbuf_new(openflow_len);
1552     return put_nxmsg_xid(openflow_len, subtype, xid, *bufferp);
1553 }
1554
1555 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
1556  * with the given 'type' and an arbitrary transaction id.  Allocated bytes
1557  * beyond the header, if any, are zeroed.
1558  *
1559  * The OpenFlow header length is initially set to 'openflow_len'; if the
1560  * message is later extended, the length should be updated with
1561  * update_openflow_length() before sending.
1562  *
1563  * Returns the header. */
1564 void *
1565 put_openflow(size_t openflow_len, uint8_t type, struct ofpbuf *buffer)
1566 {
1567     return put_openflow_xid(openflow_len, type, alloc_xid(), buffer);
1568 }
1569
1570 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
1571  * with the given 'type' and an transaction id 'xid'.  Allocated bytes beyond
1572  * the header, if any, are zeroed.
1573  *
1574  * The OpenFlow header length is initially set to 'openflow_len'; if the
1575  * message is later extended, the length should be updated with
1576  * update_openflow_length() before sending.
1577  *
1578  * Returns the header. */
1579 void *
1580 put_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
1581                  struct ofpbuf *buffer)
1582 {
1583     struct ofp_header *oh;
1584
1585     assert(openflow_len >= sizeof *oh);
1586     assert(openflow_len <= UINT16_MAX);
1587
1588     oh = ofpbuf_put_uninit(buffer, openflow_len);
1589     oh->version = OFP_VERSION;
1590     oh->type = type;
1591     oh->length = htons(openflow_len);
1592     oh->xid = xid;
1593     memset(oh + 1, 0, openflow_len - sizeof *oh);
1594     return oh;
1595 }
1596
1597 /* Similar to put_openflow() but append a Nicira vendor extension message with
1598  * the specific 'subtype'.  'subtype' should be in host byte order. */
1599 void *
1600 put_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf *buffer)
1601 {
1602     return put_nxmsg_xid(openflow_len, subtype, alloc_xid(), buffer);
1603 }
1604
1605 /* Similar to put_openflow_xid() but append a Nicira vendor extension message
1606  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1607 void *
1608 put_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
1609               struct ofpbuf *buffer)
1610 {
1611     struct nicira_header *nxh;
1612
1613     nxh = put_openflow_xid(openflow_len, OFPT_VENDOR, xid, buffer);
1614     nxh->vendor = htonl(NX_VENDOR_ID);
1615     nxh->subtype = htonl(subtype);
1616     return nxh;
1617 }
1618
1619 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
1620  * 'buffer->size'. */
1621 void
1622 update_openflow_length(struct ofpbuf *buffer)
1623 {
1624     struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
1625     oh->length = htons(buffer->size);
1626 }
1627
1628 static void
1629 put_stats__(ovs_be32 xid, uint8_t ofp_type,
1630             ovs_be16 ofpst_type, ovs_be32 nxst_subtype,
1631             struct ofpbuf *msg)
1632 {
1633     if (ofpst_type == htons(OFPST_VENDOR)) {
1634         struct nicira_stats_msg *nsm;
1635
1636         nsm = put_openflow_xid(sizeof *nsm, ofp_type, xid, msg);
1637         nsm->vsm.osm.type = ofpst_type;
1638         nsm->vsm.vendor = htonl(NX_VENDOR_ID);
1639         nsm->subtype = nxst_subtype;
1640     } else {
1641         struct ofp_stats_msg *osm;
1642
1643         osm = put_openflow_xid(sizeof *osm, ofp_type, xid, msg);
1644         osm->type = ofpst_type;
1645     }
1646 }
1647
1648 /* Creates a statistics request message with total length 'openflow_len'
1649  * (including all headers) and the given 'ofpst_type', and stores the buffer
1650  * containing the new message in '*bufferp'.  If 'ofpst_type' is OFPST_VENDOR
1651  * then 'nxst_subtype' is used as the Nicira vendor extension statistics
1652  * subtype (otherwise 'nxst_subtype' is ignored).
1653  *
1654  * Initializes bytes following the headers to all-bits-zero.
1655  *
1656  * Returns the first byte of the new message. */
1657 void *
1658 ofputil_make_stats_request(size_t openflow_len, uint16_t ofpst_type,
1659                            uint32_t nxst_subtype, struct ofpbuf **bufferp)
1660 {
1661     struct ofpbuf *msg;
1662
1663     msg = *bufferp = ofpbuf_new(openflow_len);
1664     put_stats__(alloc_xid(), OFPT_STATS_REQUEST,
1665                 htons(ofpst_type), htonl(nxst_subtype), msg);
1666     ofpbuf_padto(msg, openflow_len);
1667
1668     return msg->data;
1669 }
1670
1671 static void
1672 put_stats_reply__(const struct ofp_stats_msg *request, struct ofpbuf *msg)
1673 {
1674     assert(request->header.type == OFPT_STATS_REQUEST ||
1675            request->header.type == OFPT_STATS_REPLY);
1676     put_stats__(request->header.xid, OFPT_STATS_REPLY, request->type,
1677                 (request->type != htons(OFPST_VENDOR)
1678                  ? htonl(0)
1679                  : ((const struct nicira_stats_msg *) request)->subtype),
1680                 msg);
1681 }
1682
1683 /* Creates a statistics reply message with total length 'openflow_len'
1684  * (including all headers) and the same type (either a standard OpenFlow
1685  * statistics type or a Nicira extension type and subtype) as 'request', and
1686  * stores the buffer containing the new message in '*bufferp'.
1687  *
1688  * Initializes bytes following the headers to all-bits-zero.
1689  *
1690  * Returns the first byte of the new message. */
1691 void *
1692 ofputil_make_stats_reply(size_t openflow_len,
1693                          const struct ofp_stats_msg *request,
1694                          struct ofpbuf **bufferp)
1695 {
1696     struct ofpbuf *msg;
1697
1698     msg = *bufferp = ofpbuf_new(openflow_len);
1699     put_stats_reply__(request, msg);
1700     ofpbuf_padto(msg, openflow_len);
1701
1702     return msg->data;
1703 }
1704
1705 /* Initializes 'replies' as a list of ofpbufs that will contain a series of
1706  * replies to 'request', which should be an OpenFlow or Nicira extension
1707  * statistics request.  Initially 'replies' will have a single reply message
1708  * that has only a header.  The functions ofputil_reserve_stats_reply() and
1709  * ofputil_append_stats_reply() may be used to add to the reply. */
1710 void
1711 ofputil_start_stats_reply(const struct ofp_stats_msg *request,
1712                           struct list *replies)
1713 {
1714     struct ofpbuf *msg;
1715
1716     msg = ofpbuf_new(1024);
1717     put_stats_reply__(request, msg);
1718
1719     list_init(replies);
1720     list_push_back(replies, &msg->list_node);
1721 }
1722
1723 /* Prepares to append up to 'len' bytes to the series of statistics replies in
1724  * 'replies', which should have been initialized with
1725  * ofputil_start_stats_reply().  Returns an ofpbuf with at least 'len' bytes of
1726  * tailroom.  (The 'len' bytes have not actually be allocated; the caller must
1727  * do so with e.g. ofpbuf_put_uninit().) */
1728 struct ofpbuf *
1729 ofputil_reserve_stats_reply(size_t len, struct list *replies)
1730 {
1731     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
1732     struct ofp_stats_msg *osm = msg->data;
1733
1734     if (msg->size + len <= UINT16_MAX) {
1735         ofpbuf_prealloc_tailroom(msg, len);
1736     } else {
1737         osm->flags |= htons(OFPSF_REPLY_MORE);
1738
1739         msg = ofpbuf_new(MAX(1024, sizeof(struct nicira_stats_msg) + len));
1740         put_stats_reply__(osm, msg);
1741         list_push_back(replies, &msg->list_node);
1742     }
1743     return msg;
1744 }
1745
1746 /* Appends 'len' bytes to the series of statistics replies in 'replies', and
1747  * returns the first byte. */
1748 void *
1749 ofputil_append_stats_reply(size_t len, struct list *replies)
1750 {
1751     return ofpbuf_put_uninit(ofputil_reserve_stats_reply(len, replies), len);
1752 }
1753
1754 /* Returns the first byte past the ofp_stats_msg header in 'oh'. */
1755 const void *
1756 ofputil_stats_body(const struct ofp_header *oh)
1757 {
1758     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1759     return (const struct ofp_stats_msg *) oh + 1;
1760 }
1761
1762 /* Returns the number of bytes past the ofp_stats_msg header in 'oh'. */
1763 size_t
1764 ofputil_stats_body_len(const struct ofp_header *oh)
1765 {
1766     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1767     return ntohs(oh->length) - sizeof(struct ofp_stats_msg);
1768 }
1769
1770 /* Returns the first byte past the nicira_stats_msg header in 'oh'. */
1771 const void *
1772 ofputil_nxstats_body(const struct ofp_header *oh)
1773 {
1774     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1775     return ((const struct nicira_stats_msg *) oh) + 1;
1776 }
1777
1778 /* Returns the number of bytes past the nicira_stats_msg header in 'oh'. */
1779 size_t
1780 ofputil_nxstats_body_len(const struct ofp_header *oh)
1781 {
1782     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1783     return ntohs(oh->length) - sizeof(struct nicira_stats_msg);
1784 }
1785
1786 struct ofpbuf *
1787 make_flow_mod(uint16_t command, const struct cls_rule *rule,
1788               size_t actions_len)
1789 {
1790     struct ofp_flow_mod *ofm;
1791     size_t size = sizeof *ofm + actions_len;
1792     struct ofpbuf *out = ofpbuf_new(size);
1793     ofm = ofpbuf_put_zeros(out, sizeof *ofm);
1794     ofm->header.version = OFP_VERSION;
1795     ofm->header.type = OFPT_FLOW_MOD;
1796     ofm->header.length = htons(size);
1797     ofm->cookie = 0;
1798     ofm->priority = htons(MIN(rule->priority, UINT16_MAX));
1799     ofputil_cls_rule_to_match(rule, &ofm->match);
1800     ofm->command = htons(command);
1801     return out;
1802 }
1803
1804 struct ofpbuf *
1805 make_add_flow(const struct cls_rule *rule, uint32_t buffer_id,
1806               uint16_t idle_timeout, size_t actions_len)
1807 {
1808     struct ofpbuf *out = make_flow_mod(OFPFC_ADD, rule, actions_len);
1809     struct ofp_flow_mod *ofm = out->data;
1810     ofm->idle_timeout = htons(idle_timeout);
1811     ofm->hard_timeout = htons(OFP_FLOW_PERMANENT);
1812     ofm->buffer_id = htonl(buffer_id);
1813     return out;
1814 }
1815
1816 struct ofpbuf *
1817 make_del_flow(const struct cls_rule *rule)
1818 {
1819     struct ofpbuf *out = make_flow_mod(OFPFC_DELETE_STRICT, rule, 0);
1820     struct ofp_flow_mod *ofm = out->data;
1821     ofm->out_port = htons(OFPP_NONE);
1822     return out;
1823 }
1824
1825 struct ofpbuf *
1826 make_add_simple_flow(const struct cls_rule *rule,
1827                      uint32_t buffer_id, uint16_t out_port,
1828                      uint16_t idle_timeout)
1829 {
1830     if (out_port != OFPP_NONE) {
1831         struct ofp_action_output *oao;
1832         struct ofpbuf *buffer;
1833
1834         buffer = make_add_flow(rule, buffer_id, idle_timeout, sizeof *oao);
1835         oao = ofpbuf_put_zeros(buffer, sizeof *oao);
1836         oao->type = htons(OFPAT_OUTPUT);
1837         oao->len = htons(sizeof *oao);
1838         oao->port = htons(out_port);
1839         return buffer;
1840     } else {
1841         return make_add_flow(rule, buffer_id, idle_timeout, 0);
1842     }
1843 }
1844
1845 struct ofpbuf *
1846 make_packet_in(uint32_t buffer_id, uint16_t in_port, uint8_t reason,
1847                const struct ofpbuf *payload, int max_send_len)
1848 {
1849     struct ofp_packet_in *opi;
1850     struct ofpbuf *buf;
1851     int send_len;
1852
1853     send_len = MIN(max_send_len, payload->size);
1854     buf = ofpbuf_new(sizeof *opi + send_len);
1855     opi = put_openflow_xid(offsetof(struct ofp_packet_in, data),
1856                            OFPT_PACKET_IN, 0, buf);
1857     opi->buffer_id = htonl(buffer_id);
1858     opi->total_len = htons(payload->size);
1859     opi->in_port = htons(in_port);
1860     opi->reason = reason;
1861     ofpbuf_put(buf, payload->data, send_len);
1862     update_openflow_length(buf);
1863
1864     return buf;
1865 }
1866
1867 struct ofpbuf *
1868 make_packet_out(const struct ofpbuf *packet, uint32_t buffer_id,
1869                 uint16_t in_port,
1870                 const struct ofp_action_header *actions, size_t n_actions)
1871 {
1872     size_t actions_len = n_actions * sizeof *actions;
1873     struct ofp_packet_out *opo;
1874     size_t size = sizeof *opo + actions_len + (packet ? packet->size : 0);
1875     struct ofpbuf *out = ofpbuf_new(size);
1876
1877     opo = ofpbuf_put_uninit(out, sizeof *opo);
1878     opo->header.version = OFP_VERSION;
1879     opo->header.type = OFPT_PACKET_OUT;
1880     opo->header.length = htons(size);
1881     opo->header.xid = htonl(0);
1882     opo->buffer_id = htonl(buffer_id);
1883     opo->in_port = htons(in_port == ODPP_LOCAL ? OFPP_LOCAL : in_port);
1884     opo->actions_len = htons(actions_len);
1885     ofpbuf_put(out, actions, actions_len);
1886     if (packet) {
1887         ofpbuf_put(out, packet->data, packet->size);
1888     }
1889     return out;
1890 }
1891
1892 struct ofpbuf *
1893 make_unbuffered_packet_out(const struct ofpbuf *packet,
1894                            uint16_t in_port, uint16_t out_port)
1895 {
1896     struct ofp_action_output action;
1897     action.type = htons(OFPAT_OUTPUT);
1898     action.len = htons(sizeof action);
1899     action.port = htons(out_port);
1900     return make_packet_out(packet, UINT32_MAX, in_port,
1901                            (struct ofp_action_header *) &action, 1);
1902 }
1903
1904 struct ofpbuf *
1905 make_buffered_packet_out(uint32_t buffer_id,
1906                          uint16_t in_port, uint16_t out_port)
1907 {
1908     if (out_port != OFPP_NONE) {
1909         struct ofp_action_output action;
1910         action.type = htons(OFPAT_OUTPUT);
1911         action.len = htons(sizeof action);
1912         action.port = htons(out_port);
1913         return make_packet_out(NULL, buffer_id, in_port,
1914                                (struct ofp_action_header *) &action, 1);
1915     } else {
1916         return make_packet_out(NULL, buffer_id, in_port, NULL, 0);
1917     }
1918 }
1919
1920 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
1921 struct ofpbuf *
1922 make_echo_request(void)
1923 {
1924     struct ofp_header *rq;
1925     struct ofpbuf *out = ofpbuf_new(sizeof *rq);
1926     rq = ofpbuf_put_uninit(out, sizeof *rq);
1927     rq->version = OFP_VERSION;
1928     rq->type = OFPT_ECHO_REQUEST;
1929     rq->length = htons(sizeof *rq);
1930     rq->xid = htonl(0);
1931     return out;
1932 }
1933
1934 /* Creates and returns an OFPT_ECHO_REPLY message matching the
1935  * OFPT_ECHO_REQUEST message in 'rq'. */
1936 struct ofpbuf *
1937 make_echo_reply(const struct ofp_header *rq)
1938 {
1939     size_t size = ntohs(rq->length);
1940     struct ofpbuf *out = ofpbuf_new(size);
1941     struct ofp_header *reply = ofpbuf_put(out, rq, size);
1942     reply->type = OFPT_ECHO_REPLY;
1943     return out;
1944 }
1945
1946 /* Checks that 'port' is a valid output port for the OFPAT_OUTPUT action, given
1947  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
1948  * 'port' is valid, otherwise an ofp_mkerr() return code. */
1949 int
1950 ofputil_check_output_port(uint16_t port, int max_ports)
1951 {
1952     switch (port) {
1953     case OFPP_IN_PORT:
1954     case OFPP_TABLE:
1955     case OFPP_NORMAL:
1956     case OFPP_FLOOD:
1957     case OFPP_ALL:
1958     case OFPP_CONTROLLER:
1959     case OFPP_LOCAL:
1960         return 0;
1961
1962     default:
1963         if (port < max_ports) {
1964             return 0;
1965         }
1966         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
1967     }
1968 }
1969
1970 int
1971 validate_actions(const union ofp_action *actions, size_t n_actions,
1972                  const struct flow *flow, int max_ports)
1973 {
1974     const union ofp_action *a;
1975     size_t left;
1976
1977     OFPUTIL_ACTION_FOR_EACH (a, left, actions, n_actions) {
1978         uint16_t port;
1979         int error;
1980         int code;
1981
1982         code = ofputil_decode_action(a);
1983         if (code < 0) {
1984             char *msg;
1985
1986             error = -code;
1987             msg = ofputil_error_to_string(error);
1988             VLOG_WARN_RL(&bad_ofmsg_rl,
1989                          "action decoding error at offset %td (%s)",
1990                          (a - actions) * sizeof *a, msg);
1991             free(msg);
1992
1993             return error;
1994         }
1995
1996         error = 0;
1997         switch ((enum ofputil_action_code) code) {
1998         case OFPUTIL_OFPAT_OUTPUT:
1999             error = ofputil_check_output_port(ntohs(a->output.port),
2000                                               max_ports);
2001             break;
2002
2003         case OFPUTIL_OFPAT_SET_VLAN_VID:
2004             if (a->vlan_vid.vlan_vid & ~htons(0xfff)) {
2005                 error = ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
2006             }
2007             break;
2008
2009         case OFPUTIL_OFPAT_SET_VLAN_PCP:
2010             if (a->vlan_pcp.vlan_pcp & ~7) {
2011                 error = ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
2012             }
2013             break;
2014
2015         case OFPUTIL_OFPAT_ENQUEUE:
2016             port = ntohs(((const struct ofp_action_enqueue *) a)->port);
2017             if (port >= max_ports && port != OFPP_IN_PORT) {
2018                 error = ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
2019             }
2020             break;
2021
2022         case OFPUTIL_NXAST_REG_MOVE:
2023             error = nxm_check_reg_move((const struct nx_action_reg_move *) a,
2024                                        flow);
2025             break;
2026
2027         case OFPUTIL_NXAST_REG_LOAD:
2028             error = nxm_check_reg_load((const struct nx_action_reg_load *) a,
2029                                        flow);
2030             break;
2031
2032         case OFPUTIL_NXAST_MULTIPATH:
2033             error = multipath_check((const struct nx_action_multipath *) a,
2034                                     flow);
2035             break;
2036
2037         case OFPUTIL_NXAST_AUTOPATH:
2038             error = autopath_check((const struct nx_action_autopath *) a,
2039                                    flow);
2040             break;
2041
2042         case OFPUTIL_NXAST_BUNDLE:
2043         case OFPUTIL_NXAST_BUNDLE_LOAD:
2044             error = bundle_check((const struct nx_action_bundle *) a,
2045                                  max_ports, flow);
2046             break;
2047
2048         case OFPUTIL_OFPAT_STRIP_VLAN:
2049         case OFPUTIL_OFPAT_SET_NW_SRC:
2050         case OFPUTIL_OFPAT_SET_NW_DST:
2051         case OFPUTIL_OFPAT_SET_NW_TOS:
2052         case OFPUTIL_OFPAT_SET_TP_SRC:
2053         case OFPUTIL_OFPAT_SET_TP_DST:
2054         case OFPUTIL_OFPAT_SET_DL_SRC:
2055         case OFPUTIL_OFPAT_SET_DL_DST:
2056         case OFPUTIL_NXAST_RESUBMIT:
2057         case OFPUTIL_NXAST_SET_TUNNEL:
2058         case OFPUTIL_NXAST_SET_QUEUE:
2059         case OFPUTIL_NXAST_POP_QUEUE:
2060         case OFPUTIL_NXAST_NOTE:
2061         case OFPUTIL_NXAST_SET_TUNNEL64:
2062             break;
2063         }
2064
2065         if (error) {
2066             char *msg = ofputil_error_to_string(error);
2067             VLOG_WARN_RL(&bad_ofmsg_rl, "bad action at offset %td (%s)",
2068                          (a - actions) * sizeof *a, msg);
2069             free(msg);
2070             return error;
2071         }
2072     }
2073     if (left) {
2074         VLOG_WARN_RL(&bad_ofmsg_rl, "bad action format at offset %zu",
2075                      (n_actions - left) * sizeof *a);
2076         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
2077     }
2078     return 0;
2079 }
2080
2081 struct ofputil_ofpat_action {
2082     enum ofputil_action_code code;
2083     unsigned int len;
2084 };
2085
2086 static const struct ofputil_ofpat_action ofpat_actions[] = {
2087     { OFPUTIL_OFPAT_OUTPUT,        8 },
2088     { OFPUTIL_OFPAT_SET_VLAN_VID,  8 },
2089     { OFPUTIL_OFPAT_SET_VLAN_PCP,  8 },
2090     { OFPUTIL_OFPAT_STRIP_VLAN,    8 },
2091     { OFPUTIL_OFPAT_SET_DL_SRC,   16 },
2092     { OFPUTIL_OFPAT_SET_DL_DST,   16 },
2093     { OFPUTIL_OFPAT_SET_NW_SRC,    8 },
2094     { OFPUTIL_OFPAT_SET_NW_DST,    8 },
2095     { OFPUTIL_OFPAT_SET_NW_TOS,    8 },
2096     { OFPUTIL_OFPAT_SET_TP_SRC,    8 },
2097     { OFPUTIL_OFPAT_SET_TP_DST,    8 },
2098     { OFPUTIL_OFPAT_ENQUEUE,      16 },
2099 };
2100
2101 struct ofputil_nxast_action {
2102     enum ofputil_action_code code;
2103     unsigned int min_len;
2104     unsigned int max_len;
2105 };
2106
2107 static const struct ofputil_nxast_action nxast_actions[] = {
2108     { 0, UINT_MAX, UINT_MAX }, /* NXAST_SNAT__OBSOLETE */
2109     { OFPUTIL_NXAST_RESUBMIT,     16, 16 },
2110     { OFPUTIL_NXAST_SET_TUNNEL,   16, 16 },
2111     { 0, UINT_MAX, UINT_MAX }, /* NXAST_DROP_SPOOFED_ARP__OBSOLETE */
2112     { OFPUTIL_NXAST_SET_QUEUE,    16, 16 },
2113     { OFPUTIL_NXAST_POP_QUEUE,    16, 16 },
2114     { OFPUTIL_NXAST_REG_MOVE,     24, 24 },
2115     { OFPUTIL_NXAST_REG_LOAD,     24, 24 },
2116     { OFPUTIL_NXAST_NOTE,         16, UINT_MAX },
2117     { OFPUTIL_NXAST_SET_TUNNEL64, 24, 24 },
2118     { OFPUTIL_NXAST_MULTIPATH,    32, 32 },
2119     { OFPUTIL_NXAST_AUTOPATH,     24, 24 },
2120     { OFPUTIL_NXAST_BUNDLE,       32, UINT_MAX },
2121     { OFPUTIL_NXAST_BUNDLE_LOAD,  32, UINT_MAX },
2122 };
2123
2124 static int
2125 ofputil_decode_ofpat_action(const union ofp_action *a)
2126 {
2127     int type = ntohs(a->type);
2128
2129     if (type < ARRAY_SIZE(ofpat_actions)) {
2130         const struct ofputil_ofpat_action *ooa = &ofpat_actions[type];
2131         unsigned int len = ntohs(a->header.len);
2132
2133         return (len == ooa->len
2134                 ? ooa->code
2135                 : -ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN));
2136     } else {
2137         return -ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_TYPE);
2138     }
2139 }
2140
2141 static int
2142 ofputil_decode_nxast_action(const union ofp_action *a)
2143 {
2144     unsigned int len = ntohs(a->header.len);
2145
2146     if (len < sizeof(struct nx_action_header)) {
2147         return -ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
2148     } else {
2149         const struct nx_action_header *nah = (const void *) a;
2150         int subtype = ntohs(nah->subtype);
2151
2152         if (subtype <= ARRAY_SIZE(nxast_actions)) {
2153             const struct ofputil_nxast_action *ona = &nxast_actions[subtype];
2154             if (len >= ona->min_len && len <= ona->max_len) {
2155                 return ona->code;
2156             } else if (ona->min_len == UINT_MAX) {
2157                 return -ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_TYPE);
2158             } else {
2159                 return -ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
2160             }
2161         } else {
2162             return -ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_TYPE);
2163         }
2164     }
2165 }
2166
2167 /* Parses 'a' to determine its type.  Returns a nonnegative OFPUTIL_OFPAT_* or
2168  * OFPUTIL_NXAST_* constant if successful, otherwise a negative OpenFlow error
2169  * code (as returned by ofp_mkerr()).
2170  *
2171  * The caller must have already verified that 'a''s length is correct (that is,
2172  * a->header.len is nonzero and a multiple of sizeof(union ofp_action) and no
2173  * longer than the amount of space allocated to 'a').
2174  *
2175  * This function verifies that 'a''s length is correct for the type of action
2176  * that it represents. */
2177 int
2178 ofputil_decode_action(const union ofp_action *a)
2179 {
2180     if (a->type != htons(OFPAT_VENDOR)) {
2181         return ofputil_decode_ofpat_action(a);
2182     } else if (a->vendor.vendor == htonl(NX_VENDOR_ID)) {
2183         return ofputil_decode_nxast_action(a);
2184     } else {
2185         return -ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR);
2186     }
2187 }
2188
2189 /* Parses 'a' and returns its type as an OFPUTIL_OFPAT_* or OFPUTIL_NXAST_*
2190  * constant.  The caller must have already validated that 'a' is a valid action
2191  * understood by Open vSwitch (e.g. by a previous successful call to
2192  * ofputil_decode_action()). */
2193 enum ofputil_action_code
2194 ofputil_decode_action_unsafe(const union ofp_action *a)
2195 {
2196     if (a->type != htons(OFPAT_VENDOR)) {
2197         return ofpat_actions[ntohs(a->type)].code;
2198     } else {
2199         const struct nx_action_header *nah = (const void *) a;
2200
2201         return nxast_actions[ntohs(nah->subtype)].code;
2202     }
2203 }
2204
2205 /* Returns true if 'action' outputs to 'port', false otherwise. */
2206 bool
2207 action_outputs_to_port(const union ofp_action *action, ovs_be16 port)
2208 {
2209     switch (ntohs(action->type)) {
2210     case OFPAT_OUTPUT:
2211         return action->output.port == port;
2212     case OFPAT_ENQUEUE:
2213         return ((const struct ofp_action_enqueue *) action)->port == port;
2214     default:
2215         return false;
2216     }
2217 }
2218
2219 /* "Normalizes" the wildcards in 'rule'.  That means:
2220  *
2221  *    1. If the type of level N is known, then only the valid fields for that
2222  *       level may be specified.  For example, ARP does not have a TOS field,
2223  *       so nw_tos must be wildcarded if 'rule' specifies an ARP flow.
2224  *       Similarly, IPv4 does not have any IPv6 addresses, so ipv6_src and
2225  *       ipv6_dst (and other fields) must be wildcarded if 'rule' specifies an
2226  *       IPv4 flow.
2227  *
2228  *    2. If the type of level N is not known (or not understood by Open
2229  *       vSwitch), then no fields at all for that level may be specified.  For
2230  *       example, Open vSwitch does not understand SCTP, an L4 protocol, so the
2231  *       L4 fields tp_src and tp_dst must be wildcarded if 'rule' specifies an
2232  *       SCTP flow.
2233  *
2234  * 'flow_format' specifies the format of the flow as received or as intended to
2235  * be sent.  This is important for IPv6 and ARP, for which NXM supports more
2236  * detailed matching. */
2237 void
2238 ofputil_normalize_rule(struct cls_rule *rule, enum nx_flow_format flow_format)
2239 {
2240     enum {
2241         MAY_NW_ADDR     = 1 << 0, /* nw_src, nw_dst */
2242         MAY_TP_ADDR     = 1 << 1, /* tp_src, tp_dst */
2243         MAY_NW_PROTO    = 1 << 2, /* nw_proto */
2244         MAY_NW_TOS      = 1 << 3, /* nw_tos */
2245         MAY_ARP_SHA     = 1 << 4, /* arp_sha */
2246         MAY_ARP_THA     = 1 << 5, /* arp_tha */
2247         MAY_IPV6_ADDR   = 1 << 6, /* ipv6_src, ipv6_dst */
2248         MAY_ND_TARGET   = 1 << 7  /* nd_target */
2249     } may_match;
2250
2251     struct flow_wildcards wc;
2252
2253     /* Figure out what fields may be matched. */
2254     if (rule->flow.dl_type == htons(ETH_TYPE_IP)) {
2255         may_match = MAY_NW_PROTO | MAY_NW_TOS | MAY_NW_ADDR;
2256         if (rule->flow.nw_proto == IPPROTO_TCP ||
2257             rule->flow.nw_proto == IPPROTO_UDP ||
2258             rule->flow.nw_proto == IPPROTO_ICMP) {
2259             may_match |= MAY_TP_ADDR;
2260         }
2261     } else if (rule->flow.dl_type == htons(ETH_TYPE_IPV6)
2262                && flow_format == NXFF_NXM) {
2263         may_match = MAY_NW_PROTO | MAY_NW_TOS | MAY_IPV6_ADDR;
2264         if (rule->flow.nw_proto == IPPROTO_TCP ||
2265             rule->flow.nw_proto == IPPROTO_UDP) {
2266             may_match |= MAY_TP_ADDR;
2267         } else if (rule->flow.nw_proto == IPPROTO_ICMPV6) {
2268             may_match |= MAY_TP_ADDR;
2269             if (rule->flow.tp_src == htons(ND_NEIGHBOR_SOLICIT)) {
2270                 may_match |= MAY_ND_TARGET | MAY_ARP_SHA;
2271             } else if (rule->flow.tp_src == htons(ND_NEIGHBOR_ADVERT)) {
2272                 may_match |= MAY_ND_TARGET | MAY_ARP_THA;
2273             }
2274         }
2275     } else if (rule->flow.dl_type == htons(ETH_TYPE_ARP)) {
2276         may_match = MAY_NW_PROTO | MAY_NW_ADDR;
2277         if (flow_format == NXFF_NXM) {
2278             may_match |= MAY_ARP_SHA | MAY_ARP_THA;
2279         }
2280     } else {
2281         may_match = 0;
2282     }
2283
2284     /* Clear the fields that may not be matched. */
2285     wc = rule->wc;
2286     if (!(may_match & MAY_NW_ADDR)) {
2287         wc.nw_src_mask = wc.nw_dst_mask = htonl(0);
2288     }
2289     if (!(may_match & MAY_TP_ADDR)) {
2290         wc.wildcards |= FWW_TP_SRC | FWW_TP_DST;
2291     }
2292     if (!(may_match & MAY_NW_PROTO)) {
2293         wc.wildcards |= FWW_NW_PROTO;
2294     }
2295     if (!(may_match & MAY_NW_TOS)) {
2296         wc.wildcards |= FWW_NW_TOS;
2297     }
2298     if (!(may_match & MAY_ARP_SHA)) {
2299         wc.wildcards |= FWW_ARP_SHA;
2300     }
2301     if (!(may_match & MAY_ARP_THA)) {
2302         wc.wildcards |= FWW_ARP_THA;
2303     }
2304     if (!(may_match & MAY_IPV6_ADDR)) {
2305         wc.ipv6_src_mask = wc.ipv6_dst_mask = in6addr_any;
2306     }
2307     if (!(may_match & MAY_ND_TARGET)) {
2308         wc.wildcards |= FWW_ND_TARGET;
2309     }
2310
2311     /* Log any changes. */
2312     if (!flow_wildcards_equal(&wc, &rule->wc)) {
2313         bool log = !VLOG_DROP_INFO(&bad_ofmsg_rl);
2314         char *pre = log ? cls_rule_to_string(rule) : NULL;
2315
2316         rule->wc = wc;
2317         cls_rule_zero_wildcarded_fields(rule);
2318
2319         if (log) {
2320             char *post = cls_rule_to_string(rule);
2321             VLOG_INFO("normalization changed ofp_match, details:");
2322             VLOG_INFO(" pre: %s", pre);
2323             VLOG_INFO("post: %s", post);
2324             free(pre);
2325             free(post);
2326         }
2327     }
2328 }
2329
2330 static uint32_t
2331 vendor_code_to_id(uint8_t code)
2332 {
2333     switch (code) {
2334 #define OFPUTIL_VENDOR(NAME, VENDOR_ID) case NAME: return VENDOR_ID;
2335         OFPUTIL_VENDORS
2336 #undef OFPUTIL_VENDOR
2337     default:
2338         return UINT32_MAX;
2339     }
2340 }
2341
2342 static int
2343 vendor_id_to_code(uint32_t id)
2344 {
2345     switch (id) {
2346 #define OFPUTIL_VENDOR(NAME, VENDOR_ID) case VENDOR_ID: return NAME;
2347         OFPUTIL_VENDORS
2348 #undef OFPUTIL_VENDOR
2349     default:
2350         return -1;
2351     }
2352 }
2353
2354 /* Creates and returns an OpenFlow message of type OFPT_ERROR with the error
2355  * information taken from 'error', whose encoding must be as described in the
2356  * large comment in ofp-util.h.  If 'oh' is nonnull, then the error will use
2357  * oh->xid as its transaction ID, and it will include up to the first 64 bytes
2358  * of 'oh'.
2359  *
2360  * Returns NULL if 'error' is not an OpenFlow error code. */
2361 struct ofpbuf *
2362 ofputil_encode_error_msg(int error, const struct ofp_header *oh)
2363 {
2364     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2365
2366     struct ofpbuf *buf;
2367     const void *data;
2368     size_t len;
2369     uint8_t vendor;
2370     uint16_t type;
2371     uint16_t code;
2372     ovs_be32 xid;
2373
2374     if (!is_ofp_error(error)) {
2375         /* We format 'error' with strerror() here since it seems likely to be
2376          * a system errno value. */
2377         VLOG_WARN_RL(&rl, "invalid OpenFlow error code %d (%s)",
2378                      error, strerror(error));
2379         return NULL;
2380     }
2381
2382     if (oh) {
2383         xid = oh->xid;
2384         data = oh;
2385         len = ntohs(oh->length);
2386         if (len > 64) {
2387             len = 64;
2388         }
2389     } else {
2390         xid = 0;
2391         data = NULL;
2392         len = 0;
2393     }
2394
2395     vendor = get_ofp_err_vendor(error);
2396     type = get_ofp_err_type(error);
2397     code = get_ofp_err_code(error);
2398     if (vendor == OFPUTIL_VENDOR_OPENFLOW) {
2399         struct ofp_error_msg *oem;
2400
2401         oem = make_openflow_xid(len + sizeof *oem, OFPT_ERROR, xid, &buf);
2402         oem->type = htons(type);
2403         oem->code = htons(code);
2404     } else {
2405         struct ofp_error_msg *oem;
2406         struct nx_vendor_error *nve;
2407         uint32_t vendor_id;
2408
2409         vendor_id = vendor_code_to_id(vendor);
2410         if (vendor_id == UINT32_MAX) {
2411             VLOG_WARN_RL(&rl, "error %x contains invalid vendor code %d",
2412                          error, vendor);
2413             return NULL;
2414         }
2415
2416         oem = make_openflow_xid(len + sizeof *oem + sizeof *nve,
2417                                 OFPT_ERROR, xid, &buf);
2418         oem->type = htons(NXET_VENDOR);
2419         oem->code = htons(NXVC_VENDOR_ERROR);
2420
2421         nve = (struct nx_vendor_error *)oem->data;
2422         nve->vendor = htonl(vendor_id);
2423         nve->type = htons(type);
2424         nve->code = htons(code);
2425     }
2426
2427     if (len) {
2428         buf->size -= len;
2429         ofpbuf_put(buf, data, len);
2430     }
2431
2432     return buf;
2433 }
2434
2435 /* Decodes 'oh', which should be an OpenFlow OFPT_ERROR message, and returns an
2436  * Open vSwitch internal error code in the format described in the large
2437  * comment in ofp-util.h.
2438  *
2439  * If 'payload_ofs' is nonnull, on success '*payload_ofs' is set to the offset
2440  * to the payload starting from 'oh' and on failure it is set to 0. */
2441 int
2442 ofputil_decode_error_msg(const struct ofp_header *oh, size_t *payload_ofs)
2443 {
2444     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2445
2446     const struct ofp_error_msg *oem;
2447     uint16_t type, code;
2448     struct ofpbuf b;
2449     int vendor;
2450
2451     if (payload_ofs) {
2452         *payload_ofs = 0;
2453     }
2454     if (oh->type != OFPT_ERROR) {
2455         return EPROTO;
2456     }
2457
2458     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2459     oem = ofpbuf_try_pull(&b, sizeof *oem);
2460     if (!oem) {
2461         return EPROTO;
2462     }
2463
2464     type = ntohs(oem->type);
2465     code = ntohs(oem->code);
2466     if (type == NXET_VENDOR && code == NXVC_VENDOR_ERROR) {
2467         const struct nx_vendor_error *nve = ofpbuf_try_pull(&b, sizeof *nve);
2468         if (!nve) {
2469             return EPROTO;
2470         }
2471
2472         vendor = vendor_id_to_code(ntohl(nve->vendor));
2473         if (vendor < 0) {
2474             VLOG_WARN_RL(&rl, "error contains unknown vendor ID %#"PRIx32,
2475                          ntohl(nve->vendor));
2476             return EPROTO;
2477         }
2478         type = ntohs(nve->type);
2479         code = ntohs(nve->code);
2480     } else {
2481         vendor = OFPUTIL_VENDOR_OPENFLOW;
2482     }
2483
2484     if (type >= 1024) {
2485         VLOG_WARN_RL(&rl, "error contains type %"PRIu16" greater than "
2486                      "supported maximum value 1023", type);
2487         return EPROTO;
2488     }
2489
2490     if (payload_ofs) {
2491         *payload_ofs = (uint8_t *) b.data - (uint8_t *) oh;
2492     }
2493     return ofp_mkerr_vendor(vendor, type, code);
2494 }
2495
2496 void
2497 ofputil_format_error(struct ds *s, int error)
2498 {
2499     if (is_errno(error)) {
2500         ds_put_cstr(s, strerror(error));
2501     } else {
2502         uint16_t type = get_ofp_err_type(error);
2503         uint16_t code = get_ofp_err_code(error);
2504         const char *type_s = ofp_error_type_to_string(type);
2505         const char *code_s = ofp_error_code_to_string(type, code);
2506
2507         ds_put_format(s, "type ");
2508         if (type_s) {
2509             ds_put_cstr(s, type_s);
2510         } else {
2511             ds_put_format(s, "%"PRIu16, type);
2512         }
2513
2514         ds_put_cstr(s, ", code ");
2515         if (code_s) {
2516             ds_put_cstr(s, code_s);
2517         } else {
2518             ds_put_format(s, "%"PRIu16, code);
2519         }
2520     }
2521 }
2522
2523 char *
2524 ofputil_error_to_string(int error)
2525 {
2526     struct ds s = DS_EMPTY_INITIALIZER;
2527     ofputil_format_error(&s, error);
2528     return ds_steal_cstr(&s);
2529 }
2530
2531 /* Attempts to pull 'actions_len' bytes from the front of 'b'.  Returns 0 if
2532  * successful, otherwise an OpenFlow error.
2533  *
2534  * If successful, the first action is stored in '*actionsp' and the number of
2535  * "union ofp_action" size elements into '*n_actionsp'.  Otherwise NULL and 0
2536  * are stored, respectively.
2537  *
2538  * This function does not check that the actions are valid (the caller should
2539  * do so, with validate_actions()).  The caller is also responsible for making
2540  * sure that 'b->data' is initially aligned appropriately for "union
2541  * ofp_action". */
2542 int
2543 ofputil_pull_actions(struct ofpbuf *b, unsigned int actions_len,
2544                      union ofp_action **actionsp, size_t *n_actionsp)
2545 {
2546     if (actions_len % OFP_ACTION_ALIGN != 0) {
2547         VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
2548                      "is not a multiple of %d", actions_len, OFP_ACTION_ALIGN);
2549         goto error;
2550     }
2551
2552     *actionsp = ofpbuf_try_pull(b, actions_len);
2553     if (*actionsp == NULL) {
2554         VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
2555                      "exceeds remaining message length (%zu)",
2556                      actions_len, b->size);
2557         goto error;
2558     }
2559
2560     *n_actionsp = actions_len / OFP_ACTION_ALIGN;
2561     return 0;
2562
2563 error:
2564     *actionsp = NULL;
2565     *n_actionsp = 0;
2566     return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
2567 }
2568
2569 bool
2570 ofputil_actions_equal(const union ofp_action *a, size_t n_a,
2571                       const union ofp_action *b, size_t n_b)
2572 {
2573     return n_a == n_b && (!n_a || !memcmp(a, b, n_a * sizeof *a));
2574 }
2575
2576 union ofp_action *
2577 ofputil_actions_clone(const union ofp_action *actions, size_t n)
2578 {
2579     return n ? xmemdup(actions, n * sizeof *actions) : NULL;
2580 }