ofproto: Datapath statistics accounted twice.
[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 <stdlib.h>
22 #include "autopath.h"
23 #include "byte-order.h"
24 #include "classifier.h"
25 #include "dynamic-string.h"
26 #include "multipath.h"
27 #include "nx-match.h"
28 #include "ofp-errors.h"
29 #include "ofp-util.h"
30 #include "ofpbuf.h"
31 #include "packets.h"
32 #include "random.h"
33 #include "unaligned.h"
34 #include "type-props.h"
35 #include "vlog.h"
36
37 VLOG_DEFINE_THIS_MODULE(ofp_util);
38
39 static ovs_be32 normalize_wildcards(const struct ofp_match *);
40
41 /* Rate limit for OpenFlow message parse errors.  These always indicate a bug
42  * in the peer and so there's not much point in showing a lot of them. */
43 static struct vlog_rate_limit bad_ofmsg_rl = VLOG_RATE_LIMIT_INIT(1, 5);
44
45 /* Given the wildcard bit count in the least-significant 6 of 'wcbits', returns
46  * an IP netmask with a 1 in each bit that must match and a 0 in each bit that
47  * is wildcarded.
48  *
49  * The bits in 'wcbits' are in the format used in enum ofp_flow_wildcards: 0
50  * is exact match, 1 ignores the LSB, 2 ignores the 2 least-significant bits,
51  * ..., 32 and higher wildcard the entire field.  This is the *opposite* of the
52  * usual convention where e.g. /24 indicates that 8 bits (not 24 bits) are
53  * wildcarded. */
54 ovs_be32
55 ofputil_wcbits_to_netmask(int wcbits)
56 {
57     wcbits &= 0x3f;
58     return wcbits < 32 ? htonl(~((1u << wcbits) - 1)) : 0;
59 }
60
61 /* Given the IP netmask 'netmask', returns the number of bits of the IP address
62  * that it wildcards.  'netmask' must be a CIDR netmask (see ip_is_cidr()). */
63 int
64 ofputil_netmask_to_wcbits(ovs_be32 netmask)
65 {
66     assert(ip_is_cidr(netmask));
67 #if __GNUC__ >= 4
68     return netmask == htonl(0) ? 32 : __builtin_ctz(ntohl(netmask));
69 #else
70     int wcbits;
71
72     for (wcbits = 32; netmask; wcbits--) {
73         netmask &= netmask - 1;
74     }
75
76     return wcbits;
77 #endif
78 }
79
80 /* A list of the FWW_* and OFPFW_ bits that have the same value, meaning, and
81  * name. */
82 #define WC_INVARIANT_LIST \
83     WC_INVARIANT_BIT(IN_PORT) \
84     WC_INVARIANT_BIT(DL_SRC) \
85     WC_INVARIANT_BIT(DL_DST) \
86     WC_INVARIANT_BIT(DL_TYPE) \
87     WC_INVARIANT_BIT(NW_PROTO) \
88     WC_INVARIANT_BIT(TP_SRC) \
89     WC_INVARIANT_BIT(TP_DST)
90
91 /* Verify that all of the invariant bits (as defined on WC_INVARIANT_LIST)
92  * actually have the same names and values. */
93 #define WC_INVARIANT_BIT(NAME) BUILD_ASSERT_DECL(FWW_##NAME == OFPFW_##NAME);
94     WC_INVARIANT_LIST
95 #undef WC_INVARIANT_BIT
96
97 /* WC_INVARIANTS is the invariant bits (as defined on WC_INVARIANT_LIST) all
98  * OR'd together. */
99 static const flow_wildcards_t WC_INVARIANTS = 0
100 #define WC_INVARIANT_BIT(NAME) | FWW_##NAME
101     WC_INVARIANT_LIST
102 #undef WC_INVARIANT_BIT
103 ;
104
105 /* Converts the ofp_match in 'match' into a cls_rule in 'rule', with the given
106  * 'priority'. */
107 void
108 ofputil_cls_rule_from_match(const struct ofp_match *match,
109                             unsigned int priority, struct cls_rule *rule)
110 {
111     struct flow_wildcards *wc = &rule->wc;
112     uint32_t ofpfw;
113     ovs_be16 vid, pcp;
114
115     /* Initialize rule->priority. */
116     ofpfw = ntohl(match->wildcards) & OFPFW_ALL;
117     rule->priority = !ofpfw ? UINT16_MAX : priority;
118
119     /* Initialize most of rule->wc. */
120     flow_wildcards_init_catchall(wc);
121     wc->wildcards = (OVS_FORCE flow_wildcards_t) ofpfw & WC_INVARIANTS;
122
123     /* Wildcard fields that aren't defined by ofp_match or tun_id. */
124     wc->wildcards |= (FWW_ARP_SHA | FWW_ARP_THA | FWW_ND_TARGET);
125
126     if (ofpfw & OFPFW_NW_TOS) {
127         wc->wildcards |= FWW_NW_TOS;
128     }
129     wc->nw_src_mask = ofputil_wcbits_to_netmask(ofpfw >> OFPFW_NW_SRC_SHIFT);
130     wc->nw_dst_mask = ofputil_wcbits_to_netmask(ofpfw >> OFPFW_NW_DST_SHIFT);
131
132     if (ofpfw & OFPFW_DL_DST) {
133         /* OpenFlow 1.0 OFPFW_DL_DST covers the whole Ethernet destination, but
134          * Open vSwitch breaks the Ethernet destination into bits as FWW_DL_DST
135          * and FWW_ETH_MCAST. */
136         wc->wildcards |= FWW_ETH_MCAST;
137     }
138
139     /* Initialize most of rule->flow. */
140     rule->flow.nw_src = match->nw_src;
141     rule->flow.nw_dst = match->nw_dst;
142     rule->flow.in_port = (match->in_port == htons(OFPP_LOCAL) ? ODPP_LOCAL
143                      : ntohs(match->in_port));
144     rule->flow.dl_type = ofputil_dl_type_from_openflow(match->dl_type);
145     rule->flow.tp_src = match->tp_src;
146     rule->flow.tp_dst = match->tp_dst;
147     memcpy(rule->flow.dl_src, match->dl_src, ETH_ADDR_LEN);
148     memcpy(rule->flow.dl_dst, match->dl_dst, ETH_ADDR_LEN);
149     rule->flow.nw_tos = match->nw_tos;
150     rule->flow.nw_proto = match->nw_proto;
151
152     /* Translate VLANs. */
153     vid = match->dl_vlan & htons(VLAN_VID_MASK);
154     pcp = htons((match->dl_vlan_pcp << VLAN_PCP_SHIFT) & VLAN_PCP_MASK);
155     switch (ofpfw & (OFPFW_DL_VLAN | OFPFW_DL_VLAN_PCP)) {
156     case OFPFW_DL_VLAN | OFPFW_DL_VLAN_PCP:
157         /* Wildcard everything. */
158         rule->flow.vlan_tci = htons(0);
159         rule->wc.vlan_tci_mask = htons(0);
160         break;
161
162     case OFPFW_DL_VLAN_PCP:
163         if (match->dl_vlan == htons(OFP_VLAN_NONE)) {
164             /* Match only packets without 802.1Q header. */
165             rule->flow.vlan_tci = htons(0);
166             rule->wc.vlan_tci_mask = htons(0xffff);
167         } else {
168             /* Wildcard PCP, specific VID. */
169             rule->flow.vlan_tci = vid | htons(VLAN_CFI);
170             rule->wc.vlan_tci_mask = htons(VLAN_VID_MASK | VLAN_CFI);
171         }
172         break;
173
174     case OFPFW_DL_VLAN:
175         /* Wildcard VID, specific PCP. */
176         rule->flow.vlan_tci = pcp | htons(VLAN_CFI);
177         rule->wc.vlan_tci_mask = htons(VLAN_PCP_MASK | VLAN_CFI);
178         break;
179
180     case 0:
181         if (match->dl_vlan == htons(OFP_VLAN_NONE)) {
182             /* This case is odd, since we can't have a specific PCP without an
183              * 802.1Q header.  However, older versions of OVS treated this as
184              * matching packets withut an 802.1Q header, so we do here too. */
185             rule->flow.vlan_tci = htons(0);
186             rule->wc.vlan_tci_mask = htons(0xffff);
187         } else {
188             /* Specific VID and PCP. */
189             rule->flow.vlan_tci = vid | pcp | htons(VLAN_CFI);
190             rule->wc.vlan_tci_mask = htons(0xffff);
191         }
192         break;
193     }
194
195     /* Clean up. */
196     cls_rule_zero_wildcarded_fields(rule);
197 }
198
199 /* Convert 'rule' into the OpenFlow match structure 'match'. */
200 void
201 ofputil_cls_rule_to_match(const struct cls_rule *rule, struct ofp_match *match)
202 {
203     const struct flow_wildcards *wc = &rule->wc;
204     uint32_t ofpfw;
205
206     /* Figure out most OpenFlow wildcards. */
207     ofpfw = (OVS_FORCE uint32_t) (wc->wildcards & WC_INVARIANTS);
208     ofpfw |= ofputil_netmask_to_wcbits(wc->nw_src_mask) << OFPFW_NW_SRC_SHIFT;
209     ofpfw |= ofputil_netmask_to_wcbits(wc->nw_dst_mask) << OFPFW_NW_DST_SHIFT;
210     if (wc->wildcards & FWW_NW_TOS) {
211         ofpfw |= OFPFW_NW_TOS;
212     }
213
214     /* Translate VLANs. */
215     match->dl_vlan = htons(0);
216     match->dl_vlan_pcp = 0;
217     if (rule->wc.vlan_tci_mask == htons(0)) {
218         ofpfw |= OFPFW_DL_VLAN | OFPFW_DL_VLAN_PCP;
219     } else if (rule->wc.vlan_tci_mask & htons(VLAN_CFI)
220                && !(rule->flow.vlan_tci & htons(VLAN_CFI))) {
221         match->dl_vlan = htons(OFP_VLAN_NONE);
222     } else {
223         if (!(rule->wc.vlan_tci_mask & htons(VLAN_VID_MASK))) {
224             ofpfw |= OFPFW_DL_VLAN;
225         } else {
226             match->dl_vlan = htons(vlan_tci_to_vid(rule->flow.vlan_tci));
227         }
228
229         if (!(rule->wc.vlan_tci_mask & htons(VLAN_PCP_MASK))) {
230             ofpfw |= OFPFW_DL_VLAN_PCP;
231         } else {
232             match->dl_vlan_pcp = vlan_tci_to_pcp(rule->flow.vlan_tci);
233         }
234     }
235
236     /* Compose most of the match structure. */
237     match->wildcards = htonl(ofpfw);
238     match->in_port = htons(rule->flow.in_port == ODPP_LOCAL ? OFPP_LOCAL
239                            : rule->flow.in_port);
240     memcpy(match->dl_src, rule->flow.dl_src, ETH_ADDR_LEN);
241     memcpy(match->dl_dst, rule->flow.dl_dst, ETH_ADDR_LEN);
242     match->dl_type = ofputil_dl_type_to_openflow(rule->flow.dl_type);
243     match->nw_src = rule->flow.nw_src;
244     match->nw_dst = rule->flow.nw_dst;
245     match->nw_tos = rule->flow.nw_tos;
246     match->nw_proto = rule->flow.nw_proto;
247     match->tp_src = rule->flow.tp_src;
248     match->tp_dst = rule->flow.tp_dst;
249     memset(match->pad1, '\0', sizeof match->pad1);
250     memset(match->pad2, '\0', sizeof match->pad2);
251 }
252
253 /* Given a 'dl_type' value in the format used in struct flow, returns the
254  * corresponding 'dl_type' value for use in an OpenFlow ofp_match structure. */
255 ovs_be16
256 ofputil_dl_type_to_openflow(ovs_be16 flow_dl_type)
257 {
258     return (flow_dl_type == htons(FLOW_DL_TYPE_NONE)
259             ? htons(OFP_DL_TYPE_NOT_ETH_TYPE)
260             : flow_dl_type);
261 }
262
263 /* Given a 'dl_type' value in the format used in an OpenFlow ofp_match
264  * structure, returns the corresponding 'dl_type' value for use in struct
265  * flow. */
266 ovs_be16
267 ofputil_dl_type_from_openflow(ovs_be16 ofp_dl_type)
268 {
269     return (ofp_dl_type == htons(OFP_DL_TYPE_NOT_ETH_TYPE)
270             ? htons(FLOW_DL_TYPE_NONE)
271             : ofp_dl_type);
272 }
273
274 /* Returns a transaction ID to use for an outgoing OpenFlow message. */
275 static ovs_be32
276 alloc_xid(void)
277 {
278     static uint32_t next_xid = 1;
279     return htonl(next_xid++);
280 }
281 \f
282 /* Basic parsing of OpenFlow messages. */
283
284 struct ofputil_msg_type {
285     enum ofputil_msg_code code; /* OFPUTIL_*. */
286     uint32_t value;             /* OFPT_*, OFPST_*, NXT_*, or NXST_*. */
287     const char *name;           /* e.g. "OFPT_FLOW_REMOVED". */
288     unsigned int min_size;      /* Minimum total message size in bytes. */
289     /* 0 if 'min_size' is the exact size that the message must be.  Otherwise,
290      * the message may exceed 'min_size' by an even multiple of this value. */
291     unsigned int extra_multiple;
292 };
293
294 struct ofputil_msg_category {
295     const char *name;           /* e.g. "OpenFlow message" */
296     const struct ofputil_msg_type *types;
297     size_t n_types;
298     int missing_error;          /* ofp_mkerr() value for missing type. */
299 };
300
301 static bool
302 ofputil_length_ok(const struct ofputil_msg_category *cat,
303                   const struct ofputil_msg_type *type,
304                   unsigned int size)
305 {
306     switch (type->extra_multiple) {
307     case 0:
308         if (size != type->min_size) {
309             VLOG_WARN_RL(&bad_ofmsg_rl, "received %s %s with incorrect "
310                          "length %u (expected length %u)",
311                          cat->name, type->name, size, type->min_size);
312             return false;
313         }
314         return true;
315
316     case 1:
317         if (size < type->min_size) {
318             VLOG_WARN_RL(&bad_ofmsg_rl, "received %s %s with incorrect "
319                          "length %u (expected length at least %u bytes)",
320                          cat->name, type->name, size, type->min_size);
321             return false;
322         }
323         return true;
324
325     default:
326         if (size < type->min_size
327             || (size - type->min_size) % type->extra_multiple) {
328             VLOG_WARN_RL(&bad_ofmsg_rl, "received %s %s with incorrect "
329                          "length %u (must be exactly %u bytes or longer "
330                          "by an integer multiple of %u bytes)",
331                          cat->name, type->name, size,
332                          type->min_size, type->extra_multiple);
333             return false;
334         }
335         return true;
336     }
337 }
338
339 static int
340 ofputil_lookup_openflow_message(const struct ofputil_msg_category *cat,
341                                 uint32_t value, unsigned int size,
342                                 const struct ofputil_msg_type **typep)
343 {
344     const struct ofputil_msg_type *type;
345
346     for (type = cat->types; type < &cat->types[cat->n_types]; type++) {
347         if (type->value == value) {
348             if (!ofputil_length_ok(cat, type, size)) {
349                 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
350             }
351             *typep = type;
352             return 0;
353         }
354     }
355
356     VLOG_WARN_RL(&bad_ofmsg_rl, "received %s of unknown type %"PRIu32,
357                  cat->name, value);
358     return cat->missing_error;
359 }
360
361 static int
362 ofputil_decode_vendor(const struct ofp_header *oh,
363                       const struct ofputil_msg_type **typep)
364 {
365     static const struct ofputil_msg_type nxt_messages[] = {
366         { OFPUTIL_NXT_ROLE_REQUEST,
367           NXT_ROLE_REQUEST, "NXT_ROLE_REQUEST",
368           sizeof(struct nx_role_request), 0 },
369
370         { OFPUTIL_NXT_ROLE_REPLY,
371           NXT_ROLE_REPLY, "NXT_ROLE_REPLY",
372           sizeof(struct nx_role_request), 0 },
373
374         { OFPUTIL_NXT_SET_FLOW_FORMAT,
375           NXT_SET_FLOW_FORMAT, "NXT_SET_FLOW_FORMAT",
376           sizeof(struct nxt_set_flow_format), 0 },
377
378         { OFPUTIL_NXT_FLOW_MOD,
379           NXT_FLOW_MOD, "NXT_FLOW_MOD",
380           sizeof(struct nx_flow_mod), 8 },
381
382         { OFPUTIL_NXT_FLOW_REMOVED,
383           NXT_FLOW_REMOVED, "NXT_FLOW_REMOVED",
384           sizeof(struct nx_flow_removed), 8 },
385     };
386
387     static const struct ofputil_msg_category nxt_category = {
388         "Nicira extension message",
389         nxt_messages, ARRAY_SIZE(nxt_messages),
390         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE)
391     };
392
393     const struct ofp_vendor_header *ovh;
394     const struct nicira_header *nh;
395
396     ovh = (const struct ofp_vendor_header *) oh;
397     if (ovh->vendor != htonl(NX_VENDOR_ID)) {
398         VLOG_WARN_RL(&bad_ofmsg_rl, "received vendor message for unknown "
399                      "vendor %"PRIx32, ntohl(ovh->vendor));
400         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_VENDOR);
401     }
402
403     if (ntohs(ovh->header.length) < sizeof(struct nicira_header)) {
404         VLOG_WARN_RL(&bad_ofmsg_rl, "received Nicira vendor message of "
405                      "length %u (expected at least %zu)",
406                      ntohs(ovh->header.length), sizeof(struct nicira_header));
407         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
408     }
409
410     nh = (const struct nicira_header *) oh;
411     return ofputil_lookup_openflow_message(&nxt_category, ntohl(nh->subtype),
412                                            ntohs(oh->length), typep);
413 }
414
415 static int
416 check_nxstats_msg(const struct ofp_header *oh)
417 {
418     const struct ofp_stats_request *osr;
419     ovs_be32 vendor;
420
421     osr = (const struct ofp_stats_request *) oh;
422
423     memcpy(&vendor, osr->body, sizeof vendor);
424     if (vendor != htonl(NX_VENDOR_ID)) {
425         VLOG_WARN_RL(&bad_ofmsg_rl, "received vendor stats message for "
426                      "unknown vendor %"PRIx32, ntohl(vendor));
427         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_VENDOR);
428     }
429
430     if (ntohs(osr->header.length) < sizeof(struct nicira_stats_msg)) {
431         VLOG_WARN_RL(&bad_ofmsg_rl, "truncated Nicira stats message");
432         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
433     }
434
435     return 0;
436 }
437
438 static int
439 ofputil_decode_nxst_request(const struct ofp_header *oh,
440                             const struct ofputil_msg_type **typep)
441 {
442     static const struct ofputil_msg_type nxst_requests[] = {
443         { OFPUTIL_NXST_FLOW_REQUEST,
444           NXST_FLOW, "NXST_FLOW request",
445           sizeof(struct nx_flow_stats_request), 8 },
446
447         { OFPUTIL_NXST_AGGREGATE_REQUEST,
448           NXST_AGGREGATE, "NXST_AGGREGATE request",
449           sizeof(struct nx_aggregate_stats_request), 8 },
450     };
451
452     static const struct ofputil_msg_category nxst_request_category = {
453         "Nicira extension statistics request",
454         nxst_requests, ARRAY_SIZE(nxst_requests),
455         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE)
456     };
457
458     const struct nicira_stats_msg *nsm;
459     int error;
460
461     error = check_nxstats_msg(oh);
462     if (error) {
463         return error;
464     }
465
466     nsm = (struct nicira_stats_msg *) oh;
467     return ofputil_lookup_openflow_message(&nxst_request_category,
468                                            ntohl(nsm->subtype),
469                                            ntohs(oh->length), typep);
470 }
471
472 static int
473 ofputil_decode_nxst_reply(const struct ofp_header *oh,
474                           const struct ofputil_msg_type **typep)
475 {
476     static const struct ofputil_msg_type nxst_replies[] = {
477         { OFPUTIL_NXST_FLOW_REPLY,
478           NXST_FLOW, "NXST_FLOW reply",
479           sizeof(struct nicira_stats_msg), 8 },
480
481         { OFPUTIL_NXST_AGGREGATE_REPLY,
482           NXST_AGGREGATE, "NXST_AGGREGATE reply",
483           sizeof(struct nx_aggregate_stats_reply), 0 },
484     };
485
486     static const struct ofputil_msg_category nxst_reply_category = {
487         "Nicira extension statistics reply",
488         nxst_replies, ARRAY_SIZE(nxst_replies),
489         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE)
490     };
491
492     const struct nicira_stats_msg *nsm;
493     int error;
494
495     error = check_nxstats_msg(oh);
496     if (error) {
497         return error;
498     }
499
500     nsm = (struct nicira_stats_msg *) oh;
501     return ofputil_lookup_openflow_message(&nxst_reply_category,
502                                            ntohl(nsm->subtype),
503                                            ntohs(oh->length), typep);
504 }
505
506 static int
507 ofputil_decode_ofpst_request(const struct ofp_header *oh,
508                              const struct ofputil_msg_type **typep)
509 {
510     enum { OSR_SIZE = sizeof(struct ofp_stats_request) };
511     static const struct ofputil_msg_type ofpst_requests[] = {
512         { OFPUTIL_OFPST_DESC_REQUEST,
513           OFPST_DESC, "OFPST_DESC request",
514           OSR_SIZE, 0 },
515
516         { OFPUTIL_OFPST_FLOW_REQUEST,
517           OFPST_FLOW, "OFPST_FLOW request",
518           OSR_SIZE + sizeof(struct ofp_flow_stats_request), 0 },
519
520         { OFPUTIL_OFPST_AGGREGATE_REQUEST,
521           OFPST_AGGREGATE, "OFPST_AGGREGATE request",
522           OSR_SIZE + sizeof(struct ofp_aggregate_stats_request), 0 },
523
524         { OFPUTIL_OFPST_TABLE_REQUEST,
525           OFPST_TABLE, "OFPST_TABLE request",
526           OSR_SIZE, 0 },
527
528         { OFPUTIL_OFPST_PORT_REQUEST,
529           OFPST_PORT, "OFPST_PORT request",
530           OSR_SIZE + sizeof(struct ofp_port_stats_request), 0 },
531
532         { OFPUTIL_OFPST_QUEUE_REQUEST,
533           OFPST_QUEUE, "OFPST_QUEUE request",
534           OSR_SIZE + sizeof(struct ofp_queue_stats_request), 0 },
535
536         { 0,
537           OFPST_VENDOR, "OFPST_VENDOR request",
538           OSR_SIZE + sizeof(uint32_t), 1 },
539     };
540
541     static const struct ofputil_msg_category ofpst_request_category = {
542         "OpenFlow statistics",
543         ofpst_requests, ARRAY_SIZE(ofpst_requests),
544         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT)
545     };
546
547     const struct ofp_stats_request *osr;
548     int error;
549
550     osr = (const struct ofp_stats_request *) oh;
551     error = ofputil_lookup_openflow_message(&ofpst_request_category,
552                                             ntohs(osr->type),
553                                             ntohs(oh->length), typep);
554     if (!error && osr->type == htons(OFPST_VENDOR)) {
555         error = ofputil_decode_nxst_request(oh, typep);
556     }
557     return error;
558 }
559
560 static int
561 ofputil_decode_ofpst_reply(const struct ofp_header *oh,
562                            const struct ofputil_msg_type **typep)
563 {
564     enum { OSR_SIZE = sizeof(struct ofp_stats_reply) };
565     static const struct ofputil_msg_type ofpst_replies[] = {
566         { OFPUTIL_OFPST_DESC_REPLY,
567           OFPST_DESC, "OFPST_DESC reply",
568           OSR_SIZE + sizeof(struct ofp_desc_stats), 0 },
569
570         { OFPUTIL_OFPST_FLOW_REPLY,
571           OFPST_FLOW, "OFPST_FLOW reply",
572           OSR_SIZE, 1 },
573
574         { OFPUTIL_OFPST_AGGREGATE_REPLY,
575           OFPST_AGGREGATE, "OFPST_AGGREGATE reply",
576           OSR_SIZE + sizeof(struct ofp_aggregate_stats_reply), 0 },
577
578         { OFPUTIL_OFPST_TABLE_REPLY,
579           OFPST_TABLE, "OFPST_TABLE reply",
580           OSR_SIZE, sizeof(struct ofp_table_stats) },
581
582         { OFPUTIL_OFPST_PORT_REPLY,
583           OFPST_PORT, "OFPST_PORT reply",
584           OSR_SIZE, sizeof(struct ofp_port_stats) },
585
586         { OFPUTIL_OFPST_QUEUE_REPLY,
587           OFPST_QUEUE, "OFPST_QUEUE reply",
588           OSR_SIZE, sizeof(struct ofp_queue_stats) },
589
590         { 0,
591           OFPST_VENDOR, "OFPST_VENDOR reply",
592           OSR_SIZE + sizeof(uint32_t), 1 },
593     };
594
595     static const struct ofputil_msg_category ofpst_reply_category = {
596         "OpenFlow statistics",
597         ofpst_replies, ARRAY_SIZE(ofpst_replies),
598         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT)
599     };
600
601     const struct ofp_stats_reply *osr = (const struct ofp_stats_reply *) oh;
602     int error;
603
604     error = ofputil_lookup_openflow_message(&ofpst_reply_category,
605                                            ntohs(osr->type),
606                                            ntohs(oh->length), typep);
607     if (!error && osr->type == htons(OFPST_VENDOR)) {
608         error = ofputil_decode_nxst_reply(oh, typep);
609     }
610     return error;
611 }
612
613 /* Decodes the message type represented by 'oh'.  Returns 0 if successful or
614  * an OpenFlow error code constructed with ofp_mkerr() on failure.  Either
615  * way, stores in '*typep' a type structure that can be inspected with the
616  * ofputil_msg_type_*() functions.
617  *
618  * oh->length must indicate the correct length of the message (and must be at
619  * least sizeof(struct ofp_header)).
620  *
621  * Success indicates that 'oh' is at least as long as the minimum-length
622  * message of its type. */
623 int
624 ofputil_decode_msg_type(const struct ofp_header *oh,
625                         const struct ofputil_msg_type **typep)
626 {
627     static const struct ofputil_msg_type ofpt_messages[] = {
628         { OFPUTIL_OFPT_HELLO,
629           OFPT_HELLO, "OFPT_HELLO",
630           sizeof(struct ofp_hello), 1 },
631
632         { OFPUTIL_OFPT_ERROR,
633           OFPT_ERROR, "OFPT_ERROR",
634           sizeof(struct ofp_error_msg), 1 },
635
636         { OFPUTIL_OFPT_ECHO_REQUEST,
637           OFPT_ECHO_REQUEST, "OFPT_ECHO_REQUEST",
638           sizeof(struct ofp_header), 1 },
639
640         { OFPUTIL_OFPT_ECHO_REPLY,
641           OFPT_ECHO_REPLY, "OFPT_ECHO_REPLY",
642           sizeof(struct ofp_header), 1 },
643
644         { OFPUTIL_OFPT_FEATURES_REQUEST,
645           OFPT_FEATURES_REQUEST, "OFPT_FEATURES_REQUEST",
646           sizeof(struct ofp_header), 0 },
647
648         { OFPUTIL_OFPT_FEATURES_REPLY,
649           OFPT_FEATURES_REPLY, "OFPT_FEATURES_REPLY",
650           sizeof(struct ofp_switch_features), sizeof(struct ofp_phy_port) },
651
652         { OFPUTIL_OFPT_GET_CONFIG_REQUEST,
653           OFPT_GET_CONFIG_REQUEST, "OFPT_GET_CONFIG_REQUEST",
654           sizeof(struct ofp_header), 0 },
655
656         { OFPUTIL_OFPT_GET_CONFIG_REPLY,
657           OFPT_GET_CONFIG_REPLY, "OFPT_GET_CONFIG_REPLY",
658           sizeof(struct ofp_switch_config), 0 },
659
660         { OFPUTIL_OFPT_SET_CONFIG,
661           OFPT_SET_CONFIG, "OFPT_SET_CONFIG",
662           sizeof(struct ofp_switch_config), 0 },
663
664         { OFPUTIL_OFPT_PACKET_IN,
665           OFPT_PACKET_IN, "OFPT_PACKET_IN",
666           offsetof(struct ofp_packet_in, data), 1 },
667
668         { OFPUTIL_OFPT_FLOW_REMOVED,
669           OFPT_FLOW_REMOVED, "OFPT_FLOW_REMOVED",
670           sizeof(struct ofp_flow_removed), 0 },
671
672         { OFPUTIL_OFPT_PORT_STATUS,
673           OFPT_PORT_STATUS, "OFPT_PORT_STATUS",
674           sizeof(struct ofp_port_status), 0 },
675
676         { OFPUTIL_OFPT_PACKET_OUT,
677           OFPT_PACKET_OUT, "OFPT_PACKET_OUT",
678           sizeof(struct ofp_packet_out), 1 },
679
680         { OFPUTIL_OFPT_FLOW_MOD,
681           OFPT_FLOW_MOD, "OFPT_FLOW_MOD",
682           sizeof(struct ofp_flow_mod), 1 },
683
684         { OFPUTIL_OFPT_PORT_MOD,
685           OFPT_PORT_MOD, "OFPT_PORT_MOD",
686           sizeof(struct ofp_port_mod), 0 },
687
688         { 0,
689           OFPT_STATS_REQUEST, "OFPT_STATS_REQUEST",
690           sizeof(struct ofp_stats_request), 1 },
691
692         { 0,
693           OFPT_STATS_REPLY, "OFPT_STATS_REPLY",
694           sizeof(struct ofp_stats_reply), 1 },
695
696         { OFPUTIL_OFPT_BARRIER_REQUEST,
697           OFPT_BARRIER_REQUEST, "OFPT_BARRIER_REQUEST",
698           sizeof(struct ofp_header), 0 },
699
700         { OFPUTIL_OFPT_BARRIER_REPLY,
701           OFPT_BARRIER_REPLY, "OFPT_BARRIER_REPLY",
702           sizeof(struct ofp_header), 0 },
703
704         { 0,
705           OFPT_VENDOR, "OFPT_VENDOR",
706           sizeof(struct ofp_vendor_header), 1 },
707     };
708
709     static const struct ofputil_msg_category ofpt_category = {
710         "OpenFlow message",
711         ofpt_messages, ARRAY_SIZE(ofpt_messages),
712         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE)
713     };
714
715     int error;
716
717     error = ofputil_lookup_openflow_message(&ofpt_category, oh->type,
718                                             ntohs(oh->length), typep);
719     if (!error) {
720         switch (oh->type) {
721         case OFPT_VENDOR:
722             error = ofputil_decode_vendor(oh, typep);
723             break;
724
725         case OFPT_STATS_REQUEST:
726             error = ofputil_decode_ofpst_request(oh, typep);
727             break;
728
729         case OFPT_STATS_REPLY:
730             error = ofputil_decode_ofpst_reply(oh, typep);
731
732         default:
733             break;
734         }
735     }
736     if (error) {
737         static const struct ofputil_msg_type ofputil_invalid_type = {
738             OFPUTIL_INVALID,
739             0, "OFPUTIL_INVALID",
740             0, 0
741         };
742
743         *typep = &ofputil_invalid_type;
744     }
745     return error;
746 }
747
748 /* Returns an OFPUTIL_* message type code for 'type'. */
749 enum ofputil_msg_code
750 ofputil_msg_type_code(const struct ofputil_msg_type *type)
751 {
752     return type->code;
753 }
754 \f
755 /* Flow formats. */
756
757 bool
758 ofputil_flow_format_is_valid(enum nx_flow_format flow_format)
759 {
760     switch (flow_format) {
761     case NXFF_OPENFLOW10:
762     case NXFF_NXM:
763         return true;
764     }
765
766     return false;
767 }
768
769 const char *
770 ofputil_flow_format_to_string(enum nx_flow_format flow_format)
771 {
772     switch (flow_format) {
773     case NXFF_OPENFLOW10:
774         return "openflow10";
775     case NXFF_NXM:
776         return "nxm";
777     default:
778         NOT_REACHED();
779     }
780 }
781
782 int
783 ofputil_flow_format_from_string(const char *s)
784 {
785     return (!strcmp(s, "openflow10") ? NXFF_OPENFLOW10
786             : !strcmp(s, "nxm") ? NXFF_NXM
787             : -1);
788 }
789
790 static bool
791 regs_fully_wildcarded(const struct flow_wildcards *wc)
792 {
793     int i;
794
795     for (i = 0; i < FLOW_N_REGS; i++) {
796         if (wc->reg_masks[i] != 0) {
797             return false;
798         }
799     }
800     return true;
801 }
802
803 /* Returns the minimum nx_flow_format to use for sending 'rule' to a switch
804  * (e.g. to add or remove a flow).  Only NXM can handle tunnel IDs, registers,
805  * or fixing the Ethernet multicast bit.  Otherwise, it's better to use
806  * NXFF_OPENFLOW10 for backward compatibility. */
807 enum nx_flow_format
808 ofputil_min_flow_format(const struct cls_rule *rule)
809 {
810     const struct flow_wildcards *wc = &rule->wc;
811
812     /* Only NXM supports separately wildcards the Ethernet multicast bit. */
813     if (!(wc->wildcards & FWW_DL_DST) != !(wc->wildcards & FWW_ETH_MCAST)) {
814         return NXFF_NXM;
815     }
816
817     /* Only NXM supports matching ARP hardware addresses. */
818     if (!(wc->wildcards & FWW_ARP_SHA) || !(wc->wildcards & FWW_ARP_THA)) {
819         return NXFF_NXM;
820     }
821
822     /* Only NXM supports matching IPv6 traffic. */
823     if (!(wc->wildcards & FWW_DL_TYPE)
824             && (rule->flow.dl_type == htons(ETH_TYPE_IPV6))) {
825         return NXFF_NXM;
826     }
827
828     /* Only NXM supports matching registers. */
829     if (!regs_fully_wildcarded(wc)) {
830         return NXFF_NXM;
831     }
832
833     /* Only NXM supports matching tun_id. */
834     if (wc->tun_id_mask != htonll(0)) {
835         return NXFF_NXM;
836     }
837
838     /* Other formats can express this rule. */
839     return NXFF_OPENFLOW10;
840 }
841
842 /* Returns an OpenFlow message that can be used to set the flow format to
843  * 'flow_format'.  */
844 struct ofpbuf *
845 ofputil_make_set_flow_format(enum nx_flow_format flow_format)
846 {
847     struct nxt_set_flow_format *sff;
848     struct ofpbuf *msg;
849
850     sff = make_nxmsg(sizeof *sff, NXT_SET_FLOW_FORMAT, &msg);
851     sff->format = htonl(flow_format);
852
853     return msg;
854 }
855
856 /* Converts an OFPT_FLOW_MOD or NXT_FLOW_MOD message 'oh' into an abstract
857  * flow_mod in 'fm'.  Returns 0 if successful, otherwise an OpenFlow error
858  * code.
859  *
860  * Does not validate the flow_mod actions. */
861 int
862 ofputil_decode_flow_mod(struct flow_mod *fm, const struct ofp_header *oh)
863 {
864     const struct ofputil_msg_type *type;
865     struct ofpbuf b;
866
867     ofpbuf_use_const(&b, oh, ntohs(oh->length));
868
869     ofputil_decode_msg_type(oh, &type);
870     if (ofputil_msg_type_code(type) == OFPUTIL_OFPT_FLOW_MOD) {
871         /* Standard OpenFlow flow_mod. */
872         const struct ofp_flow_mod *ofm;
873         uint16_t priority;
874         ovs_be32 wc;
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          * normalize_wildcards() 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         /* Normalize ofm->match.  If normalization actually changes anything,
894          * then log the differences. */
895         wc = normalize_wildcards(&ofm->match);
896         if (wc == ofm->match.wildcards) {
897             ofputil_cls_rule_from_match(&ofm->match, priority, &fm->cr);
898         } else {
899             struct ofp_match match = ofm->match;
900             match.wildcards = wc;
901             ofputil_cls_rule_from_match(&match, priority, &fm->cr);
902
903             if (!VLOG_DROP_INFO(&bad_ofmsg_rl)) {
904                 char *pre = ofp_match_to_string(&ofm->match, 1);
905                 char *post = ofp_match_to_string(&match, 1);
906                 VLOG_INFO("normalization changed ofp_match, details:");
907                 VLOG_INFO(" pre: %s", pre);
908                 VLOG_INFO("post: %s", post);
909                 free(pre);
910                 free(post);
911             }
912         }
913
914         /* Translate the message. */
915         fm->cookie = ofm->cookie;
916         fm->command = ntohs(ofm->command);
917         fm->idle_timeout = ntohs(ofm->idle_timeout);
918         fm->hard_timeout = ntohs(ofm->hard_timeout);
919         fm->buffer_id = ntohl(ofm->buffer_id);
920         fm->out_port = ntohs(ofm->out_port);
921         fm->flags = ntohs(ofm->flags);
922     } else if (ofputil_msg_type_code(type) == OFPUTIL_NXT_FLOW_MOD) {
923         /* Nicira extended flow_mod. */
924         const struct nx_flow_mod *nfm;
925         int error;
926
927         /* Dissect the message. */
928         nfm = ofpbuf_pull(&b, sizeof *nfm);
929         error = nx_pull_match(&b, ntohs(nfm->match_len), ntohs(nfm->priority),
930                               &fm->cr);
931         if (error) {
932             return error;
933         }
934         error = ofputil_pull_actions(&b, b.size, &fm->actions, &fm->n_actions);
935         if (error) {
936             return error;
937         }
938
939         /* Translate the message. */
940         fm->cookie = nfm->cookie;
941         fm->command = ntohs(nfm->command);
942         fm->idle_timeout = ntohs(nfm->idle_timeout);
943         fm->hard_timeout = ntohs(nfm->hard_timeout);
944         fm->buffer_id = ntohl(nfm->buffer_id);
945         fm->out_port = ntohs(nfm->out_port);
946         fm->flags = ntohs(nfm->flags);
947     } else {
948         NOT_REACHED();
949     }
950
951     return 0;
952 }
953
954 /* Converts 'fm' into an OFPT_FLOW_MOD or NXT_FLOW_MOD message according to
955  * 'flow_format' and returns the message. */
956 struct ofpbuf *
957 ofputil_encode_flow_mod(const struct flow_mod *fm,
958                         enum nx_flow_format flow_format)
959 {
960     size_t actions_len = fm->n_actions * sizeof *fm->actions;
961     struct ofpbuf *msg;
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(fm->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(fm->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 flow_stats_request *fsr,
1006                                   const struct ofp_header *oh,
1007                                   bool aggregate)
1008 {
1009     const struct ofp_flow_stats_request *ofsr = ofputil_stats_body(oh);
1010
1011     fsr->aggregate = aggregate;
1012     ofputil_cls_rule_from_match(&ofsr->match, 0, &fsr->match);
1013     fsr->out_port = ntohs(ofsr->out_port);
1014     fsr->table_id = ofsr->table_id;
1015
1016     return 0;
1017 }
1018
1019 static int
1020 ofputil_decode_nxst_flow_request(struct flow_stats_request *fsr,
1021                                  const struct ofp_header *oh,
1022                                  bool aggregate)
1023 {
1024     const struct nx_flow_stats_request *nfsr;
1025     struct ofpbuf b;
1026     int error;
1027
1028     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1029
1030     nfsr = ofpbuf_pull(&b, sizeof *nfsr);
1031     error = nx_pull_match(&b, ntohs(nfsr->match_len), 0, &fsr->match);
1032     if (error) {
1033         return error;
1034     }
1035     if (b.size) {
1036         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1037     }
1038
1039     fsr->aggregate = aggregate;
1040     fsr->out_port = ntohs(nfsr->out_port);
1041     fsr->table_id = nfsr->table_id;
1042
1043     return 0;
1044 }
1045
1046 /* Converts an OFPST_FLOW, OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE
1047  * request 'oh', into an abstract flow_stats_request in 'fsr'.  Returns 0 if
1048  * successful, otherwise an OpenFlow error code. */
1049 int
1050 ofputil_decode_flow_stats_request(struct flow_stats_request *fsr,
1051                                   const struct ofp_header *oh)
1052 {
1053     const struct ofputil_msg_type *type;
1054     struct ofpbuf b;
1055     int code;
1056
1057     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1058
1059     ofputil_decode_msg_type(oh, &type);
1060     code = ofputil_msg_type_code(type);
1061     switch (code) {
1062     case OFPUTIL_OFPST_FLOW_REQUEST:
1063         return ofputil_decode_ofpst_flow_request(fsr, oh, false);
1064
1065     case OFPUTIL_OFPST_AGGREGATE_REQUEST:
1066         return ofputil_decode_ofpst_flow_request(fsr, oh, true);
1067
1068     case OFPUTIL_NXST_FLOW_REQUEST:
1069         return ofputil_decode_nxst_flow_request(fsr, oh, false);
1070
1071     case OFPUTIL_NXST_AGGREGATE_REQUEST:
1072         return ofputil_decode_nxst_flow_request(fsr, oh, true);
1073
1074     default:
1075         /* Hey, the caller lied. */
1076         NOT_REACHED();
1077     }
1078 }
1079
1080 /* Converts abstract flow_stats_request 'fsr' into an OFPST_FLOW,
1081  * OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE request 'oh' according to
1082  * 'flow_format', and returns the message. */
1083 struct ofpbuf *
1084 ofputil_encode_flow_stats_request(const struct flow_stats_request *fsr,
1085                                   enum nx_flow_format flow_format)
1086 {
1087     struct ofpbuf *msg;
1088
1089     if (flow_format == NXFF_OPENFLOW10) {
1090         struct ofp_flow_stats_request *ofsr;
1091         int type;
1092
1093         BUILD_ASSERT_DECL(sizeof(struct ofp_flow_stats_request)
1094                           == sizeof(struct ofp_aggregate_stats_request));
1095
1096         type = fsr->aggregate ? OFPST_AGGREGATE : OFPST_FLOW;
1097         ofsr = ofputil_make_stats_request(sizeof *ofsr, type, &msg);
1098         ofputil_cls_rule_to_match(&fsr->match, &ofsr->match);
1099         ofsr->table_id = fsr->table_id;
1100         ofsr->out_port = htons(fsr->out_port);
1101     } else if (flow_format == NXFF_NXM) {
1102         struct nx_flow_stats_request *nfsr;
1103         int match_len;
1104         int subtype;
1105
1106         subtype = fsr->aggregate ? NXST_AGGREGATE : NXST_FLOW;
1107         ofputil_make_nxstats_request(sizeof *nfsr, subtype, &msg);
1108         match_len = nx_put_match(msg, &fsr->match);
1109
1110         nfsr = msg->data;
1111         nfsr->out_port = htons(fsr->out_port);
1112         nfsr->match_len = htons(match_len);
1113         nfsr->table_id = fsr->table_id;
1114     } else {
1115         NOT_REACHED();
1116     }
1117
1118     return msg;
1119 }
1120
1121 /* Converts an OFPST_FLOW or NXST_FLOW reply in 'msg' into an abstract
1122  * ofputil_flow_stats in 'fs'.
1123  *
1124  * Multiple OFPST_FLOW or NXST_FLOW replies can be packed into a single
1125  * OpenFlow message.  Calling this function multiple times for a single 'msg'
1126  * iterates through the replies.  The caller must initially leave 'msg''s layer
1127  * pointers null and not modify them between calls.
1128  *
1129  * Returns 0 if successful, EOF if no replies were left in this 'msg',
1130  * otherwise a positive errno value. */
1131 int
1132 ofputil_decode_flow_stats_reply(struct ofputil_flow_stats *fs,
1133                                 struct ofpbuf *msg)
1134 {
1135     const struct ofputil_msg_type *type;
1136     int code;
1137
1138     ofputil_decode_msg_type(msg->l2 ? msg->l2 : msg->data, &type);
1139     code = ofputil_msg_type_code(type);
1140     if (!msg->l2) {
1141         msg->l2 = msg->data;
1142         if (code == OFPUTIL_OFPST_FLOW_REPLY) {
1143             ofpbuf_pull(msg, sizeof(struct ofp_stats_reply));
1144         } else if (code == OFPUTIL_NXST_FLOW_REPLY) {
1145             ofpbuf_pull(msg, sizeof(struct nicira_stats_msg));
1146         } else {
1147             NOT_REACHED();
1148         }
1149     }
1150
1151     if (!msg->size) {
1152         return EOF;
1153     } else if (code == OFPUTIL_OFPST_FLOW_REPLY) {
1154         const struct ofp_flow_stats *ofs;
1155         size_t length;
1156
1157         ofs = ofpbuf_try_pull(msg, sizeof *ofs);
1158         if (!ofs) {
1159             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply has %zu leftover "
1160                          "bytes at end", msg->size);
1161             return EINVAL;
1162         }
1163
1164         length = ntohs(ofs->length);
1165         if (length < sizeof *ofs) {
1166             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply claims invalid "
1167                          "length %zu", length);
1168             return EINVAL;
1169         }
1170
1171         if (ofputil_pull_actions(msg, length - sizeof *ofs,
1172                                  &fs->actions, &fs->n_actions)) {
1173             return EINVAL;
1174         }
1175
1176         fs->cookie = get_32aligned_be64(&ofs->cookie);
1177         ofputil_cls_rule_from_match(&ofs->match, ntohs(ofs->priority),
1178                                     &fs->rule);
1179         fs->table_id = ofs->table_id;
1180         fs->duration_sec = ntohl(ofs->duration_sec);
1181         fs->duration_nsec = ntohl(ofs->duration_nsec);
1182         fs->idle_timeout = ntohs(ofs->idle_timeout);
1183         fs->hard_timeout = ntohs(ofs->hard_timeout);
1184         fs->packet_count = ntohll(get_32aligned_be64(&ofs->packet_count));
1185         fs->byte_count = ntohll(get_32aligned_be64(&ofs->byte_count));
1186     } else if (code == OFPUTIL_NXST_FLOW_REPLY) {
1187         const struct nx_flow_stats *nfs;
1188         size_t match_len, length;
1189
1190         nfs = ofpbuf_try_pull(msg, sizeof *nfs);
1191         if (!nfs) {
1192             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply has %zu leftover "
1193                          "bytes at end", msg->size);
1194             return EINVAL;
1195         }
1196
1197         length = ntohs(nfs->length);
1198         match_len = ntohs(nfs->match_len);
1199         if (length < sizeof *nfs + ROUND_UP(match_len, 8)) {
1200             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply with match_len=%zu "
1201                          "claims invalid length %zu", match_len, length);
1202             return EINVAL;
1203         }
1204         if (nx_pull_match(msg, match_len, ntohs(nfs->priority), &fs->rule)) {
1205             return EINVAL;
1206         }
1207
1208         if (ofputil_pull_actions(msg,
1209                                  length - sizeof *nfs - ROUND_UP(match_len, 8),
1210                                  &fs->actions, &fs->n_actions)) {
1211             return EINVAL;
1212         }
1213
1214         fs->cookie = nfs->cookie;
1215         fs->table_id = nfs->table_id;
1216         fs->duration_sec = ntohl(nfs->duration_sec);
1217         fs->duration_nsec = ntohl(nfs->duration_nsec);
1218         fs->idle_timeout = ntohs(nfs->idle_timeout);
1219         fs->hard_timeout = ntohs(nfs->hard_timeout);
1220         fs->packet_count = ntohll(nfs->packet_count);
1221         fs->byte_count = ntohll(nfs->byte_count);
1222     } else {
1223         NOT_REACHED();
1224     }
1225
1226     return 0;
1227 }
1228
1229 /* Converts an OFPT_FLOW_REMOVED or NXT_FLOW_REMOVED message 'oh' into an
1230  * abstract ofputil_flow_removed in 'fr'.  Returns 0 if successful, otherwise
1231  * an OpenFlow error code. */
1232 int
1233 ofputil_decode_flow_removed(struct ofputil_flow_removed *fr,
1234                             const struct ofp_header *oh)
1235 {
1236     const struct ofputil_msg_type *type;
1237     enum ofputil_msg_code code;
1238
1239     ofputil_decode_msg_type(oh, &type);
1240     code = ofputil_msg_type_code(type);
1241     if (code == OFPUTIL_OFPT_FLOW_REMOVED) {
1242         const struct ofp_flow_removed *ofr;
1243
1244         ofr = (const struct ofp_flow_removed *) oh;
1245         ofputil_cls_rule_from_match(&ofr->match, ntohs(ofr->priority),
1246                                     &fr->rule);
1247         fr->cookie = ofr->cookie;
1248         fr->reason = ofr->reason;
1249         fr->duration_sec = ntohl(ofr->duration_sec);
1250         fr->duration_nsec = ntohl(ofr->duration_nsec);
1251         fr->idle_timeout = ntohs(ofr->idle_timeout);
1252         fr->packet_count = ntohll(ofr->packet_count);
1253         fr->byte_count = ntohll(ofr->byte_count);
1254     } else if (code == OFPUTIL_NXT_FLOW_REMOVED) {
1255         struct nx_flow_removed *nfr;
1256         struct ofpbuf b;
1257         int error;
1258
1259         ofpbuf_use_const(&b, oh, ntohs(oh->length));
1260
1261         nfr = ofpbuf_pull(&b, sizeof *nfr);
1262         error = nx_pull_match(&b, ntohs(nfr->match_len), ntohs(nfr->priority),
1263                               &fr->rule);
1264         if (error) {
1265             return error;
1266         }
1267         if (b.size) {
1268             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1269         }
1270
1271         fr->cookie = nfr->cookie;
1272         fr->reason = nfr->reason;
1273         fr->duration_sec = ntohl(nfr->duration_sec);
1274         fr->duration_nsec = ntohl(nfr->duration_nsec);
1275         fr->idle_timeout = ntohs(nfr->idle_timeout);
1276         fr->packet_count = ntohll(nfr->packet_count);
1277         fr->byte_count = ntohll(nfr->byte_count);
1278     } else {
1279         NOT_REACHED();
1280     }
1281
1282     return 0;
1283 }
1284
1285 /* Converts abstract ofputil_flow_removed 'fr' into an OFPT_FLOW_REMOVED or
1286  * NXT_FLOW_REMOVED message 'oh' according to 'flow_format', and returns the
1287  * message. */
1288 struct ofpbuf *
1289 ofputil_encode_flow_removed(const struct ofputil_flow_removed *fr,
1290                             enum nx_flow_format flow_format)
1291 {
1292     struct ofpbuf *msg;
1293
1294     if (flow_format == NXFF_OPENFLOW10) {
1295         struct ofp_flow_removed *ofr;
1296
1297         ofr = make_openflow_xid(sizeof *ofr, OFPT_FLOW_REMOVED, htonl(0),
1298                                 &msg);
1299         ofputil_cls_rule_to_match(&fr->rule, &ofr->match);
1300         ofr->priority = htons(fr->rule.priority);
1301         ofr->reason = fr->reason;
1302         ofr->duration_sec = htonl(fr->duration_sec);
1303         ofr->duration_nsec = htonl(fr->duration_nsec);
1304         ofr->idle_timeout = htons(fr->idle_timeout);
1305         ofr->packet_count = htonll(fr->packet_count);
1306         ofr->byte_count = htonll(fr->byte_count);
1307     } else if (flow_format == NXFF_NXM) {
1308         struct nx_flow_removed *nfr;
1309         int match_len;
1310
1311         make_nxmsg_xid(sizeof *nfr, NXT_FLOW_REMOVED, htonl(0), &msg);
1312         match_len = nx_put_match(msg, &fr->rule);
1313
1314         nfr = msg->data;
1315         nfr->cookie = fr->cookie;
1316         nfr->priority = htons(fr->rule.priority);
1317         nfr->reason = fr->reason;
1318         nfr->duration_sec = htonl(fr->duration_sec);
1319         nfr->duration_nsec = htonl(fr->duration_nsec);
1320         nfr->idle_timeout = htons(fr->idle_timeout);
1321         nfr->match_len = htons(match_len);
1322         nfr->packet_count = htonll(fr->packet_count);
1323         nfr->byte_count = htonll(fr->byte_count);
1324     } else {
1325         NOT_REACHED();
1326     }
1327
1328     return msg;
1329 }
1330
1331 /* Converts abstract ofputil_packet_in 'pin' into an OFPT_PACKET_IN message
1332  * and returns the message.
1333  *
1334  * If 'rw_packet' is NULL, the caller takes ownership of the newly allocated
1335  * returned ofpbuf.
1336  *
1337  * If 'rw_packet' is nonnull, then it must contain the same data as
1338  * pin->packet.  'rw_packet' is allowed to be the same ofpbuf as pin->packet.
1339  * It is modified in-place into an OFPT_PACKET_IN message according to 'pin',
1340  * and then ofputil_encode_packet_in() returns 'rw_packet'.  If 'rw_packet' has
1341  * enough headroom to insert a "struct ofp_packet_in", this is more efficient
1342  * than ofputil_encode_packet_in() because it does not copy the packet
1343  * payload. */
1344 struct ofpbuf *
1345 ofputil_encode_packet_in(const struct ofputil_packet_in *pin,
1346                         struct ofpbuf *rw_packet)
1347 {
1348     int total_len = pin->packet->size;
1349     struct ofp_packet_in *opi;
1350
1351     if (rw_packet) {
1352         if (pin->send_len < rw_packet->size) {
1353             rw_packet->size = pin->send_len;
1354         }
1355     } else {
1356         rw_packet = ofpbuf_clone_data_with_headroom(
1357             pin->packet->data, MIN(pin->send_len, pin->packet->size),
1358             offsetof(struct ofp_packet_in, data));
1359     }
1360
1361     /* Add OFPT_PACKET_IN. */
1362     opi = ofpbuf_push_zeros(rw_packet, offsetof(struct ofp_packet_in, data));
1363     opi->header.version = OFP_VERSION;
1364     opi->header.type = OFPT_PACKET_IN;
1365     opi->total_len = htons(total_len);
1366     opi->in_port = htons(pin->in_port);
1367     opi->reason = pin->reason;
1368     opi->buffer_id = htonl(pin->buffer_id);
1369     update_openflow_length(rw_packet);
1370
1371     return rw_packet;
1372 }
1373
1374 /* Returns a string representing the message type of 'type'.  The string is the
1375  * enumeration constant for the type, e.g. "OFPT_HELLO".  For statistics
1376  * messages, the constant is followed by "request" or "reply",
1377  * e.g. "OFPST_AGGREGATE reply". */
1378 const char *
1379 ofputil_msg_type_name(const struct ofputil_msg_type *type)
1380 {
1381     return type->name;
1382 }
1383 \f
1384 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
1385  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
1386  * an arbitrary transaction id.  Allocated bytes beyond the header, if any, are
1387  * zeroed.
1388  *
1389  * The caller is responsible for freeing '*bufferp' when it is no longer
1390  * needed.
1391  *
1392  * The OpenFlow header length is initially set to 'openflow_len'; if the
1393  * message is later extended, the length should be updated with
1394  * update_openflow_length() before sending.
1395  *
1396  * Returns the header. */
1397 void *
1398 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp)
1399 {
1400     *bufferp = ofpbuf_new(openflow_len);
1401     return put_openflow_xid(openflow_len, type, alloc_xid(), *bufferp);
1402 }
1403
1404 /* Similar to make_openflow() but creates a Nicira vendor extension message
1405  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1406 void *
1407 make_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf **bufferp)
1408 {
1409     return make_nxmsg_xid(openflow_len, subtype, alloc_xid(), bufferp);
1410 }
1411
1412 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
1413  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
1414  * transaction id 'xid'.  Allocated bytes beyond the header, if any, are
1415  * zeroed.
1416  *
1417  * The caller is responsible for freeing '*bufferp' when it is no longer
1418  * needed.
1419  *
1420  * The OpenFlow header length is initially set to 'openflow_len'; if the
1421  * message is later extended, the length should be updated with
1422  * update_openflow_length() before sending.
1423  *
1424  * Returns the header. */
1425 void *
1426 make_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
1427                   struct ofpbuf **bufferp)
1428 {
1429     *bufferp = ofpbuf_new(openflow_len);
1430     return put_openflow_xid(openflow_len, type, xid, *bufferp);
1431 }
1432
1433 /* Similar to make_openflow_xid() but creates a Nicira vendor extension message
1434  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1435 void *
1436 make_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
1437                struct ofpbuf **bufferp)
1438 {
1439     *bufferp = ofpbuf_new(openflow_len);
1440     return put_nxmsg_xid(openflow_len, subtype, xid, *bufferp);
1441 }
1442
1443 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
1444  * with the given 'type' and an arbitrary transaction id.  Allocated bytes
1445  * beyond the header, if any, are zeroed.
1446  *
1447  * The OpenFlow header length is initially set to 'openflow_len'; if the
1448  * message is later extended, the length should be updated with
1449  * update_openflow_length() before sending.
1450  *
1451  * Returns the header. */
1452 void *
1453 put_openflow(size_t openflow_len, uint8_t type, struct ofpbuf *buffer)
1454 {
1455     return put_openflow_xid(openflow_len, type, alloc_xid(), buffer);
1456 }
1457
1458 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
1459  * with the given 'type' and an transaction id 'xid'.  Allocated bytes beyond
1460  * the header, if any, are zeroed.
1461  *
1462  * The OpenFlow header length is initially set to 'openflow_len'; if the
1463  * message is later extended, the length should be updated with
1464  * update_openflow_length() before sending.
1465  *
1466  * Returns the header. */
1467 void *
1468 put_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
1469                  struct ofpbuf *buffer)
1470 {
1471     struct ofp_header *oh;
1472
1473     assert(openflow_len >= sizeof *oh);
1474     assert(openflow_len <= UINT16_MAX);
1475
1476     oh = ofpbuf_put_uninit(buffer, openflow_len);
1477     oh->version = OFP_VERSION;
1478     oh->type = type;
1479     oh->length = htons(openflow_len);
1480     oh->xid = xid;
1481     memset(oh + 1, 0, openflow_len - sizeof *oh);
1482     return oh;
1483 }
1484
1485 /* Similar to put_openflow() but append a Nicira vendor extension message with
1486  * the specific 'subtype'.  'subtype' should be in host byte order. */
1487 void *
1488 put_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf *buffer)
1489 {
1490     return put_nxmsg_xid(openflow_len, subtype, alloc_xid(), buffer);
1491 }
1492
1493 /* Similar to put_openflow_xid() but append a Nicira vendor extension message
1494  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1495 void *
1496 put_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
1497               struct ofpbuf *buffer)
1498 {
1499     struct nicira_header *nxh;
1500
1501     nxh = put_openflow_xid(openflow_len, OFPT_VENDOR, xid, buffer);
1502     nxh->vendor = htonl(NX_VENDOR_ID);
1503     nxh->subtype = htonl(subtype);
1504     return nxh;
1505 }
1506
1507 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
1508  * 'buffer->size'. */
1509 void
1510 update_openflow_length(struct ofpbuf *buffer)
1511 {
1512     struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
1513     oh->length = htons(buffer->size);
1514 }
1515
1516 /* Creates an ofp_stats_request with the given 'type' and 'body_len' bytes of
1517  * space allocated for the 'body' member.  Returns the first byte of the 'body'
1518  * member. */
1519 void *
1520 ofputil_make_stats_request(size_t body_len, uint16_t type,
1521                            struct ofpbuf **bufferp)
1522 {
1523     struct ofp_stats_request *osr;
1524     osr = make_openflow((offsetof(struct ofp_stats_request, body)
1525                         + body_len), OFPT_STATS_REQUEST, bufferp);
1526     osr->type = htons(type);
1527     osr->flags = htons(0);
1528     return osr->body;
1529 }
1530
1531 /* Creates a stats request message with Nicira as vendor and the given
1532  * 'subtype', of total length 'openflow_len'.  Returns the message. */
1533 void *
1534 ofputil_make_nxstats_request(size_t openflow_len, uint32_t subtype,
1535                              struct ofpbuf **bufferp)
1536 {
1537     struct nicira_stats_msg *nsm;
1538
1539     nsm = make_openflow(openflow_len, OFPT_STATS_REQUEST, bufferp);
1540     nsm->type = htons(OFPST_VENDOR);
1541     nsm->flags = htons(0);
1542     nsm->vendor = htonl(NX_VENDOR_ID);
1543     nsm->subtype = htonl(subtype);
1544     return nsm;
1545 }
1546
1547 /* Returns the first byte of the 'body' member of the ofp_stats_request or
1548  * ofp_stats_reply in 'oh'. */
1549 const void *
1550 ofputil_stats_body(const struct ofp_header *oh)
1551 {
1552     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1553     return ((const struct ofp_stats_request *) oh)->body;
1554 }
1555
1556 /* Returns the length of the 'body' member of the ofp_stats_request or
1557  * ofp_stats_reply in 'oh'. */
1558 size_t
1559 ofputil_stats_body_len(const struct ofp_header *oh)
1560 {
1561     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1562     return ntohs(oh->length) - sizeof(struct ofp_stats_request);
1563 }
1564
1565 /* Returns the first byte of the body of the nicira_stats_msg in 'oh'. */
1566 const void *
1567 ofputil_nxstats_body(const struct ofp_header *oh)
1568 {
1569     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1570     return ((const struct nicira_stats_msg *) oh) + 1;
1571 }
1572
1573 /* Returns the length of the body of the nicira_stats_msg in 'oh'. */
1574 size_t
1575 ofputil_nxstats_body_len(const struct ofp_header *oh)
1576 {
1577     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1578     return ntohs(oh->length) - sizeof(struct nicira_stats_msg);
1579 }
1580
1581 struct ofpbuf *
1582 make_flow_mod(uint16_t command, const struct cls_rule *rule,
1583               size_t actions_len)
1584 {
1585     struct ofp_flow_mod *ofm;
1586     size_t size = sizeof *ofm + actions_len;
1587     struct ofpbuf *out = ofpbuf_new(size);
1588     ofm = ofpbuf_put_zeros(out, sizeof *ofm);
1589     ofm->header.version = OFP_VERSION;
1590     ofm->header.type = OFPT_FLOW_MOD;
1591     ofm->header.length = htons(size);
1592     ofm->cookie = 0;
1593     ofm->priority = htons(MIN(rule->priority, UINT16_MAX));
1594     ofputil_cls_rule_to_match(rule, &ofm->match);
1595     ofm->command = htons(command);
1596     return out;
1597 }
1598
1599 struct ofpbuf *
1600 make_add_flow(const struct cls_rule *rule, uint32_t buffer_id,
1601               uint16_t idle_timeout, size_t actions_len)
1602 {
1603     struct ofpbuf *out = make_flow_mod(OFPFC_ADD, rule, actions_len);
1604     struct ofp_flow_mod *ofm = out->data;
1605     ofm->idle_timeout = htons(idle_timeout);
1606     ofm->hard_timeout = htons(OFP_FLOW_PERMANENT);
1607     ofm->buffer_id = htonl(buffer_id);
1608     return out;
1609 }
1610
1611 struct ofpbuf *
1612 make_del_flow(const struct cls_rule *rule)
1613 {
1614     struct ofpbuf *out = make_flow_mod(OFPFC_DELETE_STRICT, rule, 0);
1615     struct ofp_flow_mod *ofm = out->data;
1616     ofm->out_port = htons(OFPP_NONE);
1617     return out;
1618 }
1619
1620 struct ofpbuf *
1621 make_add_simple_flow(const struct cls_rule *rule,
1622                      uint32_t buffer_id, uint16_t out_port,
1623                      uint16_t idle_timeout)
1624 {
1625     if (out_port != OFPP_NONE) {
1626         struct ofp_action_output *oao;
1627         struct ofpbuf *buffer;
1628
1629         buffer = make_add_flow(rule, buffer_id, idle_timeout, sizeof *oao);
1630         oao = ofpbuf_put_zeros(buffer, sizeof *oao);
1631         oao->type = htons(OFPAT_OUTPUT);
1632         oao->len = htons(sizeof *oao);
1633         oao->port = htons(out_port);
1634         return buffer;
1635     } else {
1636         return make_add_flow(rule, buffer_id, idle_timeout, 0);
1637     }
1638 }
1639
1640 struct ofpbuf *
1641 make_packet_in(uint32_t buffer_id, uint16_t in_port, uint8_t reason,
1642                const struct ofpbuf *payload, int max_send_len)
1643 {
1644     struct ofp_packet_in *opi;
1645     struct ofpbuf *buf;
1646     int send_len;
1647
1648     send_len = MIN(max_send_len, payload->size);
1649     buf = ofpbuf_new(sizeof *opi + send_len);
1650     opi = put_openflow_xid(offsetof(struct ofp_packet_in, data),
1651                            OFPT_PACKET_IN, 0, buf);
1652     opi->buffer_id = htonl(buffer_id);
1653     opi->total_len = htons(payload->size);
1654     opi->in_port = htons(in_port);
1655     opi->reason = reason;
1656     ofpbuf_put(buf, payload->data, send_len);
1657     update_openflow_length(buf);
1658
1659     return buf;
1660 }
1661
1662 struct ofpbuf *
1663 make_packet_out(const struct ofpbuf *packet, uint32_t buffer_id,
1664                 uint16_t in_port,
1665                 const struct ofp_action_header *actions, size_t n_actions)
1666 {
1667     size_t actions_len = n_actions * sizeof *actions;
1668     struct ofp_packet_out *opo;
1669     size_t size = sizeof *opo + actions_len + (packet ? packet->size : 0);
1670     struct ofpbuf *out = ofpbuf_new(size);
1671
1672     opo = ofpbuf_put_uninit(out, sizeof *opo);
1673     opo->header.version = OFP_VERSION;
1674     opo->header.type = OFPT_PACKET_OUT;
1675     opo->header.length = htons(size);
1676     opo->header.xid = htonl(0);
1677     opo->buffer_id = htonl(buffer_id);
1678     opo->in_port = htons(in_port == ODPP_LOCAL ? OFPP_LOCAL : in_port);
1679     opo->actions_len = htons(actions_len);
1680     ofpbuf_put(out, actions, actions_len);
1681     if (packet) {
1682         ofpbuf_put(out, packet->data, packet->size);
1683     }
1684     return out;
1685 }
1686
1687 struct ofpbuf *
1688 make_unbuffered_packet_out(const struct ofpbuf *packet,
1689                            uint16_t in_port, uint16_t out_port)
1690 {
1691     struct ofp_action_output action;
1692     action.type = htons(OFPAT_OUTPUT);
1693     action.len = htons(sizeof action);
1694     action.port = htons(out_port);
1695     return make_packet_out(packet, UINT32_MAX, in_port,
1696                            (struct ofp_action_header *) &action, 1);
1697 }
1698
1699 struct ofpbuf *
1700 make_buffered_packet_out(uint32_t buffer_id,
1701                          uint16_t in_port, uint16_t out_port)
1702 {
1703     if (out_port != OFPP_NONE) {
1704         struct ofp_action_output action;
1705         action.type = htons(OFPAT_OUTPUT);
1706         action.len = htons(sizeof action);
1707         action.port = htons(out_port);
1708         return make_packet_out(NULL, buffer_id, in_port,
1709                                (struct ofp_action_header *) &action, 1);
1710     } else {
1711         return make_packet_out(NULL, buffer_id, in_port, NULL, 0);
1712     }
1713 }
1714
1715 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
1716 struct ofpbuf *
1717 make_echo_request(void)
1718 {
1719     struct ofp_header *rq;
1720     struct ofpbuf *out = ofpbuf_new(sizeof *rq);
1721     rq = ofpbuf_put_uninit(out, sizeof *rq);
1722     rq->version = OFP_VERSION;
1723     rq->type = OFPT_ECHO_REQUEST;
1724     rq->length = htons(sizeof *rq);
1725     rq->xid = htonl(0);
1726     return out;
1727 }
1728
1729 /* Creates and returns an OFPT_ECHO_REPLY message matching the
1730  * OFPT_ECHO_REQUEST message in 'rq'. */
1731 struct ofpbuf *
1732 make_echo_reply(const struct ofp_header *rq)
1733 {
1734     size_t size = ntohs(rq->length);
1735     struct ofpbuf *out = ofpbuf_new(size);
1736     struct ofp_header *reply = ofpbuf_put(out, rq, size);
1737     reply->type = OFPT_ECHO_REPLY;
1738     return out;
1739 }
1740
1741 static int
1742 check_action_exact_len(const union ofp_action *a, unsigned int len,
1743                        unsigned int required_len)
1744 {
1745     if (len != required_len) {
1746         VLOG_WARN_RL(&bad_ofmsg_rl, "action %"PRIu16" has invalid length "
1747                      "%"PRIu16" (must be %u)\n",
1748                      ntohs(a->type), ntohs(a->header.len), required_len);
1749         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1750     }
1751     return 0;
1752 }
1753
1754 static int
1755 check_nx_action_exact_len(const struct nx_action_header *a,
1756                           unsigned int len, unsigned int required_len)
1757 {
1758     if (len != required_len) {
1759         VLOG_WARN_RL(&bad_ofmsg_rl,
1760                      "Nicira action %"PRIu16" has invalid length %"PRIu16" "
1761                      "(must be %u)\n",
1762                      ntohs(a->subtype), ntohs(a->len), required_len);
1763         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1764     }
1765     return 0;
1766 }
1767
1768 /* Checks that 'port' is a valid output port for the OFPAT_OUTPUT action, given
1769  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
1770  * 'port' is valid, otherwise an ofp_mkerr() return code. */
1771 static int
1772 check_output_port(uint16_t port, int max_ports)
1773 {
1774     switch (port) {
1775     case OFPP_IN_PORT:
1776     case OFPP_TABLE:
1777     case OFPP_NORMAL:
1778     case OFPP_FLOOD:
1779     case OFPP_ALL:
1780     case OFPP_CONTROLLER:
1781     case OFPP_LOCAL:
1782         return 0;
1783
1784     default:
1785         if (port < max_ports) {
1786             return 0;
1787         }
1788         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown output port %x", port);
1789         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
1790     }
1791 }
1792
1793 /* Checks that 'action' is a valid OFPAT_ENQUEUE action, given that the switch
1794  * will never have more than 'max_ports' ports.  Returns 0 if 'port' is valid,
1795  * otherwise an ofp_mkerr() return code. */
1796 static int
1797 check_enqueue_action(const union ofp_action *a, unsigned int len,
1798                      int max_ports)
1799 {
1800     const struct ofp_action_enqueue *oae;
1801     uint16_t port;
1802     int error;
1803
1804     error = check_action_exact_len(a, len, 16);
1805     if (error) {
1806         return error;
1807     }
1808
1809     oae = (const struct ofp_action_enqueue *) a;
1810     port = ntohs(oae->port);
1811     if (port < max_ports || port == OFPP_IN_PORT) {
1812         return 0;
1813     }
1814     VLOG_WARN_RL(&bad_ofmsg_rl, "unknown enqueue port %x", port);
1815     return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
1816 }
1817
1818 static int
1819 check_nicira_action(const union ofp_action *a, unsigned int len,
1820                     const struct flow *flow)
1821 {
1822     const struct nx_action_header *nah;
1823     int subtype;
1824     int error;
1825
1826     if (len < 16) {
1827         VLOG_WARN_RL(&bad_ofmsg_rl,
1828                      "Nicira vendor action only %u bytes", len);
1829         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1830     }
1831     nah = (const struct nx_action_header *) a;
1832
1833     subtype = ntohs(nah->subtype);
1834     if (subtype > TYPE_MAXIMUM(enum nx_action_subtype)) {
1835         /* This is necessary because enum nx_action_subtype may be an
1836          * 8-bit type, so the cast below throws away the top 8 bits. */
1837         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR_TYPE);
1838     }
1839
1840     switch ((enum nx_action_subtype) subtype) {
1841     case NXAST_RESUBMIT:
1842     case NXAST_SET_TUNNEL:
1843     case NXAST_DROP_SPOOFED_ARP:
1844     case NXAST_SET_QUEUE:
1845     case NXAST_POP_QUEUE:
1846         return check_nx_action_exact_len(nah, len, 16);
1847
1848     case NXAST_REG_MOVE:
1849         error = check_nx_action_exact_len(nah, len,
1850                                           sizeof(struct nx_action_reg_move));
1851         if (error) {
1852             return error;
1853         }
1854         return nxm_check_reg_move((const struct nx_action_reg_move *) a, flow);
1855
1856     case NXAST_REG_LOAD:
1857         error = check_nx_action_exact_len(nah, len,
1858                                           sizeof(struct nx_action_reg_load));
1859         if (error) {
1860             return error;
1861         }
1862         return nxm_check_reg_load((const struct nx_action_reg_load *) a, flow);
1863
1864     case NXAST_NOTE:
1865         return 0;
1866
1867     case NXAST_SET_TUNNEL64:
1868         return check_nx_action_exact_len(
1869             nah, len, sizeof(struct nx_action_set_tunnel64));
1870
1871     case NXAST_MULTIPATH:
1872         error = check_nx_action_exact_len(
1873             nah, len, sizeof(struct nx_action_multipath));
1874         if (error) {
1875             return error;
1876         }
1877         return multipath_check((const struct nx_action_multipath *) a);
1878
1879     case NXAST_AUTOPATH:
1880         error = check_nx_action_exact_len(
1881             nah, len, sizeof(struct nx_action_autopath));
1882         if (error) {
1883             return error;
1884         }
1885         return autopath_check((const struct nx_action_autopath *) a);
1886
1887     case NXAST_SNAT__OBSOLETE:
1888     default:
1889         VLOG_WARN_RL(&bad_ofmsg_rl,
1890                      "unknown Nicira vendor action subtype %d", subtype);
1891         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR_TYPE);
1892     }
1893 }
1894
1895 static int
1896 check_action(const union ofp_action *a, unsigned int len,
1897              const struct flow *flow, int max_ports)
1898 {
1899     enum ofp_action_type type = ntohs(a->type);
1900     int error;
1901
1902     switch (type) {
1903     case OFPAT_OUTPUT:
1904         error = check_action_exact_len(a, len, 8);
1905         if (error) {
1906             return error;
1907         }
1908         return check_output_port(ntohs(a->output.port), max_ports);
1909
1910     case OFPAT_SET_VLAN_VID:
1911         error = check_action_exact_len(a, len, 8);
1912         if (error) {
1913             return error;
1914         }
1915         if (a->vlan_vid.vlan_vid & ~htons(0xfff)) {
1916             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
1917         }
1918         return 0;
1919
1920     case OFPAT_SET_VLAN_PCP:
1921         error = check_action_exact_len(a, len, 8);
1922         if (error) {
1923             return error;
1924         }
1925         if (a->vlan_pcp.vlan_pcp & ~7) {
1926             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
1927         }
1928         return 0;
1929
1930     case OFPAT_STRIP_VLAN:
1931     case OFPAT_SET_NW_SRC:
1932     case OFPAT_SET_NW_DST:
1933     case OFPAT_SET_NW_TOS:
1934     case OFPAT_SET_TP_SRC:
1935     case OFPAT_SET_TP_DST:
1936         return check_action_exact_len(a, len, 8);
1937
1938     case OFPAT_SET_DL_SRC:
1939     case OFPAT_SET_DL_DST:
1940         return check_action_exact_len(a, len, 16);
1941
1942     case OFPAT_VENDOR:
1943         return (a->vendor.vendor == htonl(NX_VENDOR_ID)
1944                 ? check_nicira_action(a, len, flow)
1945                 : ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR));
1946
1947     case OFPAT_ENQUEUE:
1948         return check_enqueue_action(a, len, max_ports);
1949
1950     default:
1951         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown action type %d", (int) type);
1952         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_TYPE);
1953     }
1954 }
1955
1956 int
1957 validate_actions(const union ofp_action *actions, size_t n_actions,
1958                  const struct flow *flow, int max_ports)
1959 {
1960     size_t i;
1961
1962     for (i = 0; i < n_actions; ) {
1963         const union ofp_action *a = &actions[i];
1964         unsigned int len = ntohs(a->header.len);
1965         unsigned int n_slots = len / OFP_ACTION_ALIGN;
1966         unsigned int slots_left = &actions[n_actions] - a;
1967         int error;
1968
1969         if (n_slots > slots_left) {
1970             VLOG_WARN_RL(&bad_ofmsg_rl,
1971                          "action requires %u slots but only %u remain",
1972                          n_slots, slots_left);
1973             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1974         } else if (!len) {
1975             VLOG_WARN_RL(&bad_ofmsg_rl, "action has invalid length 0");
1976             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1977         } else if (len % OFP_ACTION_ALIGN) {
1978             VLOG_WARN_RL(&bad_ofmsg_rl, "action length %u is not a multiple "
1979                          "of %d", len, OFP_ACTION_ALIGN);
1980             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1981         }
1982
1983         error = check_action(a, len, flow, max_ports);
1984         if (error) {
1985             return error;
1986         }
1987         i += n_slots;
1988     }
1989     return 0;
1990 }
1991
1992 /* Returns true if 'action' outputs to 'port', false otherwise. */
1993 bool
1994 action_outputs_to_port(const union ofp_action *action, ovs_be16 port)
1995 {
1996     switch (ntohs(action->type)) {
1997     case OFPAT_OUTPUT:
1998         return action->output.port == port;
1999     case OFPAT_ENQUEUE:
2000         return ((const struct ofp_action_enqueue *) action)->port == port;
2001     default:
2002         return false;
2003     }
2004 }
2005
2006 /* The set of actions must either come from a trusted source or have been
2007  * previously validated with validate_actions(). */
2008 const union ofp_action *
2009 actions_first(struct actions_iterator *iter,
2010               const union ofp_action *oa, size_t n_actions)
2011 {
2012     iter->pos = oa;
2013     iter->end = oa + n_actions;
2014     return actions_next(iter);
2015 }
2016
2017 const union ofp_action *
2018 actions_next(struct actions_iterator *iter)
2019 {
2020     if (iter->pos != iter->end) {
2021         const union ofp_action *a = iter->pos;
2022         unsigned int len = ntohs(a->header.len);
2023         iter->pos += len / OFP_ACTION_ALIGN;
2024         return a;
2025     } else {
2026         return NULL;
2027     }
2028 }
2029
2030 static ovs_be32
2031 normalize_wildcards(const struct ofp_match *m)
2032 {
2033     enum { OFPFW_NW = (OFPFW_NW_SRC_ALL | OFPFW_NW_DST_ALL | OFPFW_NW_PROTO
2034                        | OFPFW_NW_TOS) };
2035     enum { OFPFW_TP = OFPFW_TP_SRC | OFPFW_TP_DST };
2036     ovs_be32 wc;
2037
2038     wc = m->wildcards;
2039     if (wc & htonl(OFPFW_DL_TYPE)) {
2040         wc |= htonl(OFPFW_NW | OFPFW_TP);
2041     } else if (m->dl_type == htons(ETH_TYPE_IP)) {
2042         if (wc & htonl(OFPFW_NW_PROTO) || (m->nw_proto != IPPROTO_TCP &&
2043                                            m->nw_proto != IPPROTO_UDP &&
2044                                            m->nw_proto != IPPROTO_ICMP)) {
2045             wc |= htonl(OFPFW_TP);
2046         }
2047     } else if (m->dl_type == htons(ETH_TYPE_ARP)) {
2048         wc |= htonl(OFPFW_TP);
2049     } else {
2050         wc |= htonl(OFPFW_NW | OFPFW_TP);
2051     }
2052     return wc;
2053 }
2054
2055 static uint32_t
2056 vendor_code_to_id(uint8_t code)
2057 {
2058     switch (code) {
2059 #define OFPUTIL_VENDOR(NAME, VENDOR_ID) case NAME: return VENDOR_ID;
2060         OFPUTIL_VENDORS
2061 #undef OFPUTIL_VENDOR
2062     default:
2063         return UINT32_MAX;
2064     }
2065 }
2066
2067 static int
2068 vendor_id_to_code(uint32_t id)
2069 {
2070     switch (id) {
2071 #define OFPUTIL_VENDOR(NAME, VENDOR_ID) case VENDOR_ID: return NAME;
2072         OFPUTIL_VENDORS
2073 #undef OFPUTIL_VENDOR
2074     default:
2075         return -1;
2076     }
2077 }
2078
2079 /* Creates and returns an OpenFlow message of type OFPT_ERROR with the error
2080  * information taken from 'error', whose encoding must be as described in the
2081  * large comment in ofp-util.h.  If 'oh' is nonnull, then the error will use
2082  * oh->xid as its transaction ID, and it will include up to the first 64 bytes
2083  * of 'oh'.
2084  *
2085  * Returns NULL if 'error' is not an OpenFlow error code. */
2086 struct ofpbuf *
2087 ofputil_encode_error_msg(int error, const struct ofp_header *oh)
2088 {
2089     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2090
2091     struct ofpbuf *buf;
2092     const void *data;
2093     size_t len;
2094     uint8_t vendor;
2095     uint16_t type;
2096     uint16_t code;
2097     ovs_be32 xid;
2098
2099     if (!is_ofp_error(error)) {
2100         /* We format 'error' with strerror() here since it seems likely to be
2101          * a system errno value. */
2102         VLOG_WARN_RL(&rl, "invalid OpenFlow error code %d (%s)",
2103                      error, strerror(error));
2104         return NULL;
2105     }
2106
2107     if (oh) {
2108         xid = oh->xid;
2109         data = oh;
2110         len = ntohs(oh->length);
2111         if (len > 64) {
2112             len = 64;
2113         }
2114     } else {
2115         xid = 0;
2116         data = NULL;
2117         len = 0;
2118     }
2119
2120     vendor = get_ofp_err_vendor(error);
2121     type = get_ofp_err_type(error);
2122     code = get_ofp_err_code(error);
2123     if (vendor == OFPUTIL_VENDOR_OPENFLOW) {
2124         struct ofp_error_msg *oem;
2125
2126         oem = make_openflow_xid(len + sizeof *oem, OFPT_ERROR, xid, &buf);
2127         oem->type = htons(type);
2128         oem->code = htons(code);
2129     } else {
2130         struct ofp_error_msg *oem;
2131         struct nx_vendor_error *nve;
2132         uint32_t vendor_id;
2133
2134         vendor_id = vendor_code_to_id(vendor);
2135         if (vendor_id == UINT32_MAX) {
2136             VLOG_WARN_RL(&rl, "error %x contains invalid vendor code %d",
2137                          error, vendor);
2138             return NULL;
2139         }
2140
2141         oem = make_openflow_xid(len + sizeof *oem + sizeof *nve,
2142                                 OFPT_ERROR, xid, &buf);
2143         oem->type = htons(NXET_VENDOR);
2144         oem->code = htons(NXVC_VENDOR_ERROR);
2145
2146         nve = (struct nx_vendor_error *)oem->data;
2147         nve->vendor = htonl(vendor_id);
2148         nve->type = htons(type);
2149         nve->code = htons(code);
2150     }
2151
2152     if (len) {
2153         buf->size -= len;
2154         ofpbuf_put(buf, data, len);
2155     }
2156
2157     return buf;
2158 }
2159
2160 /* Decodes 'oh', which should be an OpenFlow OFPT_ERROR message, and returns an
2161  * Open vSwitch internal error code in the format described in the large
2162  * comment in ofp-util.h.
2163  *
2164  * If 'payload_ofs' is nonnull, on success '*payload_ofs' is set to the offset
2165  * to the payload starting from 'oh' and on failure it is set to 0. */
2166 int
2167 ofputil_decode_error_msg(const struct ofp_header *oh, size_t *payload_ofs)
2168 {
2169     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2170
2171     const struct ofp_error_msg *oem;
2172     uint16_t type, code;
2173     struct ofpbuf b;
2174     int vendor;
2175
2176     if (payload_ofs) {
2177         *payload_ofs = 0;
2178     }
2179     if (oh->type != OFPT_ERROR) {
2180         return EPROTO;
2181     }
2182
2183     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2184     oem = ofpbuf_try_pull(&b, sizeof *oem);
2185     if (!oem) {
2186         return EPROTO;
2187     }
2188
2189     type = ntohs(oem->type);
2190     code = ntohs(oem->code);
2191     if (type == NXET_VENDOR && code == NXVC_VENDOR_ERROR) {
2192         const struct nx_vendor_error *nve = ofpbuf_try_pull(&b, sizeof *nve);
2193         if (!nve) {
2194             return EPROTO;
2195         }
2196
2197         vendor = vendor_id_to_code(ntohl(nve->vendor));
2198         if (vendor < 0) {
2199             VLOG_WARN_RL(&rl, "error contains unknown vendor ID %#"PRIx32,
2200                          ntohl(nve->vendor));
2201             return EPROTO;
2202         }
2203         type = ntohs(nve->type);
2204         code = ntohs(nve->code);
2205     } else {
2206         vendor = OFPUTIL_VENDOR_OPENFLOW;
2207     }
2208
2209     if (type >= 1024) {
2210         VLOG_WARN_RL(&rl, "error contains type %"PRIu16" greater than "
2211                      "supported maximum value 1023", type);
2212         return EPROTO;
2213     }
2214
2215     if (payload_ofs) {
2216         *payload_ofs = (uint8_t *) b.data - (uint8_t *) oh;
2217     }
2218     return ofp_mkerr_vendor(vendor, type, code);
2219 }
2220
2221 void
2222 ofputil_format_error(struct ds *s, int error)
2223 {
2224     if (is_errno(error)) {
2225         ds_put_cstr(s, strerror(error));
2226     } else {
2227         uint16_t type = get_ofp_err_type(error);
2228         uint16_t code = get_ofp_err_code(error);
2229         const char *type_s = ofp_error_type_to_string(type);
2230         const char *code_s = ofp_error_code_to_string(type, code);
2231
2232         ds_put_format(s, "type ");
2233         if (type_s) {
2234             ds_put_cstr(s, type_s);
2235         } else {
2236             ds_put_format(s, "%"PRIu16, type);
2237         }
2238
2239         ds_put_cstr(s, ", code ");
2240         if (code_s) {
2241             ds_put_cstr(s, code_s);
2242         } else {
2243             ds_put_format(s, "%"PRIu16, code);
2244         }
2245     }
2246 }
2247
2248 char *
2249 ofputil_error_to_string(int error)
2250 {
2251     struct ds s = DS_EMPTY_INITIALIZER;
2252     ofputil_format_error(&s, error);
2253     return ds_steal_cstr(&s);
2254 }
2255
2256 /* Attempts to pull 'actions_len' bytes from the front of 'b'.  Returns 0 if
2257  * successful, otherwise an OpenFlow error.
2258  *
2259  * If successful, the first action is stored in '*actionsp' and the number of
2260  * "union ofp_action" size elements into '*n_actionsp'.  Otherwise NULL and 0
2261  * are stored, respectively.
2262  *
2263  * This function does not check that the actions are valid (the caller should
2264  * do so, with validate_actions()).  The caller is also responsible for making
2265  * sure that 'b->data' is initially aligned appropriately for "union
2266  * ofp_action". */
2267 int
2268 ofputil_pull_actions(struct ofpbuf *b, unsigned int actions_len,
2269                      union ofp_action **actionsp, size_t *n_actionsp)
2270 {
2271     if (actions_len % OFP_ACTION_ALIGN != 0) {
2272         VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
2273                      "is not a multiple of %d", actions_len, OFP_ACTION_ALIGN);
2274         goto error;
2275     }
2276
2277     *actionsp = ofpbuf_try_pull(b, actions_len);
2278     if (*actionsp == NULL) {
2279         VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
2280                      "exceeds remaining message length (%zu)",
2281                      actions_len, b->size);
2282         goto error;
2283     }
2284
2285     *n_actionsp = actions_len / OFP_ACTION_ALIGN;
2286     return 0;
2287
2288 error:
2289     *actionsp = NULL;
2290     *n_actionsp = 0;
2291     return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
2292 }