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