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