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