208eabb5c56844efbaf9921f2ae1301806a74ac9
[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_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 cls_rule *rule,
332               size_t actions_len)
333 {
334     struct ofp_flow_mod *ofm;
335     size_t size = sizeof *ofm + actions_len;
336     struct ofpbuf *out = ofpbuf_new(size);
337     ofm = ofpbuf_put_zeros(out, sizeof *ofm);
338     ofm->header.version = OFP_VERSION;
339     ofm->header.type = OFPT_FLOW_MOD;
340     ofm->header.length = htons(size);
341     ofm->cookie = 0;
342     ofm->priority = htons(MIN(rule->priority, UINT16_MAX));
343     ofputil_cls_rule_to_match(rule, NXFF_OPENFLOW10, &ofm->match);
344     ofm->command = htons(command);
345     return out;
346 }
347
348 struct ofpbuf *
349 make_add_flow(const struct cls_rule *rule, uint32_t buffer_id,
350               uint16_t idle_timeout, size_t actions_len)
351 {
352     struct ofpbuf *out = make_flow_mod(OFPFC_ADD, rule, actions_len);
353     struct ofp_flow_mod *ofm = out->data;
354     ofm->idle_timeout = htons(idle_timeout);
355     ofm->hard_timeout = htons(OFP_FLOW_PERMANENT);
356     ofm->buffer_id = htonl(buffer_id);
357     return out;
358 }
359
360 struct ofpbuf *
361 make_del_flow(const struct cls_rule *rule)
362 {
363     struct ofpbuf *out = make_flow_mod(OFPFC_DELETE_STRICT, rule, 0);
364     struct ofp_flow_mod *ofm = out->data;
365     ofm->out_port = htons(OFPP_NONE);
366     return out;
367 }
368
369 struct ofpbuf *
370 make_add_simple_flow(const struct cls_rule *rule,
371                      uint32_t buffer_id, uint16_t out_port,
372                      uint16_t idle_timeout)
373 {
374     if (out_port != OFPP_NONE) {
375         struct ofp_action_output *oao;
376         struct ofpbuf *buffer;
377
378         buffer = make_add_flow(rule, buffer_id, idle_timeout, sizeof *oao);
379         oao = ofpbuf_put_zeros(buffer, sizeof *oao);
380         oao->type = htons(OFPAT_OUTPUT);
381         oao->len = htons(sizeof *oao);
382         oao->port = htons(out_port);
383         return buffer;
384     } else {
385         return make_add_flow(rule, buffer_id, idle_timeout, 0);
386     }
387 }
388
389 struct ofpbuf *
390 make_packet_in(uint32_t buffer_id, uint16_t in_port, uint8_t reason,
391                const struct ofpbuf *payload, int max_send_len)
392 {
393     struct ofp_packet_in *opi;
394     struct ofpbuf *buf;
395     int send_len;
396
397     send_len = MIN(max_send_len, payload->size);
398     buf = ofpbuf_new(sizeof *opi + send_len);
399     opi = put_openflow_xid(offsetof(struct ofp_packet_in, data),
400                            OFPT_PACKET_IN, 0, buf);
401     opi->buffer_id = htonl(buffer_id);
402     opi->total_len = htons(payload->size);
403     opi->in_port = htons(in_port);
404     opi->reason = reason;
405     ofpbuf_put(buf, payload->data, send_len);
406     update_openflow_length(buf);
407
408     return buf;
409 }
410
411 struct ofpbuf *
412 make_packet_out(const struct ofpbuf *packet, uint32_t buffer_id,
413                 uint16_t in_port,
414                 const struct ofp_action_header *actions, size_t n_actions)
415 {
416     size_t actions_len = n_actions * sizeof *actions;
417     struct ofp_packet_out *opo;
418     size_t size = sizeof *opo + actions_len + (packet ? packet->size : 0);
419     struct ofpbuf *out = ofpbuf_new(size);
420
421     opo = ofpbuf_put_uninit(out, sizeof *opo);
422     opo->header.version = OFP_VERSION;
423     opo->header.type = OFPT_PACKET_OUT;
424     opo->header.length = htons(size);
425     opo->header.xid = htonl(0);
426     opo->buffer_id = htonl(buffer_id);
427     opo->in_port = htons(in_port == ODPP_LOCAL ? OFPP_LOCAL : in_port);
428     opo->actions_len = htons(actions_len);
429     ofpbuf_put(out, actions, actions_len);
430     if (packet) {
431         ofpbuf_put(out, packet->data, packet->size);
432     }
433     return out;
434 }
435
436 struct ofpbuf *
437 make_unbuffered_packet_out(const struct ofpbuf *packet,
438                            uint16_t in_port, uint16_t out_port)
439 {
440     struct ofp_action_output action;
441     action.type = htons(OFPAT_OUTPUT);
442     action.len = htons(sizeof action);
443     action.port = htons(out_port);
444     return make_packet_out(packet, UINT32_MAX, in_port,
445                            (struct ofp_action_header *) &action, 1);
446 }
447
448 struct ofpbuf *
449 make_buffered_packet_out(uint32_t buffer_id,
450                          uint16_t in_port, uint16_t out_port)
451 {
452     if (out_port != OFPP_NONE) {
453         struct ofp_action_output action;
454         action.type = htons(OFPAT_OUTPUT);
455         action.len = htons(sizeof action);
456         action.port = htons(out_port);
457         return make_packet_out(NULL, buffer_id, in_port,
458                                (struct ofp_action_header *) &action, 1);
459     } else {
460         return make_packet_out(NULL, buffer_id, in_port, NULL, 0);
461     }
462 }
463
464 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
465 struct ofpbuf *
466 make_echo_request(void)
467 {
468     struct ofp_header *rq;
469     struct ofpbuf *out = ofpbuf_new(sizeof *rq);
470     rq = ofpbuf_put_uninit(out, sizeof *rq);
471     rq->version = OFP_VERSION;
472     rq->type = OFPT_ECHO_REQUEST;
473     rq->length = htons(sizeof *rq);
474     rq->xid = htonl(0);
475     return out;
476 }
477
478 /* Creates and returns an OFPT_ECHO_REPLY message matching the
479  * OFPT_ECHO_REQUEST message in 'rq'. */
480 struct ofpbuf *
481 make_echo_reply(const struct ofp_header *rq)
482 {
483     size_t size = ntohs(rq->length);
484     struct ofpbuf *out = ofpbuf_new(size);
485     struct ofp_header *reply = ofpbuf_put(out, rq, size);
486     reply->type = OFPT_ECHO_REPLY;
487     return out;
488 }
489
490 static int
491 check_message_type(uint8_t got_type, uint8_t want_type)
492 {
493     if (got_type != want_type) {
494         char *want_type_name = ofp_message_type_to_string(want_type);
495         char *got_type_name = ofp_message_type_to_string(got_type);
496         VLOG_WARN_RL(&bad_ofmsg_rl,
497                      "received bad message type %s (expected %s)",
498                      got_type_name, want_type_name);
499         free(want_type_name);
500         free(got_type_name);
501         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE);
502     }
503     return 0;
504 }
505
506 /* Checks that 'msg' has type 'type' and that it is exactly 'size' bytes long.
507  * Returns 0 if the checks pass, otherwise an OpenFlow error code (produced
508  * with ofp_mkerr()). */
509 int
510 check_ofp_message(const struct ofp_header *msg, uint8_t type, size_t size)
511 {
512     size_t got_size;
513     int error;
514
515     error = check_message_type(msg->type, type);
516     if (error) {
517         return error;
518     }
519
520     got_size = ntohs(msg->length);
521     if (got_size != size) {
522         char *type_name = ofp_message_type_to_string(type);
523         VLOG_WARN_RL(&bad_ofmsg_rl,
524                      "received %s message of length %zu (expected %zu)",
525                      type_name, got_size, size);
526         free(type_name);
527         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
528     }
529
530     return 0;
531 }
532
533 /* Checks that 'msg' has type 'type' and that 'msg' is 'size' plus a
534  * nonnegative integer multiple of 'array_elt_size' bytes long.  Returns 0 if
535  * the checks pass, otherwise an OpenFlow error code (produced with
536  * ofp_mkerr()).
537  *
538  * If 'n_array_elts' is nonnull, then '*n_array_elts' is set to the number of
539  * 'array_elt_size' blocks in 'msg' past the first 'min_size' bytes, when
540  * successful. */
541 int
542 check_ofp_message_array(const struct ofp_header *msg, uint8_t type,
543                         size_t min_size, size_t array_elt_size,
544                         size_t *n_array_elts)
545 {
546     size_t got_size;
547     int error;
548
549     assert(array_elt_size);
550
551     error = check_message_type(msg->type, type);
552     if (error) {
553         return error;
554     }
555
556     got_size = ntohs(msg->length);
557     if (got_size < min_size) {
558         char *type_name = ofp_message_type_to_string(type);
559         VLOG_WARN_RL(&bad_ofmsg_rl, "received %s message of length %zu "
560                      "(expected at least %zu)",
561                      type_name, got_size, min_size);
562         free(type_name);
563         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
564     }
565     if ((got_size - min_size) % array_elt_size) {
566         char *type_name = ofp_message_type_to_string(type);
567         VLOG_WARN_RL(&bad_ofmsg_rl,
568                      "received %s message of bad length %zu: the "
569                      "excess over %zu (%zu) is not evenly divisible by %zu "
570                      "(remainder is %zu)",
571                      type_name, got_size, min_size, got_size - min_size,
572                      array_elt_size, (got_size - min_size) % array_elt_size);
573         free(type_name);
574         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
575     }
576     if (n_array_elts) {
577         *n_array_elts = (got_size - min_size) / array_elt_size;
578     }
579     return 0;
580 }
581
582 const struct ofp_flow_stats *
583 flow_stats_first(struct flow_stats_iterator *iter,
584                  const struct ofp_stats_reply *osr)
585 {
586     iter->pos = osr->body;
587     iter->end = osr->body + (ntohs(osr->header.length)
588                              - offsetof(struct ofp_stats_reply, body));
589     return flow_stats_next(iter);
590 }
591
592 const struct ofp_flow_stats *
593 flow_stats_next(struct flow_stats_iterator *iter)
594 {
595     ptrdiff_t bytes_left = iter->end - iter->pos;
596     const struct ofp_flow_stats *fs;
597     size_t length;
598
599     if (bytes_left < sizeof *fs) {
600         if (bytes_left != 0) {
601             VLOG_WARN_RL(&bad_ofmsg_rl,
602                          "%td leftover bytes in flow stats reply", bytes_left);
603         }
604         return NULL;
605     }
606
607     fs = (const void *) iter->pos;
608     length = ntohs(fs->length);
609     if (length < sizeof *fs) {
610         VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu is shorter than "
611                      "min %zu", length, sizeof *fs);
612         return NULL;
613     } else if (length > bytes_left) {
614         VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu but only %td "
615                      "bytes left", length, bytes_left);
616         return NULL;
617     } else if ((length - sizeof *fs) % sizeof fs->actions[0]) {
618         VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu has %zu bytes "
619                      "left over in final action", length,
620                      (length - sizeof *fs) % sizeof fs->actions[0]);
621         return NULL;
622     }
623     iter->pos += length;
624     return fs;
625 }
626
627 static int
628 check_action_exact_len(const union ofp_action *a, unsigned int len,
629                        unsigned int required_len)
630 {
631     if (len != required_len) {
632         VLOG_DBG_RL(&bad_ofmsg_rl,
633                     "action %u has invalid length %"PRIu16" (must be %u)\n",
634                     a->type, ntohs(a->header.len), required_len);
635         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
636     }
637     return 0;
638 }
639
640 /* Checks that 'port' is a valid output port for the OFPAT_OUTPUT action, given
641  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
642  * 'port' is valid, otherwise an ofp_mkerr() return code. */
643 static int
644 check_output_port(uint16_t port, int max_ports)
645 {
646     switch (port) {
647     case OFPP_IN_PORT:
648     case OFPP_TABLE:
649     case OFPP_NORMAL:
650     case OFPP_FLOOD:
651     case OFPP_ALL:
652     case OFPP_CONTROLLER:
653     case OFPP_LOCAL:
654         return 0;
655
656     default:
657         if (port < max_ports) {
658             return 0;
659         }
660         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown output port %x", port);
661         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
662     }
663 }
664
665 /* Checks that 'action' is a valid OFPAT_ENQUEUE action, given that the switch
666  * will never have more than 'max_ports' ports.  Returns 0 if 'port' is valid,
667  * otherwise an ofp_mkerr() return code. */
668 static int
669 check_enqueue_action(const union ofp_action *a, unsigned int len,
670                      int max_ports)
671 {
672     const struct ofp_action_enqueue *oae;
673     uint16_t port;
674     int error;
675
676     error = check_action_exact_len(a, len, 16);
677     if (error) {
678         return error;
679     }
680
681     oae = (const struct ofp_action_enqueue *) a;
682     port = ntohs(oae->port);
683     if (port < max_ports || port == OFPP_IN_PORT) {
684         return 0;
685     }
686     VLOG_WARN_RL(&bad_ofmsg_rl, "unknown enqueue port %x", port);
687     return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
688 }
689
690 static int
691 check_nicira_action(const union ofp_action *a, unsigned int len,
692                     const struct flow *flow)
693 {
694     const struct nx_action_header *nah;
695     int error;
696
697     if (len < 16) {
698         VLOG_DBG_RL(&bad_ofmsg_rl,
699                     "Nicira vendor action only %u bytes", len);
700         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
701     }
702     nah = (const struct nx_action_header *) a;
703
704     switch (ntohs(nah->subtype)) {
705     case NXAST_RESUBMIT:
706     case NXAST_SET_TUNNEL:
707     case NXAST_DROP_SPOOFED_ARP:
708     case NXAST_SET_QUEUE:
709     case NXAST_POP_QUEUE:
710         return check_action_exact_len(a, len, 16);
711
712     case NXAST_REG_MOVE:
713         error = check_action_exact_len(a, len,
714                                        sizeof(struct nx_action_reg_move));
715         if (error) {
716             return error;
717         }
718         return nxm_check_reg_move((const struct nx_action_reg_move *) a, flow);
719
720     case NXAST_REG_LOAD:
721         error = check_action_exact_len(a, len,
722                                        sizeof(struct nx_action_reg_load));
723         if (error) {
724             return error;
725         }
726         return nxm_check_reg_load((const struct nx_action_reg_load *) a, flow);
727
728     case NXAST_NOTE:
729         return 0;
730
731     default:
732         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR_TYPE);
733     }
734 }
735
736 static int
737 check_action(const union ofp_action *a, unsigned int len,
738              const struct flow *flow, int max_ports)
739 {
740     int error;
741
742     switch (ntohs(a->type)) {
743     case OFPAT_OUTPUT:
744         error = check_action_exact_len(a, len, 8);
745         if (error) {
746             return error;
747         }
748         return check_output_port(ntohs(a->output.port), max_ports);
749
750     case OFPAT_SET_VLAN_VID:
751         error = check_action_exact_len(a, len, 8);
752         if (error) {
753             return error;
754         }
755         if (a->vlan_vid.vlan_vid & ~htons(0xfff)) {
756             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
757         }
758         return 0;
759
760     case OFPAT_SET_VLAN_PCP:
761         error = check_action_exact_len(a, len, 8);
762         if (error) {
763             return error;
764         }
765         if (a->vlan_vid.vlan_vid & ~7) {
766             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
767         }
768         return 0;
769
770     case OFPAT_STRIP_VLAN:
771     case OFPAT_SET_NW_SRC:
772     case OFPAT_SET_NW_DST:
773     case OFPAT_SET_NW_TOS:
774     case OFPAT_SET_TP_SRC:
775     case OFPAT_SET_TP_DST:
776         return check_action_exact_len(a, len, 8);
777
778     case OFPAT_SET_DL_SRC:
779     case OFPAT_SET_DL_DST:
780         return check_action_exact_len(a, len, 16);
781
782     case OFPAT_VENDOR:
783         return (a->vendor.vendor == htonl(NX_VENDOR_ID)
784                 ? check_nicira_action(a, len, flow)
785                 : ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR));
786
787     case OFPAT_ENQUEUE:
788         return check_enqueue_action(a, len, max_ports);
789
790     default:
791         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown action type %"PRIu16,
792                 ntohs(a->type));
793         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_TYPE);
794     }
795 }
796
797 int
798 validate_actions(const union ofp_action *actions, size_t n_actions,
799                  const struct flow *flow, int max_ports)
800 {
801     size_t i;
802
803     for (i = 0; i < n_actions; ) {
804         const union ofp_action *a = &actions[i];
805         unsigned int len = ntohs(a->header.len);
806         unsigned int n_slots = len / OFP_ACTION_ALIGN;
807         unsigned int slots_left = &actions[n_actions] - a;
808         int error;
809
810         if (n_slots > slots_left) {
811             VLOG_DBG_RL(&bad_ofmsg_rl,
812                         "action requires %u slots but only %u remain",
813                         n_slots, slots_left);
814             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
815         } else if (!len) {
816             VLOG_DBG_RL(&bad_ofmsg_rl, "action has invalid length 0");
817             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
818         } else if (len % OFP_ACTION_ALIGN) {
819             VLOG_DBG_RL(&bad_ofmsg_rl, "action length %u is not a multiple "
820                         "of %d", len, OFP_ACTION_ALIGN);
821             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
822         }
823
824         error = check_action(a, len, flow, max_ports);
825         if (error) {
826             return error;
827         }
828         i += n_slots;
829     }
830     return 0;
831 }
832
833 /* Returns true if 'action' outputs to 'port' (which must be in network byte
834  * order), false otherwise. */
835 bool
836 action_outputs_to_port(const union ofp_action *action, uint16_t port)
837 {
838     switch (ntohs(action->type)) {
839     case OFPAT_OUTPUT:
840         return action->output.port == port;
841     case OFPAT_ENQUEUE:
842         return ((const struct ofp_action_enqueue *) action)->port == port;
843     default:
844         return false;
845     }
846 }
847
848 /* The set of actions must either come from a trusted source or have been
849  * previously validated with validate_actions(). */
850 const union ofp_action *
851 actions_first(struct actions_iterator *iter,
852               const union ofp_action *oa, size_t n_actions)
853 {
854     iter->pos = oa;
855     iter->end = oa + n_actions;
856     return actions_next(iter);
857 }
858
859 const union ofp_action *
860 actions_next(struct actions_iterator *iter)
861 {
862     if (iter->pos != iter->end) {
863         const union ofp_action *a = iter->pos;
864         unsigned int len = ntohs(a->header.len);
865         iter->pos += len / OFP_ACTION_ALIGN;
866         return a;
867     } else {
868         return NULL;
869     }
870 }
871
872 void
873 normalize_match(struct ofp_match *m)
874 {
875     enum { OFPFW_NW = (OFPFW_NW_SRC_MASK | OFPFW_NW_DST_MASK | OFPFW_NW_PROTO
876                        | OFPFW_NW_TOS) };
877     enum { OFPFW_TP = OFPFW_TP_SRC | OFPFW_TP_DST };
878     uint32_t wc;
879
880     wc = ntohl(m->wildcards) & OVSFW_ALL;
881     if (wc & OFPFW_DL_TYPE) {
882         m->dl_type = 0;
883
884         /* Can't sensibly match on network or transport headers if the
885          * data link type is unknown. */
886         wc |= OFPFW_NW | OFPFW_TP;
887         m->nw_src = m->nw_dst = m->nw_proto = m->nw_tos = 0;
888         m->tp_src = m->tp_dst = 0;
889     } else if (m->dl_type == htons(ETH_TYPE_IP)) {
890         if (wc & OFPFW_NW_PROTO) {
891             m->nw_proto = 0;
892
893             /* Can't sensibly match on transport headers if the network
894              * protocol is unknown. */
895             wc |= OFPFW_TP;
896             m->tp_src = m->tp_dst = 0;
897         } else if (m->nw_proto == IPPROTO_TCP ||
898                    m->nw_proto == IPPROTO_UDP ||
899                    m->nw_proto == IPPROTO_ICMP) {
900             if (wc & OFPFW_TP_SRC) {
901                 m->tp_src = 0;
902             }
903             if (wc & OFPFW_TP_DST) {
904                 m->tp_dst = 0;
905             }
906         } else {
907             /* Transport layer fields will always be extracted as zeros, so we
908              * can do an exact-match on those values.  */
909             wc &= ~OFPFW_TP;
910             m->tp_src = m->tp_dst = 0;
911         }
912         if (wc & OFPFW_NW_SRC_MASK) {
913             m->nw_src &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_SRC_SHIFT);
914         }
915         if (wc & OFPFW_NW_DST_MASK) {
916             m->nw_dst &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_DST_SHIFT);
917         }
918         if (wc & OFPFW_NW_TOS) {
919             m->nw_tos = 0;
920         } else {
921             m->nw_tos &= IP_DSCP_MASK;
922         }
923     } else if (m->dl_type == htons(ETH_TYPE_ARP)) {
924         if (wc & OFPFW_NW_PROTO) {
925             m->nw_proto = 0;
926         }
927         if (wc & OFPFW_NW_SRC_MASK) {
928             m->nw_src &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_SRC_SHIFT);
929         }
930         if (wc & OFPFW_NW_DST_MASK) {
931             m->nw_dst &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_DST_SHIFT);
932         }
933         m->tp_src = m->tp_dst = m->nw_tos = 0;
934     } else {
935         /* Network and transport layer fields will always be extracted as
936          * zeros, so we can do an exact-match on those values. */
937         wc &= ~(OFPFW_NW | OFPFW_TP);
938         m->nw_proto = m->nw_src = m->nw_dst = m->nw_tos = 0;
939         m->tp_src = m->tp_dst = 0;
940     }
941     if (wc & OFPFW_DL_SRC) {
942         memset(m->dl_src, 0, sizeof m->dl_src);
943     }
944     if (wc & OFPFW_DL_DST) {
945         memset(m->dl_dst, 0, sizeof m->dl_dst);
946     }
947     m->wildcards = htonl(wc);
948 }
949
950 /* Returns a string that describes 'match' in a very literal way, without
951  * interpreting its contents except in a very basic fashion.  The returned
952  * string is intended to be fixed-length, so that it is easy to see differences
953  * between two such strings if one is put above another.  This is useful for
954  * describing changes made by normalize_match().
955  *
956  * The caller must free the returned string (with free()). */
957 char *
958 ofp_match_to_literal_string(const struct ofp_match *match)
959 {
960     return xasprintf("wildcards=%#10"PRIx32" "
961                      " in_port=%5"PRId16" "
962                      " dl_src="ETH_ADDR_FMT" "
963                      " dl_dst="ETH_ADDR_FMT" "
964                      " dl_vlan=%5"PRId16" "
965                      " dl_vlan_pcp=%3"PRId8" "
966                      " dl_type=%#6"PRIx16" "
967                      " nw_tos=%#4"PRIx8" "
968                      " nw_proto=%#4"PRIx16" "
969                      " nw_src=%#10"PRIx32" "
970                      " nw_dst=%#10"PRIx32" "
971                      " tp_src=%5"PRId16" "
972                      " tp_dst=%5"PRId16,
973                      ntohl(match->wildcards),
974                      ntohs(match->in_port),
975                      ETH_ADDR_ARGS(match->dl_src),
976                      ETH_ADDR_ARGS(match->dl_dst),
977                      ntohs(match->dl_vlan),
978                      match->dl_vlan_pcp,
979                      ntohs(match->dl_type),
980                      match->nw_tos,
981                      match->nw_proto,
982                      ntohl(match->nw_src),
983                      ntohl(match->nw_dst),
984                      ntohs(match->tp_src),
985                      ntohs(match->tp_dst));
986 }
987
988 static uint32_t
989 vendor_code_to_id(uint8_t code)
990 {
991     switch (code) {
992 #define OFPUTIL_VENDOR(NAME, VENDOR_ID) case NAME: return VENDOR_ID;
993         OFPUTIL_VENDORS
994 #undef OFPUTIL_VENDOR
995     default:
996         return UINT32_MAX;
997     }
998 }
999
1000 /* Creates and returns an OpenFlow message of type OFPT_ERROR with the error
1001  * information taken from 'error', whose encoding must be as described in the
1002  * large comment in ofp-util.h.  If 'oh' is nonnull, then the error will use
1003  * oh->xid as its transaction ID, and it will include up to the first 64 bytes
1004  * of 'oh'.
1005  *
1006  * Returns NULL if 'error' is not an OpenFlow error code. */
1007 struct ofpbuf *
1008 make_ofp_error_msg(int error, const struct ofp_header *oh)
1009 {
1010     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1011
1012     struct ofpbuf *buf;
1013     const void *data;
1014     size_t len;
1015     uint8_t vendor;
1016     uint16_t type;
1017     uint16_t code;
1018     ovs_be32 xid;
1019
1020     if (!is_ofp_error(error)) {
1021         /* We format 'error' with strerror() here since it seems likely to be
1022          * a system errno value. */
1023         VLOG_WARN_RL(&rl, "invalid OpenFlow error code %d (%s)",
1024                      error, strerror(error));
1025         return NULL;
1026     }
1027
1028     if (oh) {
1029         xid = oh->xid;
1030         data = oh;
1031         len = ntohs(oh->length);
1032         if (len > 64) {
1033             len = 64;
1034         }
1035     } else {
1036         xid = 0;
1037         data = NULL;
1038         len = 0;
1039     }
1040
1041     vendor = get_ofp_err_vendor(error);
1042     type = get_ofp_err_type(error);
1043     code = get_ofp_err_code(error);
1044     if (vendor == OFPUTIL_VENDOR_OPENFLOW) {
1045         struct ofp_error_msg *oem;
1046
1047         oem = make_openflow_xid(len + sizeof *oem, OFPT_ERROR, xid, &buf);
1048         oem->type = htons(type);
1049         oem->code = htons(code);
1050     } else {
1051         struct ofp_error_msg *oem;
1052         struct nx_vendor_error *nve;
1053         uint32_t vendor_id;
1054
1055         vendor_id = vendor_code_to_id(vendor);
1056         if (vendor_id == UINT32_MAX) {
1057             VLOG_WARN_RL(&rl, "error %x contains invalid vendor code %d",
1058                          error, vendor);
1059             return NULL;
1060         }
1061
1062         oem = make_openflow_xid(len + sizeof *oem + sizeof *nve,
1063                                 OFPT_ERROR, xid, &buf);
1064         oem->type = htons(NXET_VENDOR);
1065         oem->code = htons(NXVC_VENDOR_ERROR);
1066
1067         nve = ofpbuf_put_uninit(buf, sizeof *nve);
1068         nve->vendor = htonl(vendor_id);
1069         nve->type = htons(type);
1070         nve->code = htons(code);
1071     }
1072
1073     if (len) {
1074         ofpbuf_put(buf, data, len);
1075     }
1076
1077     return buf;
1078 }
1079
1080 /* Attempts to pull 'actions_len' bytes from the front of 'b'.  Returns 0 if
1081  * successful, otherwise an OpenFlow error.
1082  *
1083  * If successful, the first action is stored in '*actionsp' and the number of
1084  * "union ofp_action" size elements into '*n_actionsp'.  Otherwise NULL and 0
1085  * are stored, respectively.
1086  *
1087  * This function does not check that the actions are valid (the caller should
1088  * do so, with validate_actions()).  The caller is also responsible for making
1089  * sure that 'b->data' is initially aligned appropriately for "union
1090  * ofp_action". */
1091 int
1092 ofputil_pull_actions(struct ofpbuf *b, unsigned int actions_len,
1093                      union ofp_action **actionsp, size_t *n_actionsp)
1094 {
1095     if (actions_len % OFP_ACTION_ALIGN != 0) {
1096         VLOG_DBG_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
1097                     "is not a multiple of %d", actions_len, OFP_ACTION_ALIGN);
1098         goto error;
1099     }
1100
1101     *actionsp = ofpbuf_try_pull(b, actions_len);
1102     if (*actionsp == NULL) {
1103         VLOG_DBG_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
1104                     "exceeds remaining message length (%zu)",
1105                     actions_len, b->size);
1106         goto error;
1107     }
1108
1109     *n_actionsp = actions_len / OFP_ACTION_ALIGN;
1110     return 0;
1111
1112 error:
1113     *actionsp = NULL;
1114     *n_actionsp = 0;
1115     return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1116 }