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