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