82797d4d5f1cbf806fa32814e4f11725b1260064
[openvswitch] / 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_VLAN) \
76     WC_INVARIANT_BIT(DL_SRC) \
77     WC_INVARIANT_BIT(DL_DST) \
78     WC_INVARIANT_BIT(DL_TYPE) \
79     WC_INVARIANT_BIT(NW_PROTO) \
80     WC_INVARIANT_BIT(TP_SRC) \
81     WC_INVARIANT_BIT(TP_DST)
82
83 /* Verify that all of the invariant bits (as defined on WC_INVARIANT_LIST)
84  * actually have the same names and values. */
85 #define WC_INVARIANT_BIT(NAME) BUILD_ASSERT_DECL(FWW_##NAME == OFPFW_##NAME);
86     WC_INVARIANT_LIST
87 #undef WC_INVARIANT_BIT
88
89 /* WC_INVARIANTS is the invariant bits (as defined on WC_INVARIANT_LIST) all
90  * OR'd together. */
91 enum {
92     WC_INVARIANTS = 0
93 #define WC_INVARIANT_BIT(NAME) | FWW_##NAME
94     WC_INVARIANT_LIST
95 #undef WC_INVARIANT_BIT
96 };
97
98 /* Converts the ofp_match in 'match' into a cls_rule in 'rule', with the given
99  * 'priority'.
100  *
101  * 'flow_format' must either NXFF_OPENFLOW10 or NXFF_TUN_ID_FROM_COOKIE.  In
102  * the latter case only, 'flow''s tun_id field will be taken from the high bits
103  * of 'cookie', if 'match''s wildcards do not indicate that tun_id is
104  * wildcarded. */
105 void
106 ofputil_cls_rule_from_match(const struct ofp_match *match,
107                             unsigned int priority, int flow_format,
108                             uint64_t cookie, struct cls_rule *rule)
109 {
110     struct flow_wildcards *wc = &rule->wc;
111     unsigned int ofpfw;
112
113     /* Initialize rule->priority. */
114     ofpfw = ntohl(match->wildcards);
115     ofpfw &= flow_format == NXFF_TUN_ID_FROM_COOKIE ? OVSFW_ALL : OFPFW_ALL;
116     rule->priority = !ofpfw ? UINT16_MAX : priority;
117
118     /* Initialize most of rule->wc. */
119     wc->wildcards = ofpfw & WC_INVARIANTS;
120     if (ofpfw & OFPFW_DL_VLAN_PCP) {
121         wc->wildcards |= FWW_DL_VLAN_PCP;
122     }
123     if (ofpfw & OFPFW_NW_TOS) {
124         wc->wildcards |= FWW_NW_TOS;
125     }
126     memset(wc->reg_masks, 0, sizeof wc->reg_masks);
127     wc->nw_src_mask = ofputil_wcbits_to_netmask(ofpfw >> OFPFW_NW_SRC_SHIFT);
128     wc->nw_dst_mask = ofputil_wcbits_to_netmask(ofpfw >> OFPFW_NW_DST_SHIFT);
129
130     if (!(ofpfw & NXFW_TUN_ID)) {
131         rule->flow.tun_id = htonl(ntohll(cookie) >> 32);
132     } else {
133         wc->wildcards |= FWW_TUN_ID;
134         rule->flow.tun_id = 0;
135     }
136
137     if (ofpfw & OFPFW_DL_DST) {
138         /* OpenFlow 1.0 OFPFW_DL_DST covers the whole Ethernet destination, but
139          * Open vSwitch breaks the Ethernet destination into bits as FWW_DL_DST
140          * and FWW_ETH_MCAST. */
141         wc->wildcards |= FWW_ETH_MCAST;
142     }
143
144     /* Initialize rule->flow. */
145     rule->flow.nw_src = match->nw_src;
146     rule->flow.nw_dst = match->nw_dst;
147     rule->flow.in_port = (match->in_port == htons(OFPP_LOCAL) ? ODPP_LOCAL
148                      : ntohs(match->in_port));
149     rule->flow.dl_vlan = match->dl_vlan;
150     rule->flow.dl_vlan_pcp = match->dl_vlan_pcp;
151     rule->flow.dl_type = match->dl_type;
152     rule->flow.tp_src = match->tp_src;
153     rule->flow.tp_dst = match->tp_dst;
154     memcpy(rule->flow.dl_src, match->dl_src, ETH_ADDR_LEN);
155     memcpy(rule->flow.dl_dst, match->dl_dst, ETH_ADDR_LEN);
156     rule->flow.nw_tos = match->nw_tos;
157     rule->flow.nw_proto = match->nw_proto;
158
159     /* Clean up. */
160     cls_rule_zero_wildcarded_fields(rule);
161 }
162
163 /* Extract 'flow' with 'wildcards' into the OpenFlow match structure
164  * 'match'.
165  *
166  * 'flow_format' must either NXFF_OPENFLOW10 or NXFF_TUN_ID_FROM_COOKIE.  In
167  * the latter case only, 'match''s NXFW_TUN_ID bit will be filled in; otherwise
168  * it is always set to 0. */
169 void
170 ofputil_cls_rule_to_match(const struct cls_rule *rule, int flow_format,
171                           struct ofp_match *match)
172 {
173     const struct flow_wildcards *wc = &rule->wc;
174     unsigned int ofpfw;
175
176     /* Figure out OpenFlow wildcards. */
177     ofpfw = wc->wildcards & WC_INVARIANTS;
178     ofpfw |= ofputil_netmask_to_wcbits(wc->nw_src_mask) << OFPFW_NW_SRC_SHIFT;
179     ofpfw |= ofputil_netmask_to_wcbits(wc->nw_dst_mask) << OFPFW_NW_DST_SHIFT;
180     if (wc->wildcards & FWW_DL_VLAN_PCP) {
181         ofpfw |= OFPFW_DL_VLAN_PCP;
182     }
183     if (wc->wildcards & FWW_NW_TOS) {
184         ofpfw |= OFPFW_NW_TOS;
185     }
186     if (flow_format == NXFF_TUN_ID_FROM_COOKIE && wc->wildcards & FWW_TUN_ID) {
187         ofpfw |= NXFW_TUN_ID;
188     }
189
190     /* Compose match structure. */
191     match->wildcards = htonl(ofpfw);
192     match->in_port = htons(rule->flow.in_port == ODPP_LOCAL ? OFPP_LOCAL
193                            : rule->flow.in_port);
194     match->dl_vlan = rule->flow.dl_vlan;
195     match->dl_vlan_pcp = rule->flow.dl_vlan_pcp;
196     memcpy(match->dl_src, rule->flow.dl_src, ETH_ADDR_LEN);
197     memcpy(match->dl_dst, rule->flow.dl_dst, ETH_ADDR_LEN);
198     match->dl_type = rule->flow.dl_type;
199     match->nw_src = rule->flow.nw_src;
200     match->nw_dst = rule->flow.nw_dst;
201     match->nw_tos = rule->flow.nw_tos;
202     match->nw_proto = rule->flow.nw_proto;
203     match->tp_src = rule->flow.tp_src;
204     match->tp_dst = rule->flow.tp_dst;
205     memset(match->pad1, '\0', sizeof match->pad1);
206     memset(match->pad2, '\0', sizeof match->pad2);
207 }
208
209 /* Returns a transaction ID to use for an outgoing OpenFlow message. */
210 static ovs_be32
211 alloc_xid(void)
212 {
213     static uint32_t next_xid = 1;
214     return htonl(next_xid++);
215 }
216
217 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
218  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
219  * an arbitrary transaction id.  Allocated bytes beyond the header, if any, are
220  * zeroed.
221  *
222  * The caller is responsible for freeing '*bufferp' when it is no longer
223  * needed.
224  *
225  * The OpenFlow header length is initially set to 'openflow_len'; if the
226  * message is later extended, the length should be updated with
227  * update_openflow_length() before sending.
228  *
229  * Returns the header. */
230 void *
231 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp)
232 {
233     *bufferp = ofpbuf_new(openflow_len);
234     return put_openflow_xid(openflow_len, type, alloc_xid(), *bufferp);
235 }
236
237 /* Similar to make_openflow() but creates a Nicira vendor extension message
238  * with the specific 'subtype'.  'subtype' should be in host byte order. */
239 void *
240 make_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf **bufferp)
241 {
242     return make_nxmsg_xid(openflow_len, subtype, alloc_xid(), bufferp);
243 }
244
245 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
246  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
247  * transaction id 'xid'.  Allocated bytes beyond the header, if any, are
248  * zeroed.
249  *
250  * The caller is responsible for freeing '*bufferp' when it is no longer
251  * needed.
252  *
253  * The OpenFlow header length is initially set to 'openflow_len'; if the
254  * message is later extended, the length should be updated with
255  * update_openflow_length() before sending.
256  *
257  * Returns the header. */
258 void *
259 make_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
260                   struct ofpbuf **bufferp)
261 {
262     *bufferp = ofpbuf_new(openflow_len);
263     return put_openflow_xid(openflow_len, type, xid, *bufferp);
264 }
265
266 /* Similar to make_openflow_xid() but creates a Nicira vendor extension message
267  * with the specific 'subtype'.  'subtype' should be in host byte order. */
268 void *
269 make_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
270                struct ofpbuf **bufferp)
271 {
272     struct nicira_header *nxh = make_openflow_xid(openflow_len, OFPT_VENDOR,
273                                                   xid, bufferp);
274     nxh->vendor = htonl(NX_VENDOR_ID);
275     nxh->subtype = htonl(subtype);
276     return nxh;
277 }
278
279 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
280  * with the given 'type' and an arbitrary transaction id.  Allocated bytes
281  * beyond the header, if any, are zeroed.
282  *
283  * The OpenFlow header length is initially set to 'openflow_len'; if the
284  * message is later extended, the length should be updated with
285  * update_openflow_length() before sending.
286  *
287  * Returns the header. */
288 void *
289 put_openflow(size_t openflow_len, uint8_t type, struct ofpbuf *buffer)
290 {
291     return put_openflow_xid(openflow_len, type, alloc_xid(), buffer);
292 }
293
294 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
295  * with the given 'type' and an transaction id 'xid'.  Allocated bytes beyond
296  * the header, if any, are zeroed.
297  *
298  * The OpenFlow header length is initially set to 'openflow_len'; if the
299  * message is later extended, the length should be updated with
300  * update_openflow_length() before sending.
301  *
302  * Returns the header. */
303 void *
304 put_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
305                  struct ofpbuf *buffer)
306 {
307     struct ofp_header *oh;
308
309     assert(openflow_len >= sizeof *oh);
310     assert(openflow_len <= UINT16_MAX);
311
312     oh = ofpbuf_put_uninit(buffer, openflow_len);
313     oh->version = OFP_VERSION;
314     oh->type = type;
315     oh->length = htons(openflow_len);
316     oh->xid = xid;
317     memset(oh + 1, 0, openflow_len - sizeof *oh);
318     return oh;
319 }
320
321 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
322  * 'buffer->size'. */
323 void
324 update_openflow_length(struct ofpbuf *buffer)
325 {
326     struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
327     oh->length = htons(buffer->size);
328 }
329
330 struct ofpbuf *
331 make_flow_mod(uint16_t command, const struct flow *flow, size_t actions_len)
332 {
333     struct ofp_flow_mod *ofm;
334     size_t size = sizeof *ofm + actions_len;
335     struct ofpbuf *out = ofpbuf_new(size);
336     ofm = ofpbuf_put_zeros(out, sizeof *ofm);
337     ofm->header.version = OFP_VERSION;
338     ofm->header.type = OFPT_FLOW_MOD;
339     ofm->header.length = htons(size);
340     ofm->cookie = 0;
341     ofm->match.wildcards = htonl(0);
342     ofm->match.in_port = htons(flow->in_port == ODPP_LOCAL ? OFPP_LOCAL
343                                : flow->in_port);
344     memcpy(ofm->match.dl_src, flow->dl_src, sizeof ofm->match.dl_src);
345     memcpy(ofm->match.dl_dst, flow->dl_dst, sizeof ofm->match.dl_dst);
346     ofm->match.dl_vlan = flow->dl_vlan;
347     ofm->match.dl_vlan_pcp = flow->dl_vlan_pcp;
348     ofm->match.dl_type = flow->dl_type;
349     ofm->match.nw_src = flow->nw_src;
350     ofm->match.nw_dst = flow->nw_dst;
351     ofm->match.nw_proto = flow->nw_proto;
352     ofm->match.nw_tos = flow->nw_tos;
353     ofm->match.tp_src = flow->tp_src;
354     ofm->match.tp_dst = flow->tp_dst;
355     ofm->command = htons(command);
356     return out;
357 }
358
359 struct ofpbuf *
360 make_add_flow(const struct flow *flow, uint32_t buffer_id,
361               uint16_t idle_timeout, size_t actions_len)
362 {
363     struct ofpbuf *out = make_flow_mod(OFPFC_ADD, flow, actions_len);
364     struct ofp_flow_mod *ofm = out->data;
365     ofm->idle_timeout = htons(idle_timeout);
366     ofm->hard_timeout = htons(OFP_FLOW_PERMANENT);
367     ofm->buffer_id = htonl(buffer_id);
368     return out;
369 }
370
371 struct ofpbuf *
372 make_del_flow(const struct flow *flow)
373 {
374     struct ofpbuf *out = make_flow_mod(OFPFC_DELETE_STRICT, flow, 0);
375     struct ofp_flow_mod *ofm = out->data;
376     ofm->out_port = htons(OFPP_NONE);
377     return out;
378 }
379
380 struct ofpbuf *
381 make_add_simple_flow(const struct flow *flow,
382                      uint32_t buffer_id, uint16_t out_port,
383                      uint16_t idle_timeout)
384 {
385     if (out_port != OFPP_NONE) {
386         struct ofp_action_output *oao;
387         struct ofpbuf *buffer;
388
389         buffer = make_add_flow(flow, buffer_id, idle_timeout, sizeof *oao);
390         oao = ofpbuf_put_zeros(buffer, sizeof *oao);
391         oao->type = htons(OFPAT_OUTPUT);
392         oao->len = htons(sizeof *oao);
393         oao->port = htons(out_port);
394         return buffer;
395     } else {
396         return make_add_flow(flow, buffer_id, idle_timeout, 0);
397     }
398 }
399
400 struct ofpbuf *
401 make_packet_in(uint32_t buffer_id, uint16_t in_port, uint8_t reason,
402                const struct ofpbuf *payload, int max_send_len)
403 {
404     struct ofp_packet_in *opi;
405     struct ofpbuf *buf;
406     int send_len;
407
408     send_len = MIN(max_send_len, payload->size);
409     buf = ofpbuf_new(sizeof *opi + send_len);
410     opi = put_openflow_xid(offsetof(struct ofp_packet_in, data),
411                            OFPT_PACKET_IN, 0, buf);
412     opi->buffer_id = htonl(buffer_id);
413     opi->total_len = htons(payload->size);
414     opi->in_port = htons(in_port);
415     opi->reason = reason;
416     ofpbuf_put(buf, payload->data, send_len);
417     update_openflow_length(buf);
418
419     return buf;
420 }
421
422 struct ofpbuf *
423 make_packet_out(const struct ofpbuf *packet, uint32_t buffer_id,
424                 uint16_t in_port,
425                 const struct ofp_action_header *actions, size_t n_actions)
426 {
427     size_t actions_len = n_actions * sizeof *actions;
428     struct ofp_packet_out *opo;
429     size_t size = sizeof *opo + actions_len + (packet ? packet->size : 0);
430     struct ofpbuf *out = ofpbuf_new(size);
431
432     opo = ofpbuf_put_uninit(out, sizeof *opo);
433     opo->header.version = OFP_VERSION;
434     opo->header.type = OFPT_PACKET_OUT;
435     opo->header.length = htons(size);
436     opo->header.xid = htonl(0);
437     opo->buffer_id = htonl(buffer_id);
438     opo->in_port = htons(in_port == ODPP_LOCAL ? OFPP_LOCAL : in_port);
439     opo->actions_len = htons(actions_len);
440     ofpbuf_put(out, actions, actions_len);
441     if (packet) {
442         ofpbuf_put(out, packet->data, packet->size);
443     }
444     return out;
445 }
446
447 struct ofpbuf *
448 make_unbuffered_packet_out(const struct ofpbuf *packet,
449                            uint16_t in_port, uint16_t out_port)
450 {
451     struct ofp_action_output action;
452     action.type = htons(OFPAT_OUTPUT);
453     action.len = htons(sizeof action);
454     action.port = htons(out_port);
455     return make_packet_out(packet, UINT32_MAX, in_port,
456                            (struct ofp_action_header *) &action, 1);
457 }
458
459 struct ofpbuf *
460 make_buffered_packet_out(uint32_t buffer_id,
461                          uint16_t in_port, uint16_t out_port)
462 {
463     if (out_port != OFPP_NONE) {
464         struct ofp_action_output action;
465         action.type = htons(OFPAT_OUTPUT);
466         action.len = htons(sizeof action);
467         action.port = htons(out_port);
468         return make_packet_out(NULL, buffer_id, in_port,
469                                (struct ofp_action_header *) &action, 1);
470     } else {
471         return make_packet_out(NULL, buffer_id, in_port, NULL, 0);
472     }
473 }
474
475 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
476 struct ofpbuf *
477 make_echo_request(void)
478 {
479     struct ofp_header *rq;
480     struct ofpbuf *out = ofpbuf_new(sizeof *rq);
481     rq = ofpbuf_put_uninit(out, sizeof *rq);
482     rq->version = OFP_VERSION;
483     rq->type = OFPT_ECHO_REQUEST;
484     rq->length = htons(sizeof *rq);
485     rq->xid = htonl(0);
486     return out;
487 }
488
489 /* Creates and returns an OFPT_ECHO_REPLY message matching the
490  * OFPT_ECHO_REQUEST message in 'rq'. */
491 struct ofpbuf *
492 make_echo_reply(const struct ofp_header *rq)
493 {
494     size_t size = ntohs(rq->length);
495     struct ofpbuf *out = ofpbuf_new(size);
496     struct ofp_header *reply = ofpbuf_put(out, rq, size);
497     reply->type = OFPT_ECHO_REPLY;
498     return out;
499 }
500
501 static int
502 check_message_type(uint8_t got_type, uint8_t want_type)
503 {
504     if (got_type != want_type) {
505         char *want_type_name = ofp_message_type_to_string(want_type);
506         char *got_type_name = ofp_message_type_to_string(got_type);
507         VLOG_WARN_RL(&bad_ofmsg_rl,
508                      "received bad message type %s (expected %s)",
509                      got_type_name, want_type_name);
510         free(want_type_name);
511         free(got_type_name);
512         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE);
513     }
514     return 0;
515 }
516
517 /* Checks that 'msg' has type 'type' and that it is exactly 'size' bytes long.
518  * Returns 0 if the checks pass, otherwise an OpenFlow error code (produced
519  * with ofp_mkerr()). */
520 int
521 check_ofp_message(const struct ofp_header *msg, uint8_t type, size_t size)
522 {
523     size_t got_size;
524     int error;
525
526     error = check_message_type(msg->type, type);
527     if (error) {
528         return error;
529     }
530
531     got_size = ntohs(msg->length);
532     if (got_size != size) {
533         char *type_name = ofp_message_type_to_string(type);
534         VLOG_WARN_RL(&bad_ofmsg_rl,
535                      "received %s message of length %zu (expected %zu)",
536                      type_name, got_size, size);
537         free(type_name);
538         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
539     }
540
541     return 0;
542 }
543
544 /* Checks that 'msg' has type 'type' and that 'msg' is 'size' plus a
545  * nonnegative integer multiple of 'array_elt_size' bytes long.  Returns 0 if
546  * the checks pass, otherwise an OpenFlow error code (produced with
547  * ofp_mkerr()).
548  *
549  * If 'n_array_elts' is nonnull, then '*n_array_elts' is set to the number of
550  * 'array_elt_size' blocks in 'msg' past the first 'min_size' bytes, when
551  * successful. */
552 int
553 check_ofp_message_array(const struct ofp_header *msg, uint8_t type,
554                         size_t min_size, size_t array_elt_size,
555                         size_t *n_array_elts)
556 {
557     size_t got_size;
558     int error;
559
560     assert(array_elt_size);
561
562     error = check_message_type(msg->type, type);
563     if (error) {
564         return error;
565     }
566
567     got_size = ntohs(msg->length);
568     if (got_size < min_size) {
569         char *type_name = ofp_message_type_to_string(type);
570         VLOG_WARN_RL(&bad_ofmsg_rl, "received %s message of length %zu "
571                      "(expected at least %zu)",
572                      type_name, got_size, min_size);
573         free(type_name);
574         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
575     }
576     if ((got_size - min_size) % array_elt_size) {
577         char *type_name = ofp_message_type_to_string(type);
578         VLOG_WARN_RL(&bad_ofmsg_rl,
579                      "received %s message of bad length %zu: the "
580                      "excess over %zu (%zu) is not evenly divisible by %zu "
581                      "(remainder is %zu)",
582                      type_name, got_size, min_size, got_size - min_size,
583                      array_elt_size, (got_size - min_size) % array_elt_size);
584         free(type_name);
585         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
586     }
587     if (n_array_elts) {
588         *n_array_elts = (got_size - min_size) / array_elt_size;
589     }
590     return 0;
591 }
592
593 const struct ofp_flow_stats *
594 flow_stats_first(struct flow_stats_iterator *iter,
595                  const struct ofp_stats_reply *osr)
596 {
597     iter->pos = osr->body;
598     iter->end = osr->body + (ntohs(osr->header.length)
599                              - offsetof(struct ofp_stats_reply, body));
600     return flow_stats_next(iter);
601 }
602
603 const struct ofp_flow_stats *
604 flow_stats_next(struct flow_stats_iterator *iter)
605 {
606     ptrdiff_t bytes_left = iter->end - iter->pos;
607     const struct ofp_flow_stats *fs;
608     size_t length;
609
610     if (bytes_left < sizeof *fs) {
611         if (bytes_left != 0) {
612             VLOG_WARN_RL(&bad_ofmsg_rl,
613                          "%td leftover bytes in flow stats reply", bytes_left);
614         }
615         return NULL;
616     }
617
618     fs = (const void *) iter->pos;
619     length = ntohs(fs->length);
620     if (length < sizeof *fs) {
621         VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu is shorter than "
622                      "min %zu", length, sizeof *fs);
623         return NULL;
624     } else if (length > bytes_left) {
625         VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu but only %td "
626                      "bytes left", length, bytes_left);
627         return NULL;
628     } else if ((length - sizeof *fs) % sizeof fs->actions[0]) {
629         VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu has %zu bytes "
630                      "left over in final action", length,
631                      (length - sizeof *fs) % sizeof fs->actions[0]);
632         return NULL;
633     }
634     iter->pos += length;
635     return fs;
636 }
637
638 static int
639 check_action_exact_len(const union ofp_action *a, unsigned int len,
640                        unsigned int required_len)
641 {
642     if (len != required_len) {
643         VLOG_DBG_RL(&bad_ofmsg_rl,
644                     "action %u has invalid length %"PRIu16" (must be %u)\n",
645                     a->type, ntohs(a->header.len), required_len);
646         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
647     }
648     return 0;
649 }
650
651 /* Checks that 'port' is a valid output port for the OFPAT_OUTPUT action, given
652  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
653  * 'port' is valid, otherwise an ofp_mkerr() return code. */
654 static int
655 check_output_port(uint16_t port, int max_ports)
656 {
657     switch (port) {
658     case OFPP_IN_PORT:
659     case OFPP_TABLE:
660     case OFPP_NORMAL:
661     case OFPP_FLOOD:
662     case OFPP_ALL:
663     case OFPP_CONTROLLER:
664     case OFPP_LOCAL:
665         return 0;
666
667     default:
668         if (port < max_ports) {
669             return 0;
670         }
671         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown output port %x", port);
672         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
673     }
674 }
675
676 /* Checks that 'action' is a valid OFPAT_ENQUEUE action, given that the switch
677  * will never have more than 'max_ports' ports.  Returns 0 if 'port' is valid,
678  * otherwise an ofp_mkerr() return code. */
679 static int
680 check_enqueue_action(const union ofp_action *a, unsigned int len,
681                      int max_ports)
682 {
683     const struct ofp_action_enqueue *oae;
684     uint16_t port;
685     int error;
686
687     error = check_action_exact_len(a, len, 16);
688     if (error) {
689         return error;
690     }
691
692     oae = (const struct ofp_action_enqueue *) a;
693     port = ntohs(oae->port);
694     if (port < max_ports || port == OFPP_IN_PORT) {
695         return 0;
696     }
697     VLOG_WARN_RL(&bad_ofmsg_rl, "unknown enqueue port %x", port);
698     return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
699 }
700
701 static int
702 check_nicira_action(const union ofp_action *a, unsigned int len,
703                     const struct flow *flow)
704 {
705     const struct nx_action_header *nah;
706     int error;
707
708     if (len < 16) {
709         VLOG_DBG_RL(&bad_ofmsg_rl,
710                     "Nicira vendor action only %u bytes", len);
711         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
712     }
713     nah = (const struct nx_action_header *) a;
714
715     switch (ntohs(nah->subtype)) {
716     case NXAST_RESUBMIT:
717     case NXAST_SET_TUNNEL:
718     case NXAST_DROP_SPOOFED_ARP:
719     case NXAST_SET_QUEUE:
720     case NXAST_POP_QUEUE:
721         return check_action_exact_len(a, len, 16);
722
723     case NXAST_REG_MOVE:
724         error = check_action_exact_len(a, len,
725                                        sizeof(struct nx_action_reg_move));
726         if (error) {
727             return error;
728         }
729         return nxm_check_reg_move((const struct nx_action_reg_move *) a, flow);
730
731     case NXAST_REG_LOAD:
732         error = check_action_exact_len(a, len,
733                                        sizeof(struct nx_action_reg_load));
734         if (error) {
735             return error;
736         }
737         return nxm_check_reg_load((const struct nx_action_reg_load *) a, flow);
738
739     case NXAST_NOTE:
740         return 0;
741
742     default:
743         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR_TYPE);
744     }
745 }
746
747 static int
748 check_action(const union ofp_action *a, unsigned int len,
749              const struct flow *flow, int max_ports)
750 {
751     int error;
752
753     switch (ntohs(a->type)) {
754     case OFPAT_OUTPUT:
755         error = check_action_exact_len(a, len, 8);
756         if (error) {
757             return error;
758         }
759         return check_output_port(ntohs(a->output.port), max_ports);
760
761     case OFPAT_SET_VLAN_VID:
762         error = check_action_exact_len(a, len, 8);
763         if (error) {
764             return error;
765         }
766         if (a->vlan_vid.vlan_vid & ~htons(0xfff)) {
767             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
768         }
769         return 0;
770
771     case OFPAT_SET_VLAN_PCP:
772         error = check_action_exact_len(a, len, 8);
773         if (error) {
774             return error;
775         }
776         if (a->vlan_vid.vlan_vid & ~7) {
777             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
778         }
779         return 0;
780
781     case OFPAT_STRIP_VLAN:
782     case OFPAT_SET_NW_SRC:
783     case OFPAT_SET_NW_DST:
784     case OFPAT_SET_NW_TOS:
785     case OFPAT_SET_TP_SRC:
786     case OFPAT_SET_TP_DST:
787         return check_action_exact_len(a, len, 8);
788
789     case OFPAT_SET_DL_SRC:
790     case OFPAT_SET_DL_DST:
791         return check_action_exact_len(a, len, 16);
792
793     case OFPAT_VENDOR:
794         return (a->vendor.vendor == htonl(NX_VENDOR_ID)
795                 ? check_nicira_action(a, len, flow)
796                 : ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR));
797
798     case OFPAT_ENQUEUE:
799         return check_enqueue_action(a, len, max_ports);
800
801     default:
802         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown action type %"PRIu16,
803                 ntohs(a->type));
804         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_TYPE);
805     }
806 }
807
808 int
809 validate_actions(const union ofp_action *actions, size_t n_actions,
810                  const struct flow *flow, int max_ports)
811 {
812     size_t i;
813
814     for (i = 0; i < n_actions; ) {
815         const union ofp_action *a = &actions[i];
816         unsigned int len = ntohs(a->header.len);
817         unsigned int n_slots = len / OFP_ACTION_ALIGN;
818         unsigned int slots_left = &actions[n_actions] - a;
819         int error;
820
821         if (n_slots > slots_left) {
822             VLOG_DBG_RL(&bad_ofmsg_rl,
823                         "action requires %u slots but only %u remain",
824                         n_slots, slots_left);
825             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
826         } else if (!len) {
827             VLOG_DBG_RL(&bad_ofmsg_rl, "action has invalid length 0");
828             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
829         } else if (len % OFP_ACTION_ALIGN) {
830             VLOG_DBG_RL(&bad_ofmsg_rl, "action length %u is not a multiple "
831                         "of %d", len, OFP_ACTION_ALIGN);
832             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
833         }
834
835         error = check_action(a, len, flow, max_ports);
836         if (error) {
837             return error;
838         }
839         i += n_slots;
840     }
841     return 0;
842 }
843
844 /* Returns true if 'action' outputs to 'port' (which must be in network byte
845  * order), false otherwise. */
846 bool
847 action_outputs_to_port(const union ofp_action *action, uint16_t port)
848 {
849     switch (ntohs(action->type)) {
850     case OFPAT_OUTPUT:
851         return action->output.port == port;
852     case OFPAT_ENQUEUE:
853         return ((const struct ofp_action_enqueue *) action)->port == port;
854     default:
855         return false;
856     }
857 }
858
859 /* The set of actions must either come from a trusted source or have been
860  * previously validated with validate_actions(). */
861 const union ofp_action *
862 actions_first(struct actions_iterator *iter,
863               const union ofp_action *oa, size_t n_actions)
864 {
865     iter->pos = oa;
866     iter->end = oa + n_actions;
867     return actions_next(iter);
868 }
869
870 const union ofp_action *
871 actions_next(struct actions_iterator *iter)
872 {
873     if (iter->pos != iter->end) {
874         const union ofp_action *a = iter->pos;
875         unsigned int len = ntohs(a->header.len);
876         iter->pos += len / OFP_ACTION_ALIGN;
877         return a;
878     } else {
879         return NULL;
880     }
881 }
882
883 void
884 normalize_match(struct ofp_match *m)
885 {
886     enum { OFPFW_NW = (OFPFW_NW_SRC_MASK | OFPFW_NW_DST_MASK | OFPFW_NW_PROTO
887                        | OFPFW_NW_TOS) };
888     enum { OFPFW_TP = OFPFW_TP_SRC | OFPFW_TP_DST };
889     uint32_t wc;
890
891     wc = ntohl(m->wildcards) & OVSFW_ALL;
892     if (wc & OFPFW_DL_TYPE) {
893         m->dl_type = 0;
894
895         /* Can't sensibly match on network or transport headers if the
896          * data link type is unknown. */
897         wc |= OFPFW_NW | OFPFW_TP;
898         m->nw_src = m->nw_dst = m->nw_proto = m->nw_tos = 0;
899         m->tp_src = m->tp_dst = 0;
900     } else if (m->dl_type == htons(ETH_TYPE_IP)) {
901         if (wc & OFPFW_NW_PROTO) {
902             m->nw_proto = 0;
903
904             /* Can't sensibly match on transport headers if the network
905              * protocol is unknown. */
906             wc |= OFPFW_TP;
907             m->tp_src = m->tp_dst = 0;
908         } else if (m->nw_proto == IPPROTO_TCP ||
909                    m->nw_proto == IPPROTO_UDP ||
910                    m->nw_proto == IPPROTO_ICMP) {
911             if (wc & OFPFW_TP_SRC) {
912                 m->tp_src = 0;
913             }
914             if (wc & OFPFW_TP_DST) {
915                 m->tp_dst = 0;
916             }
917         } else {
918             /* Transport layer fields will always be extracted as zeros, so we
919              * can do an exact-match on those values.  */
920             wc &= ~OFPFW_TP;
921             m->tp_src = m->tp_dst = 0;
922         }
923         if (wc & OFPFW_NW_SRC_MASK) {
924             m->nw_src &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_SRC_SHIFT);
925         }
926         if (wc & OFPFW_NW_DST_MASK) {
927             m->nw_dst &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_DST_SHIFT);
928         }
929         if (wc & OFPFW_NW_TOS) {
930             m->nw_tos = 0;
931         } else {
932             m->nw_tos &= IP_DSCP_MASK;
933         }
934     } else if (m->dl_type == htons(ETH_TYPE_ARP)) {
935         if (wc & OFPFW_NW_PROTO) {
936             m->nw_proto = 0;
937         }
938         if (wc & OFPFW_NW_SRC_MASK) {
939             m->nw_src &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_SRC_SHIFT);
940         }
941         if (wc & OFPFW_NW_DST_MASK) {
942             m->nw_dst &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_DST_SHIFT);
943         }
944         m->tp_src = m->tp_dst = m->nw_tos = 0;
945     } else {
946         /* Network and transport layer fields will always be extracted as
947          * zeros, so we can do an exact-match on those values. */
948         wc &= ~(OFPFW_NW | OFPFW_TP);
949         m->nw_proto = m->nw_src = m->nw_dst = m->nw_tos = 0;
950         m->tp_src = m->tp_dst = 0;
951     }
952     if (wc & OFPFW_DL_SRC) {
953         memset(m->dl_src, 0, sizeof m->dl_src);
954     }
955     if (wc & OFPFW_DL_DST) {
956         memset(m->dl_dst, 0, sizeof m->dl_dst);
957     }
958     m->wildcards = htonl(wc);
959 }
960
961 /* Returns a string that describes 'match' in a very literal way, without
962  * interpreting its contents except in a very basic fashion.  The returned
963  * string is intended to be fixed-length, so that it is easy to see differences
964  * between two such strings if one is put above another.  This is useful for
965  * describing changes made by normalize_match().
966  *
967  * The caller must free the returned string (with free()). */
968 char *
969 ofp_match_to_literal_string(const struct ofp_match *match)
970 {
971     return xasprintf("wildcards=%#10"PRIx32" "
972                      " in_port=%5"PRId16" "
973                      " dl_src="ETH_ADDR_FMT" "
974                      " dl_dst="ETH_ADDR_FMT" "
975                      " dl_vlan=%5"PRId16" "
976                      " dl_vlan_pcp=%3"PRId8" "
977                      " dl_type=%#6"PRIx16" "
978                      " nw_tos=%#4"PRIx8" "
979                      " nw_proto=%#4"PRIx16" "
980                      " nw_src=%#10"PRIx32" "
981                      " nw_dst=%#10"PRIx32" "
982                      " tp_src=%5"PRId16" "
983                      " tp_dst=%5"PRId16,
984                      ntohl(match->wildcards),
985                      ntohs(match->in_port),
986                      ETH_ADDR_ARGS(match->dl_src),
987                      ETH_ADDR_ARGS(match->dl_dst),
988                      ntohs(match->dl_vlan),
989                      match->dl_vlan_pcp,
990                      ntohs(match->dl_type),
991                      match->nw_tos,
992                      match->nw_proto,
993                      ntohl(match->nw_src),
994                      ntohl(match->nw_dst),
995                      ntohs(match->tp_src),
996                      ntohs(match->tp_dst));
997 }
998
999 static uint32_t
1000 vendor_code_to_id(uint8_t code)
1001 {
1002     switch (code) {
1003 #define OFPUTIL_VENDOR(NAME, VENDOR_ID) case NAME: return VENDOR_ID;
1004         OFPUTIL_VENDORS
1005 #undef OFPUTIL_VENDOR
1006     default:
1007         return UINT32_MAX;
1008     }
1009 }
1010
1011 /* Creates and returns an OpenFlow message of type OFPT_ERROR with the error
1012  * information taken from 'error', whose encoding must be as described in the
1013  * large comment in ofp-util.h.  If 'oh' is nonnull, then the error will use
1014  * oh->xid as its transaction ID, and it will include up to the first 64 bytes
1015  * of 'oh'.
1016  *
1017  * Returns NULL if 'error' is not an OpenFlow error code. */
1018 struct ofpbuf *
1019 make_ofp_error_msg(int error, const struct ofp_header *oh)
1020 {
1021     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1022
1023     struct ofpbuf *buf;
1024     const void *data;
1025     size_t len;
1026     uint8_t vendor;
1027     uint16_t type;
1028     uint16_t code;
1029     ovs_be32 xid;
1030
1031     if (!is_ofp_error(error)) {
1032         /* We format 'error' with strerror() here since it seems likely to be
1033          * a system errno value. */
1034         VLOG_WARN_RL(&rl, "invalid OpenFlow error code %d (%s)",
1035                      error, strerror(error));
1036         return NULL;
1037     }
1038
1039     if (oh) {
1040         xid = oh->xid;
1041         data = oh;
1042         len = ntohs(oh->length);
1043         if (len > 64) {
1044             len = 64;
1045         }
1046     } else {
1047         xid = 0;
1048         data = NULL;
1049         len = 0;
1050     }
1051
1052     vendor = get_ofp_err_vendor(error);
1053     type = get_ofp_err_type(error);
1054     code = get_ofp_err_code(error);
1055     if (vendor == OFPUTIL_VENDOR_OPENFLOW) {
1056         struct ofp_error_msg *oem;
1057
1058         oem = make_openflow_xid(len + sizeof *oem, OFPT_ERROR, xid, &buf);
1059         oem->type = htons(type);
1060         oem->code = htons(code);
1061     } else {
1062         struct ofp_error_msg *oem;
1063         struct nx_vendor_error *nve;
1064         uint32_t vendor_id;
1065
1066         vendor_id = vendor_code_to_id(vendor);
1067         if (vendor_id == UINT32_MAX) {
1068             VLOG_WARN_RL(&rl, "error %x contains invalid vendor code %d",
1069                          error, vendor);
1070             return NULL;
1071         }
1072
1073         oem = make_openflow_xid(len + sizeof *oem + sizeof *nve,
1074                                 OFPT_ERROR, xid, &buf);
1075         oem->type = htons(NXET_VENDOR);
1076         oem->code = htons(NXVC_VENDOR_ERROR);
1077
1078         nve = ofpbuf_put_uninit(buf, sizeof *nve);
1079         nve->vendor = htonl(vendor_id);
1080         nve->type = htons(type);
1081         nve->code = htons(code);
1082     }
1083
1084     if (len) {
1085         ofpbuf_put(buf, data, len);
1086     }
1087
1088     return buf;
1089 }
1090
1091 /* Attempts to pull 'actions_len' bytes from the front of 'b'.  Returns 0 if
1092  * successful, otherwise an OpenFlow error.
1093  *
1094  * If successful, the first action is stored in '*actionsp' and the number of
1095  * "union ofp_action" size elements into '*n_actionsp'.  Otherwise NULL and 0
1096  * are stored, respectively.
1097  *
1098  * This function does not check that the actions are valid (the caller should
1099  * do so, with validate_actions()).  The caller is also responsible for making
1100  * sure that 'b->data' is initially aligned appropriately for "union
1101  * ofp_action". */
1102 int
1103 ofputil_pull_actions(struct ofpbuf *b, unsigned int actions_len,
1104                      union ofp_action **actionsp, size_t *n_actionsp)
1105 {
1106     if (actions_len % OFP_ACTION_ALIGN != 0) {
1107         VLOG_DBG_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
1108                     "is not a multiple of %d", actions_len, OFP_ACTION_ALIGN);
1109         goto error;
1110     }
1111
1112     *actionsp = ofpbuf_try_pull(b, actions_len);
1113     if (*actionsp == NULL) {
1114         VLOG_DBG_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
1115                     "exceeds remaining message length (%zu)",
1116                     actions_len, b->size);
1117         goto error;
1118     }
1119
1120     *n_actionsp = actions_len / OFP_ACTION_ALIGN;
1121     return 0;
1122
1123 error:
1124     *actionsp = NULL;
1125     *n_actionsp = 0;
1126     return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1127 }