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