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