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