nicira-ext: New Nicira vendor action NXAST_NOTE.
[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 static int
465 check_action_exact_len(const union ofp_action *a, unsigned int len,
466                        unsigned int required_len)
467 {
468     if (len != required_len) {
469         VLOG_DBG_RL(&bad_ofmsg_rl,
470                     "action %u has invalid length %"PRIu16" (must be %u)\n",
471                     a->type, ntohs(a->header.len), required_len);
472         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
473     }
474     return 0;
475 }
476
477 /* Checks that 'port' is a valid output port for the OFPAT_OUTPUT action, given
478  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
479  * 'port' is valid, otherwise an ofp_mkerr() return code. */
480 static int
481 check_output_port(uint16_t port, int max_ports)
482 {
483     switch (port) {
484     case OFPP_IN_PORT:
485     case OFPP_TABLE:
486     case OFPP_NORMAL:
487     case OFPP_FLOOD:
488     case OFPP_ALL:
489     case OFPP_CONTROLLER:
490     case OFPP_LOCAL:
491         return 0;
492
493     default:
494         if (port < max_ports) {
495             return 0;
496         }
497         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown output port %x", port);
498         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
499     }
500 }
501
502 /* Checks that 'action' is a valid OFPAT_ENQUEUE action, given that the switch
503  * will never have more than 'max_ports' ports.  Returns 0 if 'port' is valid,
504  * otherwise an ofp_mkerr() return code. */
505 static int
506 check_enqueue_action(const union ofp_action *a, unsigned int len,
507                      int max_ports)
508 {
509     const struct ofp_action_enqueue *oae;
510     uint16_t port;
511     int error;
512
513     error = check_action_exact_len(a, len, 16);
514     if (error) {
515         return error;
516     }
517
518     oae = (const struct ofp_action_enqueue *) a;
519     port = ntohs(oae->port);
520     if (port < max_ports || port == OFPP_IN_PORT) {
521         return 0;
522     }
523     VLOG_WARN_RL(&bad_ofmsg_rl, "unknown enqueue port %x", port);
524     return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
525 }
526
527 static int
528 check_nicira_action(const union ofp_action *a, unsigned int len,
529                     const struct flow *flow)
530 {
531     const struct nx_action_header *nah;
532     int error;
533
534     if (len < 16) {
535         VLOG_DBG_RL(&bad_ofmsg_rl,
536                     "Nicira vendor action only %u bytes", len);
537         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
538     }
539     nah = (const struct nx_action_header *) a;
540
541     switch (ntohs(nah->subtype)) {
542     case NXAST_RESUBMIT:
543     case NXAST_SET_TUNNEL:
544     case NXAST_DROP_SPOOFED_ARP:
545     case NXAST_SET_QUEUE:
546     case NXAST_POP_QUEUE:
547         return check_action_exact_len(a, len, 16);
548
549     case NXAST_REG_MOVE:
550         error = check_action_exact_len(a, len,
551                                        sizeof(struct nx_action_reg_move));
552         if (error) {
553             return error;
554         }
555         return nxm_check_reg_move((const struct nx_action_reg_move *) a, flow);
556
557     case NXAST_REG_LOAD:
558         error = check_action_exact_len(a, len,
559                                        sizeof(struct nx_action_reg_load));
560         if (error) {
561             return error;
562         }
563         return nxm_check_reg_load((const struct nx_action_reg_load *) a, flow);
564
565     case NXAST_NOTE:
566         return 0;
567
568     default:
569         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR_TYPE);
570     }
571 }
572
573 static int
574 check_action(const union ofp_action *a, unsigned int len,
575              const struct flow *flow, int max_ports)
576 {
577     int error;
578
579     switch (ntohs(a->type)) {
580     case OFPAT_OUTPUT:
581         error = check_action_exact_len(a, len, 8);
582         if (error) {
583             return error;
584         }
585         return check_output_port(ntohs(a->output.port), max_ports);
586
587     case OFPAT_SET_VLAN_VID:
588         error = check_action_exact_len(a, len, 8);
589         if (error) {
590             return error;
591         }
592         if (a->vlan_vid.vlan_vid & ~htons(0xfff)) {
593             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
594         }
595         return 0;
596
597     case OFPAT_SET_VLAN_PCP:
598         error = check_action_exact_len(a, len, 8);
599         if (error) {
600             return error;
601         }
602         if (a->vlan_vid.vlan_vid & ~7) {
603             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
604         }
605         return 0;
606
607     case OFPAT_STRIP_VLAN:
608     case OFPAT_SET_NW_SRC:
609     case OFPAT_SET_NW_DST:
610     case OFPAT_SET_NW_TOS:
611     case OFPAT_SET_TP_SRC:
612     case OFPAT_SET_TP_DST:
613         return check_action_exact_len(a, len, 8);
614
615     case OFPAT_SET_DL_SRC:
616     case OFPAT_SET_DL_DST:
617         return check_action_exact_len(a, len, 16);
618
619     case OFPAT_VENDOR:
620         return (a->vendor.vendor == htonl(NX_VENDOR_ID)
621                 ? check_nicira_action(a, len, flow)
622                 : ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR));
623
624     case OFPAT_ENQUEUE:
625         return check_enqueue_action(a, len, max_ports);
626
627     default:
628         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown action type %"PRIu16,
629                 ntohs(a->type));
630         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_TYPE);
631     }
632 }
633
634 int
635 validate_actions(const union ofp_action *actions, size_t n_actions,
636                  const struct flow *flow, int max_ports)
637 {
638     size_t i;
639
640     for (i = 0; i < n_actions; ) {
641         const union ofp_action *a = &actions[i];
642         unsigned int len = ntohs(a->header.len);
643         unsigned int n_slots = len / OFP_ACTION_ALIGN;
644         unsigned int slots_left = &actions[n_actions] - a;
645         int error;
646
647         if (n_slots > slots_left) {
648             VLOG_DBG_RL(&bad_ofmsg_rl,
649                         "action requires %u slots but only %u remain",
650                         n_slots, slots_left);
651             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
652         } else if (!len) {
653             VLOG_DBG_RL(&bad_ofmsg_rl, "action has invalid length 0");
654             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
655         } else if (len % OFP_ACTION_ALIGN) {
656             VLOG_DBG_RL(&bad_ofmsg_rl, "action length %u is not a multiple "
657                         "of %d", len, OFP_ACTION_ALIGN);
658             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
659         }
660
661         error = check_action(a, len, flow, max_ports);
662         if (error) {
663             return error;
664         }
665         i += n_slots;
666     }
667     return 0;
668 }
669
670 /* Returns true if 'action' outputs to 'port' (which must be in network byte
671  * order), false otherwise. */
672 bool
673 action_outputs_to_port(const union ofp_action *action, uint16_t port)
674 {
675     switch (ntohs(action->type)) {
676     case OFPAT_OUTPUT:
677         return action->output.port == port;
678     case OFPAT_ENQUEUE:
679         return ((const struct ofp_action_enqueue *) action)->port == port;
680     default:
681         return false;
682     }
683 }
684
685 /* The set of actions must either come from a trusted source or have been
686  * previously validated with validate_actions(). */
687 const union ofp_action *
688 actions_first(struct actions_iterator *iter,
689               const union ofp_action *oa, size_t n_actions)
690 {
691     iter->pos = oa;
692     iter->end = oa + n_actions;
693     return actions_next(iter);
694 }
695
696 const union ofp_action *
697 actions_next(struct actions_iterator *iter)
698 {
699     if (iter->pos != iter->end) {
700         const union ofp_action *a = iter->pos;
701         unsigned int len = ntohs(a->header.len);
702         iter->pos += len / OFP_ACTION_ALIGN;
703         return a;
704     } else {
705         return NULL;
706     }
707 }
708
709 void
710 normalize_match(struct ofp_match *m)
711 {
712     enum { OFPFW_NW = (OFPFW_NW_SRC_MASK | OFPFW_NW_DST_MASK | OFPFW_NW_PROTO
713                        | OFPFW_NW_TOS) };
714     enum { OFPFW_TP = OFPFW_TP_SRC | OFPFW_TP_DST };
715     uint32_t wc;
716
717     wc = ntohl(m->wildcards) & OVSFW_ALL;
718     if (wc & OFPFW_DL_TYPE) {
719         m->dl_type = 0;
720
721         /* Can't sensibly match on network or transport headers if the
722          * data link type is unknown. */
723         wc |= OFPFW_NW | OFPFW_TP;
724         m->nw_src = m->nw_dst = m->nw_proto = m->nw_tos = 0;
725         m->tp_src = m->tp_dst = 0;
726     } else if (m->dl_type == htons(ETH_TYPE_IP)) {
727         if (wc & OFPFW_NW_PROTO) {
728             m->nw_proto = 0;
729
730             /* Can't sensibly match on transport headers if the network
731              * protocol is unknown. */
732             wc |= OFPFW_TP;
733             m->tp_src = m->tp_dst = 0;
734         } else if (m->nw_proto == IPPROTO_TCP ||
735                    m->nw_proto == IPPROTO_UDP ||
736                    m->nw_proto == IPPROTO_ICMP) {
737             if (wc & OFPFW_TP_SRC) {
738                 m->tp_src = 0;
739             }
740             if (wc & OFPFW_TP_DST) {
741                 m->tp_dst = 0;
742             }
743         } else {
744             /* Transport layer fields will always be extracted as zeros, so we
745              * can do an exact-match on those values.  */
746             wc &= ~OFPFW_TP;
747             m->tp_src = m->tp_dst = 0;
748         }
749         if (wc & OFPFW_NW_SRC_MASK) {
750             m->nw_src &= flow_nw_bits_to_mask(wc, OFPFW_NW_SRC_SHIFT);
751         }
752         if (wc & OFPFW_NW_DST_MASK) {
753             m->nw_dst &= flow_nw_bits_to_mask(wc, OFPFW_NW_DST_SHIFT);
754         }
755         if (wc & OFPFW_NW_TOS) {
756             m->nw_tos = 0;
757         } else {
758             m->nw_tos &= IP_DSCP_MASK;
759         }
760     } else if (m->dl_type == htons(ETH_TYPE_ARP)) {
761         if (wc & OFPFW_NW_PROTO) {
762             m->nw_proto = 0;
763         }
764         if (wc & OFPFW_NW_SRC_MASK) {
765             m->nw_src &= flow_nw_bits_to_mask(wc, OFPFW_NW_SRC_SHIFT);
766         }
767         if (wc & OFPFW_NW_DST_MASK) {
768             m->nw_dst &= flow_nw_bits_to_mask(wc, OFPFW_NW_DST_SHIFT);
769         }
770         m->tp_src = m->tp_dst = m->nw_tos = 0;
771     } else {
772         /* Network and transport layer fields will always be extracted as
773          * zeros, so we can do an exact-match on those values. */
774         wc &= ~(OFPFW_NW | OFPFW_TP);
775         m->nw_proto = m->nw_src = m->nw_dst = m->nw_tos = 0;
776         m->tp_src = m->tp_dst = 0;
777     }
778     if (wc & OFPFW_DL_SRC) {
779         memset(m->dl_src, 0, sizeof m->dl_src);
780     }
781     if (wc & OFPFW_DL_DST) {
782         memset(m->dl_dst, 0, sizeof m->dl_dst);
783     }
784     m->wildcards = htonl(wc);
785 }
786
787 /* Returns a string that describes 'match' in a very literal way, without
788  * interpreting its contents except in a very basic fashion.  The returned
789  * string is intended to be fixed-length, so that it is easy to see differences
790  * between two such strings if one is put above another.  This is useful for
791  * describing changes made by normalize_match().
792  *
793  * The caller must free the returned string (with free()). */
794 char *
795 ofp_match_to_literal_string(const struct ofp_match *match)
796 {
797     return xasprintf("wildcards=%#10"PRIx32" "
798                      " in_port=%5"PRId16" "
799                      " dl_src="ETH_ADDR_FMT" "
800                      " dl_dst="ETH_ADDR_FMT" "
801                      " dl_vlan=%5"PRId16" "
802                      " dl_vlan_pcp=%3"PRId8" "
803                      " dl_type=%#6"PRIx16" "
804                      " nw_tos=%#4"PRIx8" "
805                      " nw_proto=%#4"PRIx16" "
806                      " nw_src=%#10"PRIx32" "
807                      " nw_dst=%#10"PRIx32" "
808                      " tp_src=%5"PRId16" "
809                      " tp_dst=%5"PRId16,
810                      ntohl(match->wildcards),
811                      ntohs(match->in_port),
812                      ETH_ADDR_ARGS(match->dl_src),
813                      ETH_ADDR_ARGS(match->dl_dst),
814                      ntohs(match->dl_vlan),
815                      match->dl_vlan_pcp,
816                      ntohs(match->dl_type),
817                      match->nw_tos,
818                      match->nw_proto,
819                      ntohl(match->nw_src),
820                      ntohl(match->nw_dst),
821                      ntohs(match->tp_src),
822                      ntohs(match->tp_dst));
823 }
824
825 static uint32_t
826 vendor_code_to_id(uint8_t code)
827 {
828     switch (code) {
829 #define OFPUTIL_VENDOR(NAME, VENDOR_ID) case NAME: return VENDOR_ID;
830         OFPUTIL_VENDORS
831 #undef OFPUTIL_VENDOR
832     default:
833         return UINT32_MAX;
834     }
835 }
836
837 /* Creates and returns an OpenFlow message of type OFPT_ERROR with the error
838  * information taken from 'error', whose encoding must be as described in the
839  * large comment in ofp-util.h.  If 'oh' is nonnull, then the error will use
840  * oh->xid as its transaction ID, and it will include up to the first 64 bytes
841  * of 'oh'.
842  *
843  * Returns NULL if 'error' is not an OpenFlow error code. */
844 struct ofpbuf *
845 make_ofp_error_msg(int error, const struct ofp_header *oh)
846 {
847     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
848
849     struct ofpbuf *buf;
850     const void *data;
851     size_t len;
852     uint8_t vendor;
853     uint16_t type;
854     uint16_t code;
855     uint32_t xid;
856
857     if (!is_ofp_error(error)) {
858         /* We format 'error' with strerror() here since it seems likely to be
859          * a system errno value. */
860         VLOG_WARN_RL(&rl, "invalid OpenFlow error code %d (%s)",
861                      error, strerror(error));
862         return NULL;
863     }
864
865     if (oh) {
866         xid = oh->xid;
867         data = oh;
868         len = ntohs(oh->length);
869         if (len > 64) {
870             len = 64;
871         }
872     } else {
873         xid = 0;
874         data = NULL;
875         len = 0;
876     }
877
878     vendor = get_ofp_err_vendor(error);
879     type = get_ofp_err_type(error);
880     code = get_ofp_err_code(error);
881     if (vendor == OFPUTIL_VENDOR_OPENFLOW) {
882         struct ofp_error_msg *oem;
883
884         oem = make_openflow_xid(len + sizeof *oem, OFPT_ERROR, xid, &buf);
885         oem->type = htons(type);
886         oem->code = htons(code);
887     } else {
888         struct ofp_error_msg *oem;
889         struct nx_vendor_error *nve;
890         uint32_t vendor_id;
891
892         vendor_id = vendor_code_to_id(vendor);
893         if (vendor_id == UINT32_MAX) {
894             VLOG_WARN_RL(&rl, "error %x contains invalid vendor code %d",
895                          error, vendor);
896             return NULL;
897         }
898
899         oem = make_openflow_xid(len + sizeof *oem + sizeof *nve,
900                                 OFPT_ERROR, xid, &buf);
901         oem->type = htons(NXET_VENDOR);
902         oem->code = htons(NXVC_VENDOR_ERROR);
903
904         nve = ofpbuf_put_uninit(buf, sizeof *nve);
905         nve->vendor = htonl(vendor_id);
906         nve->type = htons(type);
907         nve->code = htons(code);
908     }
909
910     if (len) {
911         ofpbuf_put(buf, data, len);
912     }
913
914     return buf;
915 }
916
917 /* Attempts to pull 'actions_len' bytes from the front of 'b'.  Returns 0 if
918  * successful, otherwise an OpenFlow error.
919  *
920  * If successful, the first action is stored in '*actionsp' and the number of
921  * "union ofp_action" size elements into '*n_actionsp'.  Otherwise NULL and 0
922  * are stored, respectively.
923  *
924  * This function does not check that the actions are valid (the caller should
925  * do so, with validate_actions()).  The caller is also responsible for making
926  * sure that 'b->data' is initially aligned appropriately for "union
927  * ofp_action". */
928 int
929 ofputil_pull_actions(struct ofpbuf *b, unsigned int actions_len,
930                      union ofp_action **actionsp, size_t *n_actionsp)
931 {
932     if (actions_len % OFP_ACTION_ALIGN != 0) {
933         VLOG_DBG_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
934                     "is not a multiple of %d", actions_len, OFP_ACTION_ALIGN);
935         goto error;
936     }
937
938     *actionsp = ofpbuf_try_pull(b, actions_len);
939     if (*actionsp == NULL) {
940         VLOG_DBG_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
941                     "exceeds remaining message length (%zu)",
942                     actions_len, b->size);
943         goto error;
944     }
945
946     *n_actionsp = actions_len / OFP_ACTION_ALIGN;
947     return 0;
948
949 error:
950     *actionsp = NULL;
951     *n_actionsp = 0;
952     return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
953 }