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