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