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