ofp-print: Implement printing for OFPUTIL_NXT_FLOW_MOD.
[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                             uint64_t 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     wc->wildcards = ofpfw & WC_INVARIANTS;
121     if (ofpfw & OFPFW_NW_TOS) {
122         wc->wildcards |= FWW_NW_TOS;
123     }
124     memset(wc->reg_masks, 0, sizeof wc->reg_masks);
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 /* Converts an OFPT_FLOW_MOD or NXT_FLOW_MOD message 'oh' into an abstract
790  * flow_mod in 'fm'.  Returns 0 if successful, otherwise an OpenFlow error
791  * code.
792  *
793  * For OFPT_FLOW_MOD messages, 'flow_format' should be the current flow format
794  * at the time when the message was received.  Otherwise 'flow_format' is
795  * ignored.
796  *
797  * Does not validate the flow_mod actions. */
798 int
799 ofputil_decode_flow_mod(struct flow_mod *fm, const struct ofp_header *oh,
800                         enum nx_flow_format flow_format)
801 {
802     const struct ofputil_msg_type *type;
803     struct ofpbuf b;
804
805     b.data = (void *) oh;
806     b.size = ntohs(oh->length);
807
808     ofputil_decode_msg_type(oh, &type);
809     if (ofputil_msg_type_code(type) == OFPUTIL_OFPT_FLOW_MOD) {
810         /* Standard OpenFlow flow_mod. */
811         struct ofp_match match, orig_match;
812         const struct ofp_flow_mod *ofm;
813         int error;
814
815         /* Dissect the message. */
816         ofm = ofpbuf_try_pull(&b, sizeof *ofm);
817         if (!ofm) {
818             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
819         }
820         error = ofputil_pull_actions(&b, b.size, &fm->actions, &fm->n_actions);
821         if (error) {
822             return error;
823         }
824
825         /* Normalize ofm->match.  If normalization actually changes anything,
826          * then log the differences. */
827         match = ofm->match;
828         match.pad1[0] = match.pad2[0] = 0;
829         orig_match = match;
830         normalize_match(&match);
831         if (memcmp(&match, &orig_match, sizeof orig_match)) {
832             if (!VLOG_DROP_INFO(&bad_ofmsg_rl)) {
833                 char *old = ofp_match_to_literal_string(&orig_match);
834                 char *new = ofp_match_to_literal_string(&match);
835                 VLOG_INFO("normalization changed ofp_match, details:");
836                 VLOG_INFO(" pre: %s", old);
837                 VLOG_INFO("post: %s", new);
838                 free(old);
839                 free(new);
840             }
841         }
842
843         /* Translate the message. */
844         ofputil_cls_rule_from_match(&match, ntohs(ofm->priority), flow_format,
845                                     ofm->cookie, &fm->cr);
846         fm->cookie = ofm->cookie;
847         fm->command = ntohs(ofm->command);
848         fm->idle_timeout = ntohs(ofm->idle_timeout);
849         fm->hard_timeout = ntohs(ofm->hard_timeout);
850         fm->buffer_id = ntohl(ofm->buffer_id);
851         fm->out_port = ntohs(ofm->out_port);
852         fm->flags = ntohs(ofm->flags);
853     } else if (ofputil_msg_type_code(type) == OFPUTIL_NXT_FLOW_MOD) {
854         /* Nicira extended flow_mod. */
855         const struct nx_flow_mod *nfm;
856         int error;
857
858         /* Dissect the message. */
859         nfm = ofpbuf_try_pull(&b, sizeof *nfm);
860         if (!nfm) {
861             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
862         }
863         error = nx_pull_match(&b, ntohs(nfm->match_len), ntohs(nfm->priority),
864                               &fm->cr);
865         if (error) {
866             return error;
867         }
868         error = ofputil_pull_actions(&b, b.size, &fm->actions, &fm->n_actions);
869         if (error) {
870             return error;
871         }
872
873         /* Translate the message. */
874         fm->cookie = nfm->cookie;
875         fm->command = ntohs(nfm->command);
876         fm->idle_timeout = ntohs(nfm->idle_timeout);
877         fm->hard_timeout = ntohs(nfm->hard_timeout);
878         fm->buffer_id = ntohl(nfm->buffer_id);
879         fm->out_port = ntohs(nfm->out_port);
880         fm->flags = ntohs(nfm->flags);
881     } else {
882         NOT_REACHED();
883     }
884
885     return 0;
886 }
887
888 /* Converts 'fm' into an OFPT_FLOW_MOD or NXT_FLOW_MOD message according to
889  * 'flow_format' and returns the message. */
890 struct ofpbuf *
891 ofputil_encode_flow_mod(const struct flow_mod *fm,
892                         enum nx_flow_format flow_format)
893 {
894     size_t actions_len = fm->n_actions * sizeof *fm->actions;
895     struct ofpbuf *msg;
896
897     if (flow_format == NXFF_OPENFLOW10
898         || flow_format == NXFF_TUN_ID_FROM_COOKIE) {
899         struct ofp_flow_mod *ofm;
900
901         msg = ofpbuf_new(sizeof *ofm + actions_len);
902         ofm = put_openflow(sizeof *ofm, OFPT_FLOW_MOD, msg);
903         ofputil_cls_rule_to_match(&fm->cr, flow_format, &ofm->match);
904         ofm->cookie = fm->cookie;
905         ofm->command = htons(fm->command);
906         ofm->idle_timeout = htons(fm->idle_timeout);
907         ofm->hard_timeout = htons(fm->hard_timeout);
908         ofm->priority = htons(fm->cr.priority);
909         ofm->buffer_id = htonl(fm->buffer_id);
910         ofm->out_port = htons(fm->out_port);
911         ofm->flags = htons(fm->flags);
912     } else if (flow_format == NXFF_NXM) {
913         struct nx_flow_mod *nfm;
914         int match_len;
915
916         msg = ofpbuf_new(sizeof *nfm + NXM_TYPICAL_LEN + actions_len);
917         put_nxmsg(sizeof *nfm, NXT_FLOW_MOD, msg);
918         match_len = nx_put_match(msg, &fm->cr);
919
920         nfm = msg->data;
921         nfm->cookie = fm->cookie;
922         nfm->command = htons(fm->command);
923         nfm->idle_timeout = htons(fm->idle_timeout);
924         nfm->hard_timeout = htons(fm->hard_timeout);
925         nfm->priority = htons(fm->cr.priority);
926         nfm->buffer_id = htonl(fm->buffer_id);
927         nfm->out_port = htons(fm->out_port);
928         nfm->flags = htons(fm->flags);
929         nfm->match_len = htons(match_len);
930     } else {
931         NOT_REACHED();
932     }
933
934     ofpbuf_put(msg, fm->actions, actions_len);
935     update_openflow_length(msg);
936     return msg;
937 }
938
939 static int
940 ofputil_decode_ofpst_flow_request(struct flow_stats_request *fsr,
941                                   const struct ofp_header *oh,
942                                   enum nx_flow_format flow_format,
943                                   bool aggregate)
944 {
945     const struct ofp_flow_stats_request *ofsr = ofputil_stats_body(oh);
946
947     fsr->aggregate = aggregate;
948     ofputil_cls_rule_from_match(&ofsr->match, 0, flow_format, 0, &fsr->match);
949     fsr->out_port = ntohs(ofsr->out_port);
950     fsr->table_id = ofsr->table_id;
951
952     return 0;
953 }
954
955 static int
956 ofputil_decode_nxst_flow_request(struct flow_stats_request *fsr,
957                                  const struct ofp_header *oh,
958                                  bool aggregate)
959 {
960     const struct nx_flow_stats_request *nfsr;
961     struct ofpbuf b;
962     int error;
963
964     b.data = (void *) oh;
965     b.size = ntohs(oh->length);
966
967     nfsr = ofpbuf_try_pull(&b, sizeof *nfsr);
968     if (!nfsr) {
969         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
970     }
971     error = nx_pull_match(&b, ntohs(nfsr->match_len), 0, &fsr->match);
972     if (error) {
973         return error;
974     }
975     if (b.size) {
976         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
977     }
978
979     fsr->aggregate = aggregate;
980     fsr->out_port = ntohs(nfsr->out_port);
981     fsr->table_id = nfsr->table_id;
982
983     return 0;
984 }
985
986 /* Converts an OFPST_FLOW, OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE
987  * message 'oh', received when the current flow format was 'flow_format', into
988  * an abstract flow_stats_request in 'fsr'.  Returns 0 if successful, otherwise
989  * an OpenFlow error code. */
990 int
991 ofputil_decode_flow_stats_request(struct flow_stats_request *fsr,
992                                   const struct ofp_header *oh,
993                                   enum nx_flow_format flow_format)
994 {
995     const struct ofputil_msg_type *type;
996     struct ofpbuf b;
997     int code;
998
999     b.data = (void *) oh;
1000     b.size = ntohs(oh->length);
1001
1002     ofputil_decode_msg_type(oh, &type);
1003     code = ofputil_msg_type_code(type);
1004     switch (code) {
1005     case OFPUTIL_OFPST_FLOW_REQUEST:
1006         return ofputil_decode_ofpst_flow_request(fsr, oh, flow_format, false);
1007
1008     case OFPUTIL_OFPST_AGGREGATE_REQUEST:
1009         return ofputil_decode_ofpst_flow_request(fsr, oh, flow_format, true);
1010
1011     case OFPUTIL_NXST_FLOW_REQUEST:
1012         return ofputil_decode_nxst_flow_request(fsr, oh, false);
1013
1014     case OFPUTIL_NXST_AGGREGATE_REQUEST:
1015         return ofputil_decode_nxst_flow_request(fsr, oh, true);
1016
1017     default:
1018         /* Hey, the caller lied. */
1019         NOT_REACHED();
1020     }
1021 }
1022
1023 /* Converts abstract flow_stats_request 'fsr' into an OFPST_FLOW,
1024  * OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE message 'oh' according to
1025  * 'flow_format', and returns the message. */
1026 struct ofpbuf *
1027 ofputil_encode_flow_stats_request(const struct flow_stats_request *fsr,
1028                                   enum nx_flow_format flow_format)
1029 {
1030     struct ofpbuf *msg;
1031
1032     if (flow_format == NXFF_OPENFLOW10
1033         || flow_format == NXFF_TUN_ID_FROM_COOKIE) {
1034         struct ofp_flow_stats_request *ofsr;
1035         int type;
1036
1037         BUILD_ASSERT_DECL(sizeof(struct ofp_flow_stats_request)
1038                           == sizeof(struct ofp_aggregate_stats_request));
1039
1040         type = fsr->aggregate ? OFPST_AGGREGATE : OFPST_FLOW;
1041         ofsr = ofputil_make_stats_request(sizeof *ofsr, type, &msg);
1042         ofputil_cls_rule_to_match(&fsr->match, flow_format, &ofsr->match);
1043         ofsr->table_id = fsr->table_id;
1044         ofsr->out_port = htons(fsr->out_port);
1045     } else if (flow_format == NXFF_NXM) {
1046         struct nx_flow_stats_request *nfsr;
1047         int match_len;
1048
1049         ofputil_make_nxstats_request(sizeof *nfsr, NXST_FLOW, &msg);
1050         match_len = nx_put_match(msg, &fsr->match);
1051
1052         nfsr = msg->data;
1053         nfsr->out_port = htons(fsr->out_port);
1054         nfsr->match_len = htons(match_len);
1055         nfsr->table_id = fsr->table_id;
1056     } else {
1057         NOT_REACHED();
1058     }
1059
1060     return msg;
1061 }
1062
1063 /* Returns a string representing the message type of 'type'.  The string is the
1064  * enumeration constant for the type, e.g. "OFPT_HELLO".  For statistics
1065  * messages, the constant is followed by "request" or "reply",
1066  * e.g. "OFPST_AGGREGATE reply". */
1067 const char *
1068 ofputil_msg_type_name(const struct ofputil_msg_type *type)
1069 {
1070     return type->name;
1071 }
1072 \f
1073 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
1074  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
1075  * an arbitrary transaction id.  Allocated bytes beyond the header, if any, are
1076  * zeroed.
1077  *
1078  * The caller is responsible for freeing '*bufferp' when it is no longer
1079  * needed.
1080  *
1081  * The OpenFlow header length is initially set to 'openflow_len'; if the
1082  * message is later extended, the length should be updated with
1083  * update_openflow_length() before sending.
1084  *
1085  * Returns the header. */
1086 void *
1087 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp)
1088 {
1089     *bufferp = ofpbuf_new(openflow_len);
1090     return put_openflow_xid(openflow_len, type, alloc_xid(), *bufferp);
1091 }
1092
1093 /* Similar to make_openflow() but creates a Nicira vendor extension message
1094  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1095 void *
1096 make_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf **bufferp)
1097 {
1098     return make_nxmsg_xid(openflow_len, subtype, alloc_xid(), bufferp);
1099 }
1100
1101 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
1102  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
1103  * transaction id 'xid'.  Allocated bytes beyond the header, if any, are
1104  * zeroed.
1105  *
1106  * The caller is responsible for freeing '*bufferp' when it is no longer
1107  * needed.
1108  *
1109  * The OpenFlow header length is initially set to 'openflow_len'; if the
1110  * message is later extended, the length should be updated with
1111  * update_openflow_length() before sending.
1112  *
1113  * Returns the header. */
1114 void *
1115 make_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
1116                   struct ofpbuf **bufferp)
1117 {
1118     *bufferp = ofpbuf_new(openflow_len);
1119     return put_openflow_xid(openflow_len, type, xid, *bufferp);
1120 }
1121
1122 /* Similar to make_openflow_xid() but creates a Nicira vendor extension message
1123  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1124 void *
1125 make_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
1126                struct ofpbuf **bufferp)
1127 {
1128     *bufferp = ofpbuf_new(openflow_len);
1129     return put_nxmsg_xid(openflow_len, subtype, xid, *bufferp);
1130 }
1131
1132 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
1133  * with the given 'type' and an arbitrary transaction id.  Allocated bytes
1134  * beyond the header, if any, are zeroed.
1135  *
1136  * The OpenFlow header length is initially set to 'openflow_len'; if the
1137  * message is later extended, the length should be updated with
1138  * update_openflow_length() before sending.
1139  *
1140  * Returns the header. */
1141 void *
1142 put_openflow(size_t openflow_len, uint8_t type, struct ofpbuf *buffer)
1143 {
1144     return put_openflow_xid(openflow_len, type, alloc_xid(), buffer);
1145 }
1146
1147 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
1148  * with the given 'type' and an transaction id 'xid'.  Allocated bytes beyond
1149  * the header, if any, are zeroed.
1150  *
1151  * The OpenFlow header length is initially set to 'openflow_len'; if the
1152  * message is later extended, the length should be updated with
1153  * update_openflow_length() before sending.
1154  *
1155  * Returns the header. */
1156 void *
1157 put_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
1158                  struct ofpbuf *buffer)
1159 {
1160     struct ofp_header *oh;
1161
1162     assert(openflow_len >= sizeof *oh);
1163     assert(openflow_len <= UINT16_MAX);
1164
1165     oh = ofpbuf_put_uninit(buffer, openflow_len);
1166     oh->version = OFP_VERSION;
1167     oh->type = type;
1168     oh->length = htons(openflow_len);
1169     oh->xid = xid;
1170     memset(oh + 1, 0, openflow_len - sizeof *oh);
1171     return oh;
1172 }
1173
1174 /* Similar to put_openflow() but append a Nicira vendor extension message with
1175  * the specific 'subtype'.  'subtype' should be in host byte order. */
1176 void *
1177 put_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf *buffer)
1178 {
1179     return put_nxmsg_xid(openflow_len, subtype, alloc_xid(), buffer);
1180 }
1181
1182 /* Similar to put_openflow_xid() but append a Nicira vendor extension message
1183  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1184 void *
1185 put_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
1186               struct ofpbuf *buffer)
1187 {
1188     struct nicira_header *nxh;
1189
1190     nxh = put_openflow_xid(openflow_len, OFPT_VENDOR, xid, buffer);
1191     nxh->vendor = htonl(NX_VENDOR_ID);
1192     nxh->subtype = htonl(subtype);
1193     return nxh;
1194 }
1195
1196 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
1197  * 'buffer->size'. */
1198 void
1199 update_openflow_length(struct ofpbuf *buffer)
1200 {
1201     struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
1202     oh->length = htons(buffer->size);
1203 }
1204
1205 /* Creates an ofp_stats_request with the given 'type' and 'body_len' bytes of
1206  * space allocated for the 'body' member.  Returns the first byte of the 'body'
1207  * member. */
1208 void *
1209 ofputil_make_stats_request(size_t body_len, uint16_t type,
1210                            struct ofpbuf **bufferp)
1211 {
1212     struct ofp_stats_request *osr;
1213     osr = make_openflow((offsetof(struct ofp_stats_request, body)
1214                         + body_len), OFPT_STATS_REQUEST, bufferp);
1215     osr->type = htons(type);
1216     osr->flags = htons(0);
1217     return osr->body;
1218 }
1219
1220 /* Creates a stats request message with Nicira as vendor and the given
1221  * 'subtype', of total length 'openflow_len'.  Returns the message. */
1222 void *
1223 ofputil_make_nxstats_request(size_t openflow_len, uint32_t subtype,
1224                              struct ofpbuf **bufferp)
1225 {
1226     struct nicira_stats_msg *nsm;
1227
1228     nsm = make_openflow(openflow_len, OFPT_STATS_REQUEST, bufferp);
1229     nsm->type = htons(OFPST_VENDOR);
1230     nsm->flags = htons(0);
1231     nsm->vendor = htonl(NX_VENDOR_ID);
1232     nsm->subtype = htonl(subtype);
1233     return nsm;
1234 }
1235
1236 /* Returns the first byte of the 'body' member of the ofp_stats_request or
1237  * ofp_stats_reply in 'oh'. */
1238 const void *
1239 ofputil_stats_body(const struct ofp_header *oh)
1240 {
1241     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1242     return ((const struct ofp_stats_request *) oh)->body;
1243 }
1244
1245 /* Returns the length of the 'body' member of the ofp_stats_request or
1246  * ofp_stats_reply in 'oh'. */
1247 size_t
1248 ofputil_stats_body_len(const struct ofp_header *oh)
1249 {
1250     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1251     return ntohs(oh->length) - sizeof(struct ofp_stats_request);
1252 }
1253
1254 struct ofpbuf *
1255 make_flow_mod(uint16_t command, const struct cls_rule *rule,
1256               size_t actions_len)
1257 {
1258     struct ofp_flow_mod *ofm;
1259     size_t size = sizeof *ofm + actions_len;
1260     struct ofpbuf *out = ofpbuf_new(size);
1261     ofm = ofpbuf_put_zeros(out, sizeof *ofm);
1262     ofm->header.version = OFP_VERSION;
1263     ofm->header.type = OFPT_FLOW_MOD;
1264     ofm->header.length = htons(size);
1265     ofm->cookie = 0;
1266     ofm->priority = htons(MIN(rule->priority, UINT16_MAX));
1267     ofputil_cls_rule_to_match(rule, NXFF_OPENFLOW10, &ofm->match);
1268     ofm->command = htons(command);
1269     return out;
1270 }
1271
1272 struct ofpbuf *
1273 make_add_flow(const struct cls_rule *rule, uint32_t buffer_id,
1274               uint16_t idle_timeout, size_t actions_len)
1275 {
1276     struct ofpbuf *out = make_flow_mod(OFPFC_ADD, rule, actions_len);
1277     struct ofp_flow_mod *ofm = out->data;
1278     ofm->idle_timeout = htons(idle_timeout);
1279     ofm->hard_timeout = htons(OFP_FLOW_PERMANENT);
1280     ofm->buffer_id = htonl(buffer_id);
1281     return out;
1282 }
1283
1284 struct ofpbuf *
1285 make_del_flow(const struct cls_rule *rule)
1286 {
1287     struct ofpbuf *out = make_flow_mod(OFPFC_DELETE_STRICT, rule, 0);
1288     struct ofp_flow_mod *ofm = out->data;
1289     ofm->out_port = htons(OFPP_NONE);
1290     return out;
1291 }
1292
1293 struct ofpbuf *
1294 make_add_simple_flow(const struct cls_rule *rule,
1295                      uint32_t buffer_id, uint16_t out_port,
1296                      uint16_t idle_timeout)
1297 {
1298     if (out_port != OFPP_NONE) {
1299         struct ofp_action_output *oao;
1300         struct ofpbuf *buffer;
1301
1302         buffer = make_add_flow(rule, buffer_id, idle_timeout, sizeof *oao);
1303         oao = ofpbuf_put_zeros(buffer, sizeof *oao);
1304         oao->type = htons(OFPAT_OUTPUT);
1305         oao->len = htons(sizeof *oao);
1306         oao->port = htons(out_port);
1307         return buffer;
1308     } else {
1309         return make_add_flow(rule, buffer_id, idle_timeout, 0);
1310     }
1311 }
1312
1313 struct ofpbuf *
1314 make_packet_in(uint32_t buffer_id, uint16_t in_port, uint8_t reason,
1315                const struct ofpbuf *payload, int max_send_len)
1316 {
1317     struct ofp_packet_in *opi;
1318     struct ofpbuf *buf;
1319     int send_len;
1320
1321     send_len = MIN(max_send_len, payload->size);
1322     buf = ofpbuf_new(sizeof *opi + send_len);
1323     opi = put_openflow_xid(offsetof(struct ofp_packet_in, data),
1324                            OFPT_PACKET_IN, 0, buf);
1325     opi->buffer_id = htonl(buffer_id);
1326     opi->total_len = htons(payload->size);
1327     opi->in_port = htons(in_port);
1328     opi->reason = reason;
1329     ofpbuf_put(buf, payload->data, send_len);
1330     update_openflow_length(buf);
1331
1332     return buf;
1333 }
1334
1335 struct ofpbuf *
1336 make_packet_out(const struct ofpbuf *packet, uint32_t buffer_id,
1337                 uint16_t in_port,
1338                 const struct ofp_action_header *actions, size_t n_actions)
1339 {
1340     size_t actions_len = n_actions * sizeof *actions;
1341     struct ofp_packet_out *opo;
1342     size_t size = sizeof *opo + actions_len + (packet ? packet->size : 0);
1343     struct ofpbuf *out = ofpbuf_new(size);
1344
1345     opo = ofpbuf_put_uninit(out, sizeof *opo);
1346     opo->header.version = OFP_VERSION;
1347     opo->header.type = OFPT_PACKET_OUT;
1348     opo->header.length = htons(size);
1349     opo->header.xid = htonl(0);
1350     opo->buffer_id = htonl(buffer_id);
1351     opo->in_port = htons(in_port == ODPP_LOCAL ? OFPP_LOCAL : in_port);
1352     opo->actions_len = htons(actions_len);
1353     ofpbuf_put(out, actions, actions_len);
1354     if (packet) {
1355         ofpbuf_put(out, packet->data, packet->size);
1356     }
1357     return out;
1358 }
1359
1360 struct ofpbuf *
1361 make_unbuffered_packet_out(const struct ofpbuf *packet,
1362                            uint16_t in_port, uint16_t out_port)
1363 {
1364     struct ofp_action_output action;
1365     action.type = htons(OFPAT_OUTPUT);
1366     action.len = htons(sizeof action);
1367     action.port = htons(out_port);
1368     return make_packet_out(packet, UINT32_MAX, in_port,
1369                            (struct ofp_action_header *) &action, 1);
1370 }
1371
1372 struct ofpbuf *
1373 make_buffered_packet_out(uint32_t buffer_id,
1374                          uint16_t in_port, uint16_t out_port)
1375 {
1376     if (out_port != OFPP_NONE) {
1377         struct ofp_action_output action;
1378         action.type = htons(OFPAT_OUTPUT);
1379         action.len = htons(sizeof action);
1380         action.port = htons(out_port);
1381         return make_packet_out(NULL, buffer_id, in_port,
1382                                (struct ofp_action_header *) &action, 1);
1383     } else {
1384         return make_packet_out(NULL, buffer_id, in_port, NULL, 0);
1385     }
1386 }
1387
1388 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
1389 struct ofpbuf *
1390 make_echo_request(void)
1391 {
1392     struct ofp_header *rq;
1393     struct ofpbuf *out = ofpbuf_new(sizeof *rq);
1394     rq = ofpbuf_put_uninit(out, sizeof *rq);
1395     rq->version = OFP_VERSION;
1396     rq->type = OFPT_ECHO_REQUEST;
1397     rq->length = htons(sizeof *rq);
1398     rq->xid = htonl(0);
1399     return out;
1400 }
1401
1402 /* Creates and returns an OFPT_ECHO_REPLY message matching the
1403  * OFPT_ECHO_REQUEST message in 'rq'. */
1404 struct ofpbuf *
1405 make_echo_reply(const struct ofp_header *rq)
1406 {
1407     size_t size = ntohs(rq->length);
1408     struct ofpbuf *out = ofpbuf_new(size);
1409     struct ofp_header *reply = ofpbuf_put(out, rq, size);
1410     reply->type = OFPT_ECHO_REPLY;
1411     return out;
1412 }
1413
1414 const struct ofp_flow_stats *
1415 flow_stats_first(struct flow_stats_iterator *iter,
1416                  const struct ofp_stats_reply *osr)
1417 {
1418     iter->pos = osr->body;
1419     iter->end = osr->body + (ntohs(osr->header.length)
1420                              - offsetof(struct ofp_stats_reply, body));
1421     return flow_stats_next(iter);
1422 }
1423
1424 const struct ofp_flow_stats *
1425 flow_stats_next(struct flow_stats_iterator *iter)
1426 {
1427     ptrdiff_t bytes_left = iter->end - iter->pos;
1428     const struct ofp_flow_stats *fs;
1429     size_t length;
1430
1431     if (bytes_left < sizeof *fs) {
1432         if (bytes_left != 0) {
1433             VLOG_WARN_RL(&bad_ofmsg_rl,
1434                          "%td leftover bytes in flow stats reply", bytes_left);
1435         }
1436         return NULL;
1437     }
1438
1439     fs = (const void *) iter->pos;
1440     length = ntohs(fs->length);
1441     if (length < sizeof *fs) {
1442         VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu is shorter than "
1443                      "min %zu", length, sizeof *fs);
1444         return NULL;
1445     } else if (length > bytes_left) {
1446         VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu but only %td "
1447                      "bytes left", length, bytes_left);
1448         return NULL;
1449     } else if ((length - sizeof *fs) % sizeof fs->actions[0]) {
1450         VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu has %zu bytes "
1451                      "left over in final action", length,
1452                      (length - sizeof *fs) % sizeof fs->actions[0]);
1453         return NULL;
1454     }
1455     iter->pos += length;
1456     return fs;
1457 }
1458
1459 static int
1460 check_action_exact_len(const union ofp_action *a, unsigned int len,
1461                        unsigned int required_len)
1462 {
1463     if (len != required_len) {
1464         VLOG_DBG_RL(&bad_ofmsg_rl,
1465                     "action %u has invalid length %"PRIu16" (must be %u)\n",
1466                     a->type, ntohs(a->header.len), required_len);
1467         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1468     }
1469     return 0;
1470 }
1471
1472 /* Checks that 'port' is a valid output port for the OFPAT_OUTPUT action, given
1473  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
1474  * 'port' is valid, otherwise an ofp_mkerr() return code. */
1475 static int
1476 check_output_port(uint16_t port, int max_ports)
1477 {
1478     switch (port) {
1479     case OFPP_IN_PORT:
1480     case OFPP_TABLE:
1481     case OFPP_NORMAL:
1482     case OFPP_FLOOD:
1483     case OFPP_ALL:
1484     case OFPP_CONTROLLER:
1485     case OFPP_LOCAL:
1486         return 0;
1487
1488     default:
1489         if (port < max_ports) {
1490             return 0;
1491         }
1492         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown output port %x", port);
1493         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
1494     }
1495 }
1496
1497 /* Checks that 'action' is a valid OFPAT_ENQUEUE action, given that the switch
1498  * will never have more than 'max_ports' ports.  Returns 0 if 'port' is valid,
1499  * otherwise an ofp_mkerr() return code. */
1500 static int
1501 check_enqueue_action(const union ofp_action *a, unsigned int len,
1502                      int max_ports)
1503 {
1504     const struct ofp_action_enqueue *oae;
1505     uint16_t port;
1506     int error;
1507
1508     error = check_action_exact_len(a, len, 16);
1509     if (error) {
1510         return error;
1511     }
1512
1513     oae = (const struct ofp_action_enqueue *) a;
1514     port = ntohs(oae->port);
1515     if (port < max_ports || port == OFPP_IN_PORT) {
1516         return 0;
1517     }
1518     VLOG_WARN_RL(&bad_ofmsg_rl, "unknown enqueue port %x", port);
1519     return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
1520 }
1521
1522 static int
1523 check_nicira_action(const union ofp_action *a, unsigned int len,
1524                     const struct flow *flow)
1525 {
1526     const struct nx_action_header *nah;
1527     int error;
1528
1529     if (len < 16) {
1530         VLOG_DBG_RL(&bad_ofmsg_rl,
1531                     "Nicira vendor action only %u bytes", len);
1532         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1533     }
1534     nah = (const struct nx_action_header *) a;
1535
1536     switch (ntohs(nah->subtype)) {
1537     case NXAST_RESUBMIT:
1538     case NXAST_SET_TUNNEL:
1539     case NXAST_DROP_SPOOFED_ARP:
1540     case NXAST_SET_QUEUE:
1541     case NXAST_POP_QUEUE:
1542         return check_action_exact_len(a, len, 16);
1543
1544     case NXAST_REG_MOVE:
1545         error = check_action_exact_len(a, len,
1546                                        sizeof(struct nx_action_reg_move));
1547         if (error) {
1548             return error;
1549         }
1550         return nxm_check_reg_move((const struct nx_action_reg_move *) a, flow);
1551
1552     case NXAST_REG_LOAD:
1553         error = check_action_exact_len(a, len,
1554                                        sizeof(struct nx_action_reg_load));
1555         if (error) {
1556             return error;
1557         }
1558         return nxm_check_reg_load((const struct nx_action_reg_load *) a, flow);
1559
1560     case NXAST_NOTE:
1561         return 0;
1562
1563     default:
1564         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR_TYPE);
1565     }
1566 }
1567
1568 static int
1569 check_action(const union ofp_action *a, unsigned int len,
1570              const struct flow *flow, int max_ports)
1571 {
1572     int error;
1573
1574     switch (ntohs(a->type)) {
1575     case OFPAT_OUTPUT:
1576         error = check_action_exact_len(a, len, 8);
1577         if (error) {
1578             return error;
1579         }
1580         return check_output_port(ntohs(a->output.port), max_ports);
1581
1582     case OFPAT_SET_VLAN_VID:
1583         error = check_action_exact_len(a, len, 8);
1584         if (error) {
1585             return error;
1586         }
1587         if (a->vlan_vid.vlan_vid & ~htons(0xfff)) {
1588             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
1589         }
1590         return 0;
1591
1592     case OFPAT_SET_VLAN_PCP:
1593         error = check_action_exact_len(a, len, 8);
1594         if (error) {
1595             return error;
1596         }
1597         if (a->vlan_vid.vlan_vid & ~7) {
1598             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
1599         }
1600         return 0;
1601
1602     case OFPAT_STRIP_VLAN:
1603     case OFPAT_SET_NW_SRC:
1604     case OFPAT_SET_NW_DST:
1605     case OFPAT_SET_NW_TOS:
1606     case OFPAT_SET_TP_SRC:
1607     case OFPAT_SET_TP_DST:
1608         return check_action_exact_len(a, len, 8);
1609
1610     case OFPAT_SET_DL_SRC:
1611     case OFPAT_SET_DL_DST:
1612         return check_action_exact_len(a, len, 16);
1613
1614     case OFPAT_VENDOR:
1615         return (a->vendor.vendor == htonl(NX_VENDOR_ID)
1616                 ? check_nicira_action(a, len, flow)
1617                 : ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR));
1618
1619     case OFPAT_ENQUEUE:
1620         return check_enqueue_action(a, len, max_ports);
1621
1622     default:
1623         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown action type %"PRIu16,
1624                 ntohs(a->type));
1625         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_TYPE);
1626     }
1627 }
1628
1629 int
1630 validate_actions(const union ofp_action *actions, size_t n_actions,
1631                  const struct flow *flow, int max_ports)
1632 {
1633     size_t i;
1634
1635     for (i = 0; i < n_actions; ) {
1636         const union ofp_action *a = &actions[i];
1637         unsigned int len = ntohs(a->header.len);
1638         unsigned int n_slots = len / OFP_ACTION_ALIGN;
1639         unsigned int slots_left = &actions[n_actions] - a;
1640         int error;
1641
1642         if (n_slots > slots_left) {
1643             VLOG_DBG_RL(&bad_ofmsg_rl,
1644                         "action requires %u slots but only %u remain",
1645                         n_slots, slots_left);
1646             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1647         } else if (!len) {
1648             VLOG_DBG_RL(&bad_ofmsg_rl, "action has invalid length 0");
1649             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1650         } else if (len % OFP_ACTION_ALIGN) {
1651             VLOG_DBG_RL(&bad_ofmsg_rl, "action length %u is not a multiple "
1652                         "of %d", len, OFP_ACTION_ALIGN);
1653             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1654         }
1655
1656         error = check_action(a, len, flow, max_ports);
1657         if (error) {
1658             return error;
1659         }
1660         i += n_slots;
1661     }
1662     return 0;
1663 }
1664
1665 /* Returns true if 'action' outputs to 'port' (which must be in network byte
1666  * order), false otherwise. */
1667 bool
1668 action_outputs_to_port(const union ofp_action *action, uint16_t port)
1669 {
1670     switch (ntohs(action->type)) {
1671     case OFPAT_OUTPUT:
1672         return action->output.port == port;
1673     case OFPAT_ENQUEUE:
1674         return ((const struct ofp_action_enqueue *) action)->port == port;
1675     default:
1676         return false;
1677     }
1678 }
1679
1680 /* The set of actions must either come from a trusted source or have been
1681  * previously validated with validate_actions(). */
1682 const union ofp_action *
1683 actions_first(struct actions_iterator *iter,
1684               const union ofp_action *oa, size_t n_actions)
1685 {
1686     iter->pos = oa;
1687     iter->end = oa + n_actions;
1688     return actions_next(iter);
1689 }
1690
1691 const union ofp_action *
1692 actions_next(struct actions_iterator *iter)
1693 {
1694     if (iter->pos != iter->end) {
1695         const union ofp_action *a = iter->pos;
1696         unsigned int len = ntohs(a->header.len);
1697         iter->pos += len / OFP_ACTION_ALIGN;
1698         return a;
1699     } else {
1700         return NULL;
1701     }
1702 }
1703
1704 void
1705 normalize_match(struct ofp_match *m)
1706 {
1707     enum { OFPFW_NW = (OFPFW_NW_SRC_MASK | OFPFW_NW_DST_MASK | OFPFW_NW_PROTO
1708                        | OFPFW_NW_TOS) };
1709     enum { OFPFW_TP = OFPFW_TP_SRC | OFPFW_TP_DST };
1710     uint32_t wc;
1711
1712     wc = ntohl(m->wildcards) & OVSFW_ALL;
1713     if (wc & OFPFW_DL_TYPE) {
1714         m->dl_type = 0;
1715
1716         /* Can't sensibly match on network or transport headers if the
1717          * data link type is unknown. */
1718         wc |= OFPFW_NW | OFPFW_TP;
1719         m->nw_src = m->nw_dst = m->nw_proto = m->nw_tos = 0;
1720         m->tp_src = m->tp_dst = 0;
1721     } else if (m->dl_type == htons(ETH_TYPE_IP)) {
1722         if (wc & OFPFW_NW_PROTO) {
1723             m->nw_proto = 0;
1724
1725             /* Can't sensibly match on transport headers if the network
1726              * protocol is unknown. */
1727             wc |= OFPFW_TP;
1728             m->tp_src = m->tp_dst = 0;
1729         } else if (m->nw_proto == IPPROTO_TCP ||
1730                    m->nw_proto == IPPROTO_UDP ||
1731                    m->nw_proto == IPPROTO_ICMP) {
1732             if (wc & OFPFW_TP_SRC) {
1733                 m->tp_src = 0;
1734             }
1735             if (wc & OFPFW_TP_DST) {
1736                 m->tp_dst = 0;
1737             }
1738         } else {
1739             /* Transport layer fields will always be extracted as zeros, so we
1740              * can do an exact-match on those values.  */
1741             wc &= ~OFPFW_TP;
1742             m->tp_src = m->tp_dst = 0;
1743         }
1744         if (wc & OFPFW_NW_SRC_MASK) {
1745             m->nw_src &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_SRC_SHIFT);
1746         }
1747         if (wc & OFPFW_NW_DST_MASK) {
1748             m->nw_dst &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_DST_SHIFT);
1749         }
1750         if (wc & OFPFW_NW_TOS) {
1751             m->nw_tos = 0;
1752         } else {
1753             m->nw_tos &= IP_DSCP_MASK;
1754         }
1755     } else if (m->dl_type == htons(ETH_TYPE_ARP)) {
1756         if (wc & OFPFW_NW_PROTO) {
1757             m->nw_proto = 0;
1758         }
1759         if (wc & OFPFW_NW_SRC_MASK) {
1760             m->nw_src &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_SRC_SHIFT);
1761         }
1762         if (wc & OFPFW_NW_DST_MASK) {
1763             m->nw_dst &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_DST_SHIFT);
1764         }
1765         m->tp_src = m->tp_dst = m->nw_tos = 0;
1766     } else {
1767         /* Network and transport layer fields will always be extracted as
1768          * zeros, so we can do an exact-match on those values. */
1769         wc &= ~(OFPFW_NW | OFPFW_TP);
1770         m->nw_proto = m->nw_src = m->nw_dst = m->nw_tos = 0;
1771         m->tp_src = m->tp_dst = 0;
1772     }
1773     if (wc & OFPFW_DL_SRC) {
1774         memset(m->dl_src, 0, sizeof m->dl_src);
1775     }
1776     if (wc & OFPFW_DL_DST) {
1777         memset(m->dl_dst, 0, sizeof m->dl_dst);
1778     }
1779     m->wildcards = htonl(wc);
1780 }
1781
1782 /* Returns a string that describes 'match' in a very literal way, without
1783  * interpreting its contents except in a very basic fashion.  The returned
1784  * string is intended to be fixed-length, so that it is easy to see differences
1785  * between two such strings if one is put above another.  This is useful for
1786  * describing changes made by normalize_match().
1787  *
1788  * The caller must free the returned string (with free()). */
1789 char *
1790 ofp_match_to_literal_string(const struct ofp_match *match)
1791 {
1792     return xasprintf("wildcards=%#10"PRIx32" "
1793                      " in_port=%5"PRId16" "
1794                      " dl_src="ETH_ADDR_FMT" "
1795                      " dl_dst="ETH_ADDR_FMT" "
1796                      " dl_vlan=%5"PRId16" "
1797                      " dl_vlan_pcp=%3"PRId8" "
1798                      " dl_type=%#6"PRIx16" "
1799                      " nw_tos=%#4"PRIx8" "
1800                      " nw_proto=%#4"PRIx16" "
1801                      " nw_src=%#10"PRIx32" "
1802                      " nw_dst=%#10"PRIx32" "
1803                      " tp_src=%5"PRId16" "
1804                      " tp_dst=%5"PRId16,
1805                      ntohl(match->wildcards),
1806                      ntohs(match->in_port),
1807                      ETH_ADDR_ARGS(match->dl_src),
1808                      ETH_ADDR_ARGS(match->dl_dst),
1809                      ntohs(match->dl_vlan),
1810                      match->dl_vlan_pcp,
1811                      ntohs(match->dl_type),
1812                      match->nw_tos,
1813                      match->nw_proto,
1814                      ntohl(match->nw_src),
1815                      ntohl(match->nw_dst),
1816                      ntohs(match->tp_src),
1817                      ntohs(match->tp_dst));
1818 }
1819
1820 static uint32_t
1821 vendor_code_to_id(uint8_t code)
1822 {
1823     switch (code) {
1824 #define OFPUTIL_VENDOR(NAME, VENDOR_ID) case NAME: return VENDOR_ID;
1825         OFPUTIL_VENDORS
1826 #undef OFPUTIL_VENDOR
1827     default:
1828         return UINT32_MAX;
1829     }
1830 }
1831
1832 /* Creates and returns an OpenFlow message of type OFPT_ERROR with the error
1833  * information taken from 'error', whose encoding must be as described in the
1834  * large comment in ofp-util.h.  If 'oh' is nonnull, then the error will use
1835  * oh->xid as its transaction ID, and it will include up to the first 64 bytes
1836  * of 'oh'.
1837  *
1838  * Returns NULL if 'error' is not an OpenFlow error code. */
1839 struct ofpbuf *
1840 make_ofp_error_msg(int error, const struct ofp_header *oh)
1841 {
1842     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1843
1844     struct ofpbuf *buf;
1845     const void *data;
1846     size_t len;
1847     uint8_t vendor;
1848     uint16_t type;
1849     uint16_t code;
1850     ovs_be32 xid;
1851
1852     if (!is_ofp_error(error)) {
1853         /* We format 'error' with strerror() here since it seems likely to be
1854          * a system errno value. */
1855         VLOG_WARN_RL(&rl, "invalid OpenFlow error code %d (%s)",
1856                      error, strerror(error));
1857         return NULL;
1858     }
1859
1860     if (oh) {
1861         xid = oh->xid;
1862         data = oh;
1863         len = ntohs(oh->length);
1864         if (len > 64) {
1865             len = 64;
1866         }
1867     } else {
1868         xid = 0;
1869         data = NULL;
1870         len = 0;
1871     }
1872
1873     vendor = get_ofp_err_vendor(error);
1874     type = get_ofp_err_type(error);
1875     code = get_ofp_err_code(error);
1876     if (vendor == OFPUTIL_VENDOR_OPENFLOW) {
1877         struct ofp_error_msg *oem;
1878
1879         oem = make_openflow_xid(len + sizeof *oem, OFPT_ERROR, xid, &buf);
1880         oem->type = htons(type);
1881         oem->code = htons(code);
1882     } else {
1883         struct ofp_error_msg *oem;
1884         struct nx_vendor_error *nve;
1885         uint32_t vendor_id;
1886
1887         vendor_id = vendor_code_to_id(vendor);
1888         if (vendor_id == UINT32_MAX) {
1889             VLOG_WARN_RL(&rl, "error %x contains invalid vendor code %d",
1890                          error, vendor);
1891             return NULL;
1892         }
1893
1894         oem = make_openflow_xid(len + sizeof *oem + sizeof *nve,
1895                                 OFPT_ERROR, xid, &buf);
1896         oem->type = htons(NXET_VENDOR);
1897         oem->code = htons(NXVC_VENDOR_ERROR);
1898
1899         nve = ofpbuf_put_uninit(buf, sizeof *nve);
1900         nve->vendor = htonl(vendor_id);
1901         nve->type = htons(type);
1902         nve->code = htons(code);
1903     }
1904
1905     if (len) {
1906         ofpbuf_put(buf, data, len);
1907     }
1908
1909     return buf;
1910 }
1911
1912 /* Attempts to pull 'actions_len' bytes from the front of 'b'.  Returns 0 if
1913  * successful, otherwise an OpenFlow error.
1914  *
1915  * If successful, the first action is stored in '*actionsp' and the number of
1916  * "union ofp_action" size elements into '*n_actionsp'.  Otherwise NULL and 0
1917  * are stored, respectively.
1918  *
1919  * This function does not check that the actions are valid (the caller should
1920  * do so, with validate_actions()).  The caller is also responsible for making
1921  * sure that 'b->data' is initially aligned appropriately for "union
1922  * ofp_action". */
1923 int
1924 ofputil_pull_actions(struct ofpbuf *b, unsigned int actions_len,
1925                      union ofp_action **actionsp, size_t *n_actionsp)
1926 {
1927     if (actions_len % OFP_ACTION_ALIGN != 0) {
1928         VLOG_DBG_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
1929                     "is not a multiple of %d", actions_len, OFP_ACTION_ALIGN);
1930         goto error;
1931     }
1932
1933     *actionsp = ofpbuf_try_pull(b, actions_len);
1934     if (*actionsp == NULL) {
1935         VLOG_DBG_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
1936                     "exceeds remaining message length (%zu)",
1937                     actions_len, b->size);
1938         goto error;
1939     }
1940
1941     *n_actionsp = actions_len / OFP_ACTION_ALIGN;
1942     return 0;
1943
1944 error:
1945     *actionsp = NULL;
1946     *n_actionsp = 0;
1947     return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1948 }