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