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