ofp-msgs: Add support for ONF extension messages.
[cascardo/ovs.git] / lib / ofp-msgs.c
1 /*
2  * Copyright (c) 2012, 2013, 2014, 2015, 2016 Nicira, Inc.
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-msgs.h"
19 #include "byte-order.h"
20 #include "dynamic-string.h"
21 #include "hash.h"
22 #include "hmap.h"
23 #include "ofpbuf.h"
24 #include "openflow/nicira-ext.h"
25 #include "openflow/openflow.h"
26 #include "ovs-thread.h"
27 #include "openvswitch/vlog.h"
28
29 VLOG_DEFINE_THIS_MODULE(ofp_msgs);
30
31 #define OFPT_VENDOR 4
32 #define OFPT10_STATS_REQUEST 16
33 #define OFPT10_STATS_REPLY 17
34 #define OFPT11_STATS_REQUEST 18
35 #define OFPT11_STATS_REPLY 19
36 #define OFPST_VENDOR 0xffff
37
38 /* Vendor extension message. */
39 struct ofp_vendor_header {
40     struct ofp_header header;   /* OFPT_VENDOR. */
41     ovs_be32 vendor;            /* Vendor ID:
42                                  * - MSB 0: low-order bytes are IEEE OUI.
43                                  * - MSB != 0: defined by OpenFlow
44                                  *   consortium. */
45
46     /* In theory everything after 'vendor' is vendor specific.  In practice,
47      * the vendors we support put a 32-bit subtype here.  We'll change this
48      * structure if we start adding support for other vendor formats. */
49     ovs_be32 subtype;           /* Vendor-specific subtype. */
50
51     /* Followed by vendor-defined additional data. */
52 };
53 OFP_ASSERT(sizeof(struct ofp_vendor_header) == 16);
54
55 /* Vendor extension stats message. */
56 struct ofp11_vendor_stats_msg {
57     struct ofp11_stats_msg osm; /* Type OFPST_VENDOR. */
58     ovs_be32 vendor;            /* Vendor ID:
59                                  * - MSB 0: low-order bytes are IEEE OUI.
60                                  * - MSB != 0: defined by OpenFlow
61                                  *   consortium. */
62
63     /* In theory everything after 'vendor' is vendor specific.  In practice,
64      * the vendors we support put a 32-bit subtype here.  We'll change this
65      * structure if we start adding support for other vendor formats. */
66     ovs_be32 subtype;           /* Vendor-specific subtype. */
67
68     /* Followed by vendor-defined additional data. */
69 };
70 OFP_ASSERT(sizeof(struct ofp11_vendor_stats_msg) == 24);
71 /* A thin abstraction of OpenFlow headers:
72  *
73  *   - 'version' and 'type' come straight from struct ofp_header, so these are
74  *     always present and meaningful.
75  *
76  *   - 'stat' comes from the 'type' member in statistics messages only.  It is
77  *     meaningful, therefore, only if 'version' and 'type' taken together
78  *     specify a statistics request or reply.  Otherwise it is 0.
79  *
80  *   - 'vendor' is meaningful only for vendor messages, that is, if 'version'
81  *     and 'type' specify a vendor message or if 'version' and 'type' specify
82  *     a statistics message and 'stat' specifies a vendor statistic type.
83  *     Otherwise it is 0.
84  *
85  *   - 'subtype' is meaningful only for vendor messages and otherwise 0.  It
86  *     specifies a vendor-defined subtype.  There is no standard format for
87  *     these but 32 bits seems like it should be enough. */
88 struct ofphdrs {
89     uint8_t version;            /* From ofp_header. */
90     uint8_t type;               /* From ofp_header. */
91     uint16_t stat;              /* From ofp10_stats_msg or ofp11_stats_msg. */
92     uint32_t vendor;            /* From ofp_vendor_header,
93                                  * ofp10_vendor_stats_msg, or
94                                  * ofp11_vendor_stats_msg. */
95     uint32_t subtype;           /* From nicira_header, nicira10_stats_msg, or
96                                  * nicira11_stats_msg. */
97 };
98 BUILD_ASSERT_DECL(sizeof(struct ofphdrs) == 12);
99
100 /* A mapping from OpenFlow headers to OFPRAW_*.  */
101 struct raw_instance {
102     struct hmap_node hmap_node; /* In 'raw_instance_map'. */
103     struct ofphdrs hdrs;        /* Key. */
104     enum ofpraw raw;            /* Value. */
105     unsigned int hdrs_len;      /* ofphdrs_len(hdrs). */
106 };
107
108 /* Information about a particular 'enum ofpraw'. */
109 struct raw_info {
110     /* All possible instantiations of this OFPRAW_* into OpenFlow headers. */
111     struct raw_instance *instances; /* min_version - max_version + 1 elems. */
112     uint8_t min_version;
113     uint8_t max_version;
114
115     unsigned int min_body;
116     unsigned int extra_multiple;
117     enum ofptype type;
118     const char *name;
119 };
120
121 /* All understood OpenFlow message types, indexed by their 'struct ofphdrs'. */
122 static struct hmap raw_instance_map;
123 #include "ofp-msgs.inc"
124
125 static ovs_be32 alloc_xid(void);
126
127 /* ofphdrs functions. */
128 static uint32_t ofphdrs_hash(const struct ofphdrs *);
129 static bool ofphdrs_equal(const struct ofphdrs *a, const struct ofphdrs *b);
130 static enum ofperr ofphdrs_decode(struct ofphdrs *,
131                                   const struct ofp_header *oh, size_t length);
132 static void ofphdrs_decode_assert(struct ofphdrs *,
133                                   const struct ofp_header *oh, size_t length);
134 size_t ofphdrs_len(const struct ofphdrs *);
135
136 static const struct raw_info *raw_info_get(enum ofpraw);
137 static struct raw_instance *raw_instance_get(const struct raw_info *,
138                                              uint8_t version);
139
140 static enum ofperr ofpraw_from_ofphdrs(enum ofpraw *, const struct ofphdrs *);
141 \f
142 /* Returns a transaction ID to use for an outgoing OpenFlow message. */
143 static ovs_be32
144 alloc_xid(void)
145 {
146     static atomic_count next_xid = ATOMIC_COUNT_INIT(1);
147
148     return htonl(atomic_count_inc(&next_xid));
149 }
150 \f
151 static uint32_t
152 ofphdrs_hash(const struct ofphdrs *hdrs)
153 {
154     BUILD_ASSERT_DECL(sizeof *hdrs % 4 == 0);
155     return hash_bytes32((const uint32_t *) hdrs, sizeof *hdrs, 0);
156 }
157
158 static bool
159 ofphdrs_equal(const struct ofphdrs *a, const struct ofphdrs *b)
160 {
161     return !memcmp(a, b, sizeof *a);
162 }
163
164 static void
165 log_bad_vendor(uint32_t vendor)
166 {
167     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
168
169     VLOG_WARN_RL(&rl, "OpenFlow message has unknown vendor %#"PRIx32, vendor);
170 }
171
172 static enum ofperr
173 ofphdrs_decode(struct ofphdrs *hdrs,
174                const struct ofp_header *oh, size_t length)
175 {
176     memset(hdrs, 0, sizeof *hdrs);
177     if (length < sizeof *oh) {
178         return OFPERR_OFPBRC_BAD_LEN;
179     }
180
181     /* Get base message version and type (OFPT_*). */
182     hdrs->version = oh->version;
183     hdrs->type = oh->type;
184
185     if (hdrs->type == OFPT_VENDOR) {
186         /* Get vendor. */
187         const struct ofp_vendor_header *ovh;
188
189         if (length < sizeof *ovh) {
190             return OFPERR_OFPBRC_BAD_LEN;
191         }
192
193         ovh = (const struct ofp_vendor_header *) oh;
194         hdrs->vendor = ntohl(ovh->vendor);
195         if (hdrs->vendor == NX_VENDOR_ID || hdrs->vendor == ONF_VENDOR_ID) {
196             hdrs->subtype = ntohl(ovh->subtype);
197         } else {
198             log_bad_vendor(hdrs->vendor);
199             return OFPERR_OFPBRC_BAD_VENDOR;
200         }
201     } else if (hdrs->version == OFP10_VERSION
202                && (hdrs->type == OFPT10_STATS_REQUEST ||
203                    hdrs->type == OFPT10_STATS_REPLY)) {
204         const struct ofp10_stats_msg *osm;
205
206         /* Get statistic type (OFPST_*). */
207         if (length < sizeof *osm) {
208             return OFPERR_OFPBRC_BAD_LEN;
209         }
210         osm = (const struct ofp10_stats_msg *) oh;
211         hdrs->stat = ntohs(osm->type);
212
213         if (hdrs->stat == OFPST_VENDOR) {
214             /* Get vendor. */
215             const struct ofp10_vendor_stats_msg *ovsm;
216
217             if (length < sizeof *ovsm) {
218                 return OFPERR_OFPBRC_BAD_LEN;
219             }
220
221             ovsm = (const struct ofp10_vendor_stats_msg *) oh;
222             hdrs->vendor = ntohl(ovsm->vendor);
223             if (hdrs->vendor == NX_VENDOR_ID) {
224                 /* Get Nicira statistic type (NXST_*). */
225                 const struct nicira10_stats_msg *nsm;
226
227                 if (length < sizeof *nsm) {
228                     return OFPERR_OFPBRC_BAD_LEN;
229                 }
230                 nsm = (const struct nicira10_stats_msg *) oh;
231                 hdrs->subtype = ntohl(nsm->subtype);
232             } else {
233                 log_bad_vendor(hdrs->vendor);
234                 return OFPERR_OFPBRC_BAD_VENDOR;
235             }
236         }
237     } else if (hdrs->version != OFP10_VERSION
238                && (hdrs->type == OFPT11_STATS_REQUEST ||
239                    hdrs->type == OFPT11_STATS_REPLY)) {
240         const struct ofp11_stats_msg *osm;
241
242         /* Get statistic type (OFPST_*). */
243         if (length < sizeof *osm) {
244             return OFPERR_OFPBRC_BAD_LEN;
245         }
246         osm = (const struct ofp11_stats_msg *) oh;
247         hdrs->stat = ntohs(osm->type);
248
249         if (hdrs->stat == OFPST_VENDOR) {
250             /* Get vendor. */
251             const struct ofp11_vendor_stats_msg *ovsm;
252
253             if (length < sizeof *ovsm) {
254                 return OFPERR_OFPBRC_BAD_LEN;
255             }
256
257             ovsm = (const struct ofp11_vendor_stats_msg *) oh;
258             hdrs->vendor = ntohl(ovsm->vendor);
259             if (hdrs->vendor == NX_VENDOR_ID ||
260                 hdrs->vendor == ONF_VENDOR_ID) {
261                 hdrs->subtype = ntohl(ovsm->subtype);
262             } else {
263                 log_bad_vendor(hdrs->vendor);
264                 return OFPERR_OFPBRC_BAD_VENDOR;
265             }
266         }
267     }
268
269     return 0;
270 }
271
272 static void
273 ofphdrs_decode_assert(struct ofphdrs *hdrs,
274                       const struct ofp_header *oh, size_t length)
275 {
276     enum ofperr error = ofphdrs_decode(hdrs, oh, length);
277     ovs_assert(!error);
278 }
279
280 static bool
281 ofp_is_stat_request(enum ofp_version version, uint8_t type)
282 {
283     switch (version) {
284     case OFP10_VERSION:
285         return type == OFPT10_STATS_REQUEST;
286     case OFP11_VERSION:
287     case OFP12_VERSION:
288     case OFP13_VERSION:
289     case OFP14_VERSION:
290     case OFP15_VERSION:
291         return type == OFPT11_STATS_REQUEST;
292     }
293
294     return false;
295 }
296
297 static bool
298 ofp_is_stat_reply(enum ofp_version version, uint8_t type)
299 {
300     switch (version) {
301     case OFP10_VERSION:
302         return type == OFPT10_STATS_REPLY;
303     case OFP11_VERSION:
304     case OFP12_VERSION:
305     case OFP13_VERSION:
306     case OFP14_VERSION:
307     case OFP15_VERSION:
308         return type == OFPT11_STATS_REPLY;
309     }
310
311     return false;
312 }
313
314 static bool
315 ofp_is_stat(enum ofp_version version, uint8_t type)
316 {
317     return (ofp_is_stat_request(version, type) ||
318             ofp_is_stat_reply(version, type));
319 }
320
321 static bool
322 ofphdrs_is_stat(const struct ofphdrs *hdrs)
323 {
324     return ofp_is_stat(hdrs->version, hdrs->type);
325 }
326
327 size_t
328 ofphdrs_len(const struct ofphdrs *hdrs)
329 {
330     if (hdrs->type == OFPT_VENDOR) {
331         return sizeof(struct ofp_vendor_header);
332     }
333
334     switch ((enum ofp_version) hdrs->version) {
335     case OFP10_VERSION:
336         if (hdrs->type == OFPT10_STATS_REQUEST ||
337             hdrs->type == OFPT10_STATS_REPLY) {
338             return (hdrs->stat == OFPST_VENDOR
339                     ? sizeof(struct nicira10_stats_msg)
340                     : sizeof(struct ofp10_stats_msg));
341         }
342         break;
343
344     case OFP11_VERSION:
345     case OFP12_VERSION:
346     case OFP13_VERSION:
347     case OFP14_VERSION:
348     case OFP15_VERSION:
349         if (hdrs->type == OFPT11_STATS_REQUEST ||
350             hdrs->type == OFPT11_STATS_REPLY) {
351             return (hdrs->stat == OFPST_VENDOR
352                     ? sizeof(struct ofp11_vendor_stats_msg)
353                     : sizeof(struct ofp11_stats_msg));
354         }
355         break;
356     }
357
358     return sizeof(struct ofp_header);
359 }
360 \f
361 /* Determines the OFPRAW_* type of the OpenFlow message at 'oh', which has
362  * length 'oh->length'.  (The caller must ensure that 'oh->length' bytes of
363  * data are readable at 'oh'.)  On success, returns 0 and stores the type into
364  * '*raw'.  On failure, returns an OFPERR_* error code and zeros '*raw'.
365  *
366  * This function checks that 'oh' is a valid length for its particular type of
367  * message, and returns an error if not. */
368 enum ofperr
369 ofpraw_decode(enum ofpraw *raw, const struct ofp_header *oh)
370 {
371     struct ofpbuf msg;
372
373     ofpbuf_use_const(&msg, oh, ntohs(oh->length));
374     return ofpraw_pull(raw, &msg);
375 }
376
377 /* Does the same job as ofpraw_decode(), except that it assert-fails if
378  * ofpraw_decode() would have reported an error.  Thus, it's able to use the
379  * return value for the OFPRAW_* message type instead of an error code.
380  *
381  * (It only makes sense to use this function if you previously called
382  * ofpraw_decode() on the message and thus know that it's OK.) */
383 enum ofpraw
384 ofpraw_decode_assert(const struct ofp_header *oh)
385 {
386     enum ofperr error;
387     enum ofpraw raw;
388
389     error = ofpraw_decode(&raw, oh);
390     ovs_assert(!error);
391     return raw;
392 }
393
394 /* Determines the OFPRAW_* type of the OpenFlow message in 'msg', which starts
395  * at 'msg->data' and has length 'msg->size' bytes.  On success,
396  * returns 0 and stores the type into '*rawp'.  On failure, returns an OFPERR_*
397  * error code and zeros '*rawp'.
398  *
399  * This function checks that the message has a valid length for its particular
400  * type of message, and returns an error if not.
401  *
402  * In addition to setting '*rawp', this function pulls off the OpenFlow header
403  * (including the stats headers, vendor header, and any subtype header) with
404  * ofpbuf_pull().  It also sets 'msg->header' to the start of the OpenFlow
405  * header and 'msg->msg' just beyond the headers (that is, to the final value
406  * of msg->data). */
407 enum ofperr
408 ofpraw_pull(enum ofpraw *rawp, struct ofpbuf *msg)
409 {
410     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
411
412     const struct raw_instance *instance;
413     const struct raw_info *info;
414     struct ofphdrs hdrs;
415
416     unsigned int min_len;
417     unsigned int len;
418
419     enum ofperr error;
420     enum ofpraw raw;
421
422     /* Set default outputs. */
423     msg->header = msg->data;
424     msg->msg = msg->header;
425     *rawp = 0;
426
427     len = msg->size;
428     error = ofphdrs_decode(&hdrs, msg->data, len);
429     if (error) {
430         return error;
431     }
432
433     error = ofpraw_from_ofphdrs(&raw, &hdrs);
434     if (error) {
435         return error;
436     }
437
438     info = raw_info_get(raw);
439     instance = raw_instance_get(info, hdrs.version);
440     msg->header = ofpbuf_pull(msg, instance->hdrs_len);
441     msg->msg = msg->data;
442
443     min_len = instance->hdrs_len + info->min_body;
444     switch (info->extra_multiple) {
445     case 0:
446         if (len != min_len) {
447             VLOG_WARN_RL(&rl, "received %s with incorrect length %u (expected "
448                          "length %u)", info->name, len, min_len);
449             return OFPERR_OFPBRC_BAD_LEN;
450         }
451         break;
452
453     case 1:
454         if (len < min_len) {
455             VLOG_WARN_RL(&rl, "received %s with incorrect length %u (expected "
456                          "length at least %u bytes)",
457                          info->name, len, min_len);
458             return OFPERR_OFPBRC_BAD_LEN;
459         }
460         break;
461
462     default:
463         if (len < min_len || (len - min_len) % info->extra_multiple) {
464             VLOG_WARN_RL(&rl, "received %s with incorrect length %u (must be "
465                          "exactly %u bytes or longer by an integer multiple "
466                          "of %u bytes)",
467                          info->name, len, min_len, info->extra_multiple);
468             return OFPERR_OFPBRC_BAD_LEN;
469         }
470         break;
471     }
472
473     *rawp = raw;
474     return 0;
475 }
476
477 /* Does the same job as ofpraw_pull(), except that it assert-fails if
478  * ofpraw_pull() would have reported an error.  Thus, it's able to use the
479  * return value for the OFPRAW_* message type instead of an error code.
480  *
481  * (It only makes sense to use this function if you previously called
482  * ofpraw_decode() on the message and thus know that it's OK.) */
483 enum ofpraw
484 ofpraw_pull_assert(struct ofpbuf *msg)
485 {
486     enum ofperr error;
487     enum ofpraw raw;
488
489     error = ofpraw_pull(&raw, msg);
490     ovs_assert(!error);
491     return raw;
492 }
493
494 /* Determines the OFPRAW_* type of the OpenFlow message that starts at 'oh' and
495  * has length 'length' bytes.  On success, returns 0 and stores the type into
496  * '*rawp'.  On failure, returns an OFPERR_* error code and zeros '*rawp'.
497  *
498  * Unlike other functions for decoding message types, this one is not picky
499  * about message length.  For example, it will successfully decode a message
500  * whose body is shorter than the minimum length for a message of its type.
501  * Thus, this is the correct function to use for decoding the type of a message
502  * that might have been truncated, such as the payload of an OpenFlow error
503  * message (which is allowed to be truncated to 64 bytes). */
504 enum ofperr
505 ofpraw_decode_partial(enum ofpraw *raw,
506                       const struct ofp_header *oh, size_t length)
507 {
508     struct ofphdrs hdrs;
509     enum ofperr error;
510
511     error = ofphdrs_decode(&hdrs, oh, length);
512     if (!error) {
513         error = ofpraw_from_ofphdrs(raw, &hdrs);
514     }
515
516     if (error) {
517         *raw = 0;
518     }
519     return error;
520 }
521 \f
522 /* Encoding messages using OFPRAW_* values. */
523
524 static void ofpraw_put__(enum ofpraw, uint8_t version, ovs_be32 xid,
525                          size_t extra_tailroom, struct ofpbuf *);
526
527 /* Allocates and returns a new ofpbuf that contains an OpenFlow header for
528  * 'raw' with OpenFlow version 'version' and a fresh OpenFlow transaction ID.
529  * The ofpbuf has enough tailroom for the minimum body length of 'raw', plus
530  * 'extra_tailroom' additional bytes.
531  *
532  * Each 'raw' value is valid only for certain OpenFlow versions.  The caller
533  * must specify a valid (raw, version) pair.
534  *
535  * In the returned ofpbuf, 'header' points to the beginning of the
536  * OpenFlow header and 'msg' points just after it, to where the
537  * message's body will start.  The caller must actually allocate the
538  * body into the space reserved for it, e.g. with ofpbuf_put_uninit().
539  *
540  * The caller owns the returned ofpbuf and must free it when it is no longer
541  * needed, e.g. with ofpbuf_delete(). */
542 struct ofpbuf *
543 ofpraw_alloc(enum ofpraw raw, uint8_t version, size_t extra_tailroom)
544 {
545     return ofpraw_alloc_xid(raw, version, alloc_xid(), extra_tailroom);
546 }
547
548 /* Same as ofpraw_alloc() but the caller provides the transaction ID. */
549 struct ofpbuf *
550 ofpraw_alloc_xid(enum ofpraw raw, uint8_t version, ovs_be32 xid,
551                  size_t extra_tailroom)
552 {
553     struct ofpbuf *buf = ofpbuf_new(0);
554     ofpraw_put__(raw, version, xid, extra_tailroom, buf);
555     return buf;
556 }
557
558 /* Same as ofpraw_alloc(), but obtains the OpenFlow version and transaction ID
559  * from 'request->version' and 'request->xid', respectively.
560  *
561  * Even though the version comes from 'request->version', the caller must still
562  * know what it is doing, by specifying a valid pairing of 'raw' and
563  * 'request->version', just like ofpraw_alloc(). */
564 struct ofpbuf *
565 ofpraw_alloc_reply(enum ofpraw raw, const struct ofp_header *request,
566                    size_t extra_tailroom)
567 {
568     return ofpraw_alloc_xid(raw, request->version, request->xid,
569                             extra_tailroom);
570 }
571
572 /* Allocates and returns a new ofpbuf that contains an OpenFlow header that is
573  * a stats reply to the stats request in 'request', using the same OpenFlow
574  * version and transaction ID as 'request'.  The ofpbuf has enough tailroom for
575  * the stats reply's minimum body length, plus 'extra_tailroom' additional
576  * bytes.
577  *
578  * 'request' must be a stats request, that is, an OFPRAW_OFPST* or OFPRAW_NXST*
579  * value.  Every stats request has a corresponding reply, so the (raw, version)
580  * pairing pitfalls of the other ofpraw_alloc_*() functions don't apply here.
581  *
582  * In the returned ofpbuf, 'header' points to the beginning of the
583  * OpenFlow header and 'msg' points just after it, to where the
584  * message's body will start.  The caller must actually allocate the
585  * body into the space reserved for it, e.g. with ofpbuf_put_uninit().
586  *
587  * The caller owns the returned ofpbuf and must free it when it is no longer
588  * needed, e.g. with ofpbuf_delete(). */
589 struct ofpbuf *
590 ofpraw_alloc_stats_reply(const struct ofp_header *request,
591                          size_t extra_tailroom)
592 {
593     enum ofpraw request_raw;
594     enum ofpraw reply_raw;
595     enum ofperr error;
596
597     error = ofpraw_decode_partial(&request_raw, request,
598                                   ntohs(request->length));
599     ovs_assert(!error);
600
601     reply_raw = ofpraw_stats_request_to_reply(request_raw, request->version);
602     ovs_assert(reply_raw);
603
604     return ofpraw_alloc_reply(reply_raw, request, extra_tailroom);
605 }
606
607 /* Appends to 'buf' an OpenFlow header for 'raw' with OpenFlow version
608  * 'version' and a fresh OpenFlow transaction ID.  Preallocates enough tailroom
609  * in 'buf' for the minimum body length of 'raw', plus 'extra_tailroom'
610  * additional bytes.
611  *
612  * Each 'raw' value is valid only for certain OpenFlow versions.  The caller
613  * must specify a valid (raw, version) pair.
614  *
615  * Upon return, 'buf->header' points to the beginning of the OpenFlow header
616  * and 'buf->msg' points just after it, to where the message's body will start.
617  * The caller must actually allocating the body into the space reserved for it,
618  * e.g. with ofpbuf_put_uninit(). */
619 void
620 ofpraw_put(enum ofpraw raw, uint8_t version, struct ofpbuf *buf)
621 {
622     ofpraw_put__(raw, version, alloc_xid(), 0, buf);
623 }
624
625 /* Same as ofpraw_put() but the caller provides the transaction ID. */
626 void
627 ofpraw_put_xid(enum ofpraw raw, uint8_t version, ovs_be32 xid,
628                struct ofpbuf *buf)
629 {
630     ofpraw_put__(raw, version, xid, 0, buf);
631 }
632
633 /* Same as ofpraw_put(), but obtains the OpenFlow version and transaction ID
634  * from 'request->version' and 'request->xid', respectively.
635  *
636  * Even though the version comes from 'request->version', the caller must still
637  * know what it is doing, by specifying a valid pairing of 'raw' and
638  * 'request->version', just like ofpraw_put(). */
639 void
640 ofpraw_put_reply(enum ofpraw raw, const struct ofp_header *request,
641                  struct ofpbuf *buf)
642 {
643     ofpraw_put__(raw, request->version, request->xid, 0, buf);
644 }
645
646 /* Appends to 'buf' an OpenFlow header that is a stats reply to the stats
647  * request in 'request', using the same OpenFlow version and transaction ID as
648  * 'request'.  Preallocate enough tailroom in 'buf for the stats reply's
649  * minimum body length, plus 'extra_tailroom' additional bytes.
650  *
651  * 'request' must be a stats request, that is, an OFPRAW_OFPST* or OFPRAW_NXST*
652  * value.  Every stats request has a corresponding reply, so the (raw, version)
653  * pairing pitfalls of the other ofpraw_alloc_*() functions don't apply here.
654  *
655  * In the returned ofpbuf, 'header' points to the beginning of the
656  * OpenFlow header and 'msg' points just after it, to where the
657  * message's body will start.  The caller must actually allocate the
658  * body into the space reserved for it, e.g. with ofpbuf_put_uninit().
659  *
660  * The caller owns the returned ofpbuf and must free it when it is no longer
661  * needed, e.g. with ofpbuf_delete(). */
662 void
663 ofpraw_put_stats_reply(const struct ofp_header *request, struct ofpbuf *buf)
664 {
665     enum ofperr error;
666     enum ofpraw raw;
667
668     error = ofpraw_decode_partial(&raw, request, ntohs(request->length));
669     ovs_assert(!error);
670
671     raw = ofpraw_stats_request_to_reply(raw, request->version);
672     ovs_assert(raw);
673
674     ofpraw_put__(raw, request->version, request->xid, 0, buf);
675 }
676
677 static void
678 ofpraw_put__(enum ofpraw raw, uint8_t version, ovs_be32 xid,
679              size_t extra_tailroom, struct ofpbuf *buf)
680 {
681     const struct raw_info *info = raw_info_get(raw);
682     const struct raw_instance *instance = raw_instance_get(info, version);
683     const struct ofphdrs *hdrs = &instance->hdrs;
684     struct ofp_header *oh;
685
686     ofpbuf_prealloc_tailroom(buf, (instance->hdrs_len + info->min_body
687                                    + extra_tailroom));
688     buf->header = ofpbuf_put_uninit(buf, instance->hdrs_len);
689     buf->msg = ofpbuf_tail(buf);
690
691     oh = buf->header;
692     oh->version = version;
693     oh->type = hdrs->type;
694     oh->length = htons(buf->size);
695     oh->xid = xid;
696
697     if (hdrs->type == OFPT_VENDOR) {
698         struct ofp_vendor_header *ovh = buf->header;
699
700         ovh->vendor = htonl(hdrs->vendor);
701         ovh->subtype = htonl(hdrs->subtype);
702     } else if (version == OFP10_VERSION
703                && (hdrs->type == OFPT10_STATS_REQUEST ||
704                    hdrs->type == OFPT10_STATS_REPLY)) {
705         struct ofp10_stats_msg *osm = buf->header;
706
707         osm->type = htons(hdrs->stat);
708         osm->flags = htons(0);
709
710         if (hdrs->stat == OFPST_VENDOR) {
711             struct ofp10_vendor_stats_msg *ovsm = buf->header;
712
713             ovsm->vendor = htonl(hdrs->vendor);
714             if (hdrs->vendor == NX_VENDOR_ID) {
715                 struct nicira10_stats_msg *nsm = buf->header;
716
717                 nsm->subtype = htonl(hdrs->subtype);
718                 memset(nsm->pad, 0, sizeof nsm->pad);
719             } else {
720                 OVS_NOT_REACHED();
721             }
722         }
723     } else if (version != OFP10_VERSION
724                && (hdrs->type == OFPT11_STATS_REQUEST ||
725                    hdrs->type == OFPT11_STATS_REPLY)) {
726         struct ofp11_stats_msg *osm = buf->header;
727
728         osm->type = htons(hdrs->stat);
729         osm->flags = htons(0);
730         memset(osm->pad, 0, sizeof osm->pad);
731
732         if (hdrs->stat == OFPST_VENDOR) {
733             struct ofp11_vendor_stats_msg *ovsm = buf->header;
734
735             ovsm->vendor = htonl(hdrs->vendor);
736             ovsm->subtype = htonl(hdrs->subtype);
737         }
738     }
739 }
740 \f
741 /* Returns 'raw''s name.
742  *
743  * The name is the name used for 'raw' in the OpenFlow specification.  For
744  * example, ofpraw_get_name(OFPRAW_OFPT10_FEATURES_REPLY) is
745  * "OFPT_FEATURES_REPLY".
746  *
747  * The caller must not modify or free the returned string. */
748 const char *
749 ofpraw_get_name(enum ofpraw raw)
750 {
751     return raw_info_get(raw)->name;
752 }
753
754 /* Returns the stats reply that corresponds to 'raw' in the given OpenFlow
755  * 'version'. */
756 enum ofpraw
757 ofpraw_stats_request_to_reply(enum ofpraw raw, uint8_t version)
758 {
759     const struct raw_info *info = raw_info_get(raw);
760     const struct raw_instance *instance = raw_instance_get(info, version);
761     enum ofpraw reply_raw;
762     struct ofphdrs hdrs;
763     enum ofperr error;
764
765     hdrs = instance->hdrs;
766     switch ((enum ofp_version)hdrs.version) {
767     case OFP10_VERSION:
768         ovs_assert(hdrs.type == OFPT10_STATS_REQUEST);
769         hdrs.type = OFPT10_STATS_REPLY;
770         break;
771     case OFP11_VERSION:
772     case OFP12_VERSION:
773     case OFP13_VERSION:
774     case OFP14_VERSION:
775     case OFP15_VERSION:
776         ovs_assert(hdrs.type == OFPT11_STATS_REQUEST);
777         hdrs.type = OFPT11_STATS_REPLY;
778         break;
779     default:
780         OVS_NOT_REACHED();
781     }
782
783     error = ofpraw_from_ofphdrs(&reply_raw, &hdrs);
784     ovs_assert(!error);
785
786     return reply_raw;
787 }
788 \f
789 /* Determines the OFPTYPE_* type of the OpenFlow message at 'oh', which has
790  * length 'oh->length'.  (The caller must ensure that 'oh->length' bytes of
791  * data are readable at 'oh'.)  On success, returns 0 and stores the type into
792  * '*typep'.  On failure, returns an OFPERR_* error code and zeros '*typep'.
793  *
794  * This function checks that 'oh' is a valid length for its particular type of
795  * message, and returns an error if not. */
796 enum ofperr
797 ofptype_decode(enum ofptype *typep, const struct ofp_header *oh)
798 {
799     enum ofperr error;
800     enum ofpraw raw;
801
802     error = ofpraw_decode(&raw, oh);
803     *typep = error ? 0 : ofptype_from_ofpraw(raw);
804     return error;
805 }
806
807 /* Determines the OFPTYPE_* type of the OpenFlow message in 'msg', which starts
808  * at 'msg->data' and has length 'msg->size' bytes.  On success,
809  * returns 0 and stores the type into '*typep'.  On failure, returns an
810  * OFPERR_* error code and zeros '*typep'.
811  *
812  * This function checks that the message has a valid length for its particular
813  * type of message, and returns an error if not.
814  *
815  * In addition to setting '*typep', this function pulls off the OpenFlow header
816  * (including the stats headers, vendor header, and any subtype header) with
817  * ofpbuf_pull().  It also sets 'msg->header' to the start of the OpenFlow
818  * header and 'msg->msg' just beyond the headers (that is, to the final value
819  * of msg->data). */
820 enum ofperr
821 ofptype_pull(enum ofptype *typep, struct ofpbuf *buf)
822 {
823     enum ofperr error;
824     enum ofpraw raw;
825
826     error = ofpraw_pull(&raw, buf);
827     *typep = error ? 0 : ofptype_from_ofpraw(raw);
828     return error;
829 }
830
831 /* Returns the OFPTYPE_* type that corresponds to 'raw'.
832  *
833  * (This is a one-way trip, because the mapping from ofpraw to ofptype is
834  * many-to-one.)  */
835 enum ofptype
836 ofptype_from_ofpraw(enum ofpraw raw)
837 {
838     return raw_info_get(raw)->type;
839 }
840
841 const char *
842 ofptype_get_name(enum ofptype type)
843 {
844     ovs_assert(type < ARRAY_SIZE(type_names));
845     return type_names[type];
846 }
847 \f
848 /* Updates the 'length' field of the OpenFlow message in 'buf' to
849  * 'buf->size'. */
850 void
851 ofpmsg_update_length(struct ofpbuf *buf)
852 {
853     struct ofp_header *oh = ofpbuf_at_assert(buf, 0, sizeof *oh);
854     oh->length = htons(buf->size);
855 }
856
857 /* Returns just past the OpenFlow header (including the stats headers, vendor
858  * header, and any subtype header) in 'oh'. */
859 const void *
860 ofpmsg_body(const struct ofp_header *oh)
861 {
862     struct ofphdrs hdrs;
863
864     ofphdrs_decode_assert(&hdrs, oh, ntohs(oh->length));
865     return (const uint8_t *) oh + ofphdrs_len(&hdrs);
866 }
867
868 /* Return if it's a stat/multipart (OFPST) request message. */
869 bool
870 ofpmsg_is_stat_request(const struct ofp_header *oh)
871 {
872     return ofp_is_stat_request(oh->version, oh->type);
873 }
874 \f
875 static ovs_be16 *ofpmp_flags__(const struct ofp_header *);
876
877 /* Initializes 'replies' as a new list of stats messages that reply to
878  * 'request', which must be a stats request message.  Initially the list will
879  * consist of only a single reply part without any body.  The caller should
880  * use calls to the other ofpmp_*() functions to add to the body and split the
881  * message into multiple parts, if necessary. */
882 void
883 ofpmp_init(struct ovs_list *replies, const struct ofp_header *request)
884 {
885     struct ofpbuf *msg;
886
887     list_init(replies);
888
889     msg = ofpraw_alloc_stats_reply(request, 1000);
890     list_push_back(replies, &msg->list_node);
891 }
892
893 /* Prepares to append up to 'len' bytes to the series of statistics replies in
894  * 'replies', which should have been initialized with ofpmp_init(), if
895  * necessary adding a new reply to the list.
896  *
897  * Returns an ofpbuf with at least 'len' bytes of tailroom.  The 'len' bytes
898  * have not actually been allocated, so the caller must do so with
899  * e.g. ofpbuf_put_uninit(). */
900 struct ofpbuf *
901 ofpmp_reserve(struct ovs_list *replies, size_t len)
902 {
903     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
904
905     if (msg->size + len <= UINT16_MAX) {
906         ofpbuf_prealloc_tailroom(msg, len);
907         return msg;
908     } else {
909         unsigned int hdrs_len;
910         struct ofpbuf *next;
911         struct ofphdrs hdrs;
912
913         ofphdrs_decode_assert(&hdrs, msg->data, msg->size);
914         hdrs_len = ofphdrs_len(&hdrs);
915
916         next = ofpbuf_new(MAX(1024, hdrs_len + len));
917         ofpbuf_put(next, msg->data, hdrs_len);
918         next->header = next->data;
919         next->msg = ofpbuf_tail(next);
920         list_push_back(replies, &next->list_node);
921
922         *ofpmp_flags__(msg->data) |= htons(OFPSF_REPLY_MORE);
923
924         return next;
925     }
926 }
927
928 /* Appends 'len' bytes to the series of statistics replies in 'replies', and
929  * returns the first byte. */
930 void *
931 ofpmp_append(struct ovs_list *replies, size_t len)
932 {
933     return ofpbuf_put_uninit(ofpmp_reserve(replies, len), len);
934 }
935
936 /* Sometimes, when composing stats replies, it's difficult to predict how long
937  * an individual reply chunk will be before actually encoding it into the reply
938  * buffer.  This function allows easy handling of this case: just encode the
939  * reply, then use this function to break the message into two pieces if it
940  * exceeds the OpenFlow message limit.
941  *
942  * In detail, if the final stats message in 'replies' is too long for OpenFlow,
943  * this function breaks it into two separate stats replies, the first one with
944  * the first 'start_ofs' bytes, the second one containing the bytes from that
945  * offset onward. */
946 void
947 ofpmp_postappend(struct ovs_list *replies, size_t start_ofs)
948 {
949     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
950
951     ovs_assert(start_ofs <= UINT16_MAX);
952     if (msg->size > UINT16_MAX) {
953         size_t len = msg->size - start_ofs;
954         memcpy(ofpmp_append(replies, len),
955                (const uint8_t *) msg->data + start_ofs, len);
956         msg->size = start_ofs;
957     }
958 }
959
960 /* Returns the OpenFlow version of the replies being constructed in 'replies',
961  * which should have been initialized by ofpmp_init(). */
962 enum ofp_version
963 ofpmp_version(struct ovs_list *replies)
964 {
965     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
966     const struct ofp_header *oh = msg->data;
967
968     return oh->version;
969 }
970
971 /* Determines the OFPRAW_* type of the OpenFlow messages in 'replies', which
972  * should have been initialized by ofpmp_init(). */
973 enum ofpraw
974 ofpmp_decode_raw(struct ovs_list *replies)
975 {
976     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
977     enum ofperr error;
978     enum ofpraw raw;
979
980     error = ofpraw_decode_partial(&raw, msg->data, msg->size);
981     ovs_assert(!error);
982     return raw;
983 }
984
985 static ovs_be16 *
986 ofpmp_flags__(const struct ofp_header *oh)
987 {
988     switch ((enum ofp_version)oh->version) {
989     case OFP10_VERSION:
990         return &((struct ofp10_stats_msg *) oh)->flags;
991     case OFP11_VERSION:
992     case OFP12_VERSION:
993     case OFP13_VERSION:
994     case OFP14_VERSION:
995     case OFP15_VERSION:
996         return &((struct ofp11_stats_msg *) oh)->flags;
997     default:
998         OVS_NOT_REACHED();
999     }
1000 }
1001
1002 /* Returns the OFPSF_* flags found in the OpenFlow stats header of 'oh', which
1003  * must be an OpenFlow stats request or reply.
1004  *
1005  * (OFPSF_REPLY_MORE is the only defined flag.) */
1006 uint16_t
1007 ofpmp_flags(const struct ofp_header *oh)
1008 {
1009     return ntohs(*ofpmp_flags__(oh));
1010 }
1011
1012 /* Returns true if the OFPSF_REPLY_MORE flag is set in the OpenFlow stats
1013  * header of 'oh', which must be an OpenFlow stats request or reply, false if
1014  * it is not set. */
1015 bool
1016 ofpmp_more(const struct ofp_header *oh)
1017 {
1018     return (ofpmp_flags(oh) & OFPSF_REPLY_MORE) != 0;
1019 }
1020 \f
1021 static void ofpmsgs_init(void);
1022
1023 static const struct raw_info *
1024 raw_info_get(enum ofpraw raw)
1025 {
1026     ofpmsgs_init();
1027
1028     ovs_assert(raw < ARRAY_SIZE(raw_infos));
1029     return &raw_infos[raw];
1030 }
1031
1032 static struct raw_instance *
1033 raw_instance_get(const struct raw_info *info, uint8_t version)
1034 {
1035     ovs_assert(version >= info->min_version && version <= info->max_version);
1036     return &info->instances[version - info->min_version];
1037 }
1038
1039 static enum ofperr
1040 ofpraw_from_ofphdrs(enum ofpraw *raw, const struct ofphdrs *hdrs)
1041 {
1042     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
1043
1044     struct raw_instance *raw_hdrs;
1045     uint32_t hash;
1046
1047     ofpmsgs_init();
1048
1049     hash = ofphdrs_hash(hdrs);
1050     HMAP_FOR_EACH_WITH_HASH (raw_hdrs, hmap_node, hash, &raw_instance_map) {
1051         if (ofphdrs_equal(hdrs, &raw_hdrs->hdrs)) {
1052             *raw = raw_hdrs->raw;
1053             return 0;
1054         }
1055     }
1056
1057     if (!VLOG_DROP_WARN(&rl)) {
1058         struct ds s;
1059
1060         ds_init(&s);
1061         ds_put_format(&s, "version %"PRIu8", type %"PRIu8,
1062                       hdrs->version, hdrs->type);
1063         if (ofphdrs_is_stat(hdrs)) {
1064             ds_put_format(&s, ", stat %"PRIu16, hdrs->stat);
1065         }
1066         if (hdrs->vendor) {
1067             ds_put_format(&s, ", vendor 0x%"PRIx32", subtype %"PRIu32,
1068                           hdrs->vendor, hdrs->subtype);
1069         }
1070         VLOG_WARN("unknown OpenFlow message (%s)", ds_cstr(&s));
1071         ds_destroy(&s);
1072     }
1073
1074     return (hdrs->vendor ? OFPERR_OFPBRC_BAD_SUBTYPE
1075             : ofphdrs_is_stat(hdrs) ? OFPERR_OFPBRC_BAD_STAT
1076             : OFPERR_OFPBRC_BAD_TYPE);
1077 }
1078
1079 static void
1080 ofpmsgs_init(void)
1081 {
1082     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
1083     const struct raw_info *info;
1084
1085     if (!ovsthread_once_start(&once)) {
1086         return;
1087     }
1088
1089     hmap_init(&raw_instance_map);
1090     for (info = raw_infos; info < &raw_infos[ARRAY_SIZE(raw_infos)]; info++)
1091     {
1092         int n_instances = info->max_version - info->min_version + 1;
1093         struct raw_instance *inst;
1094
1095         for (inst = info->instances;
1096              inst < &info->instances[n_instances];
1097              inst++) {
1098             inst->hdrs_len = ofphdrs_len(&inst->hdrs);
1099             hmap_insert(&raw_instance_map, &inst->hmap_node,
1100                         ofphdrs_hash(&inst->hdrs));
1101         }
1102     }
1103
1104     ovsthread_once_done(&once);
1105 }