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