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