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