bc38f401bb17777b3412d4cdab873d8de22a1f27
[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;
411
412     ofpbuf_use_const(&msg, oh, ntohs(oh->length));
413     return ofpraw_pull(raw, &msg);
414 }
415
416 /* Does the same job as ofpraw_decode(), except that it assert-fails if
417  * ofpraw_decode() would have reported an error.  Thus, it's able to use the
418  * return value for the OFPRAW_* message type instead of an error code.
419  *
420  * (It only makes sense to use this function if you previously called
421  * ofpraw_decode() on the message and thus know that it's OK.) */
422 enum ofpraw
423 ofpraw_decode_assert(const struct ofp_header *oh)
424 {
425     enum ofperr error;
426     enum ofpraw raw;
427
428     error = ofpraw_decode(&raw, oh);
429     ovs_assert(!error);
430     return raw;
431 }
432
433 /* Determines the OFPRAW_* type of the OpenFlow message in 'msg', which starts
434  * at 'msg->data' and has length 'msg->size' bytes.  On success,
435  * returns 0 and stores the type into '*rawp'.  On failure, returns an OFPERR_*
436  * error code and zeros '*rawp'.
437  *
438  * This function checks that the message has a valid length for its particular
439  * type of message, and returns an error if not.
440  *
441  * In addition to setting '*rawp', this function pulls off the OpenFlow header
442  * (including the stats headers, vendor header, and any subtype header) with
443  * ofpbuf_pull().  It also sets 'msg->header' to the start of the OpenFlow
444  * header and 'msg->msg' just beyond the headers (that is, to the final value
445  * of msg->data). */
446 enum ofperr
447 ofpraw_pull(enum ofpraw *rawp, struct ofpbuf *msg)
448 {
449     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
450
451     const struct raw_instance *instance;
452     const struct raw_info *info;
453     struct ofphdrs hdrs;
454
455     unsigned int min_len;
456     unsigned int len;
457
458     enum ofperr error;
459     enum ofpraw raw;
460
461     /* Set default outputs. */
462     msg->header = msg->data;
463     msg->msg = msg->header;
464     *rawp = 0;
465
466     len = msg->size;
467     error = ofphdrs_decode(&hdrs, msg->data, len);
468     if (error) {
469         return error;
470     }
471
472     error = ofpraw_from_ofphdrs(&raw, &hdrs);
473     if (error) {
474         return error;
475     }
476
477     info = raw_info_get(raw);
478     instance = raw_instance_get(info, hdrs.version);
479     msg->header = ofpbuf_pull(msg, instance->hdrs_len);
480     msg->msg = msg->data;
481
482     min_len = instance->hdrs_len + info->min_body;
483     switch (info->extra_multiple) {
484     case 0:
485         if (len != min_len) {
486             VLOG_WARN_RL(&rl, "received %s with incorrect length %u (expected "
487                          "length %u)", info->name, len, min_len);
488             return OFPERR_OFPBRC_BAD_LEN;
489         }
490         break;
491
492     case 1:
493         if (len < min_len) {
494             VLOG_WARN_RL(&rl, "received %s with incorrect length %u (expected "
495                          "length at least %u bytes)",
496                          info->name, len, min_len);
497             return OFPERR_OFPBRC_BAD_LEN;
498         }
499         break;
500
501     default:
502         if (len < min_len || (len - min_len) % info->extra_multiple) {
503             VLOG_WARN_RL(&rl, "received %s with incorrect length %u (must be "
504                          "exactly %u bytes or longer by an integer multiple "
505                          "of %u bytes)",
506                          info->name, len, min_len, info->extra_multiple);
507             return OFPERR_OFPBRC_BAD_LEN;
508         }
509         break;
510     }
511
512     *rawp = raw;
513     return 0;
514 }
515
516 /* Does the same job as ofpraw_pull(), except that it assert-fails if
517  * ofpraw_pull() would have reported an error.  Thus, it's able to use the
518  * return value for the OFPRAW_* message type instead of an error code.
519  *
520  * (It only makes sense to use this function if you previously called
521  * ofpraw_decode() on the message and thus know that it's OK.) */
522 enum ofpraw
523 ofpraw_pull_assert(struct ofpbuf *msg)
524 {
525     enum ofperr error;
526     enum ofpraw raw;
527
528     error = ofpraw_pull(&raw, msg);
529     ovs_assert(!error);
530     return raw;
531 }
532
533 /* Determines the OFPRAW_* type of the OpenFlow message that starts at 'oh' and
534  * has length 'length' bytes.  On success, returns 0 and stores the type into
535  * '*rawp'.  On failure, returns an OFPERR_* error code and zeros '*rawp'.
536  *
537  * Unlike other functions for decoding message types, this one is not picky
538  * about message length.  For example, it will successfully decode a message
539  * whose body is shorter than the minimum length for a message of its type.
540  * Thus, this is the correct function to use for decoding the type of a message
541  * that might have been truncated, such as the payload of an OpenFlow error
542  * message (which is allowed to be truncated to 64 bytes). */
543 enum ofperr
544 ofpraw_decode_partial(enum ofpraw *raw,
545                       const struct ofp_header *oh, size_t length)
546 {
547     struct ofphdrs hdrs;
548     enum ofperr error;
549
550     error = ofphdrs_decode(&hdrs, oh, length);
551     if (!error) {
552         error = ofpraw_from_ofphdrs(raw, &hdrs);
553     }
554
555     if (error) {
556         *raw = 0;
557     }
558     return error;
559 }
560 \f
561 /* Encoding messages using OFPRAW_* values. */
562
563 static void ofpraw_put__(enum ofpraw, uint8_t version, ovs_be32 xid,
564                          size_t extra_tailroom, struct ofpbuf *);
565
566 /* Allocates and returns a new ofpbuf that contains an OpenFlow header for
567  * 'raw' with OpenFlow version 'version' and a fresh OpenFlow transaction ID.
568  * The ofpbuf has enough tailroom for the minimum body length of 'raw', plus
569  * 'extra_tailroom' additional bytes.
570  *
571  * Each 'raw' value is valid only for certain OpenFlow versions.  The caller
572  * must specify a valid (raw, version) pair.
573  *
574  * In the returned ofpbuf, 'header' points to the beginning of the
575  * OpenFlow header and 'msg' points just after it, to where the
576  * message's body will start.  The caller must actually allocate the
577  * body into the space reserved for it, e.g. with ofpbuf_put_uninit().
578  *
579  * The caller owns the returned ofpbuf and must free it when it is no longer
580  * needed, e.g. with ofpbuf_delete(). */
581 struct ofpbuf *
582 ofpraw_alloc(enum ofpraw raw, uint8_t version, size_t extra_tailroom)
583 {
584     return ofpraw_alloc_xid(raw, version, alloc_xid(), extra_tailroom);
585 }
586
587 /* Same as ofpraw_alloc() but the caller provides the transaction ID. */
588 struct ofpbuf *
589 ofpraw_alloc_xid(enum ofpraw raw, uint8_t version, ovs_be32 xid,
590                  size_t extra_tailroom)
591 {
592     struct ofpbuf *buf = ofpbuf_new(0);
593     ofpraw_put__(raw, version, xid, extra_tailroom, buf);
594     return buf;
595 }
596
597 /* Same as ofpraw_alloc(), but obtains the OpenFlow version and transaction ID
598  * from 'request->version' and 'request->xid', respectively.
599  *
600  * Even though the version comes from 'request->version', the caller must still
601  * know what it is doing, by specifying a valid pairing of 'raw' and
602  * 'request->version', just like ofpraw_alloc(). */
603 struct ofpbuf *
604 ofpraw_alloc_reply(enum ofpraw raw, const struct ofp_header *request,
605                    size_t extra_tailroom)
606 {
607     return ofpraw_alloc_xid(raw, request->version, request->xid,
608                             extra_tailroom);
609 }
610
611 /* Allocates and returns a new ofpbuf that contains an OpenFlow header that is
612  * a stats reply to the stats request in 'request', using the same OpenFlow
613  * version and transaction ID as 'request'.  The ofpbuf has enough tailroom for
614  * the stats reply's minimum body length, plus 'extra_tailroom' additional
615  * bytes.
616  *
617  * 'request' must be a stats request, that is, an OFPRAW_OFPST* or OFPRAW_NXST*
618  * value.  Every stats request has a corresponding reply, so the (raw, version)
619  * pairing pitfalls of the other ofpraw_alloc_*() functions don't apply here.
620  *
621  * In the returned ofpbuf, 'header' points to the beginning of the
622  * OpenFlow header and 'msg' points just after it, to where the
623  * message's body will start.  The caller must actually allocate the
624  * body into the space reserved for it, e.g. with ofpbuf_put_uninit().
625  *
626  * The caller owns the returned ofpbuf and must free it when it is no longer
627  * needed, e.g. with ofpbuf_delete(). */
628 struct ofpbuf *
629 ofpraw_alloc_stats_reply(const struct ofp_header *request,
630                          size_t extra_tailroom)
631 {
632     enum ofpraw request_raw;
633     enum ofpraw reply_raw;
634     enum ofperr error;
635
636     error = ofpraw_decode_partial(&request_raw, request,
637                                   ntohs(request->length));
638     ovs_assert(!error);
639
640     reply_raw = ofpraw_stats_request_to_reply(request_raw, request->version);
641     ovs_assert(reply_raw);
642
643     return ofpraw_alloc_reply(reply_raw, request, extra_tailroom);
644 }
645
646 /* Appends to 'buf' an OpenFlow header for 'raw' with OpenFlow version
647  * 'version' and a fresh OpenFlow transaction ID.  Preallocates enough tailroom
648  * in 'buf' for the minimum body length of 'raw', plus 'extra_tailroom'
649  * additional bytes.
650  *
651  * Each 'raw' value is valid only for certain OpenFlow versions.  The caller
652  * must specify a valid (raw, version) pair.
653  *
654  * Upon return, 'buf->header' points to the beginning of the OpenFlow header
655  * and 'buf->msg' points just after it, to where the message's body will start.
656  * The caller must actually allocating the body into the space reserved for it,
657  * e.g. with ofpbuf_put_uninit(). */
658 void
659 ofpraw_put(enum ofpraw raw, uint8_t version, struct ofpbuf *buf)
660 {
661     ofpraw_put__(raw, version, alloc_xid(), 0, buf);
662 }
663
664 /* Same as ofpraw_put() but the caller provides the transaction ID. */
665 void
666 ofpraw_put_xid(enum ofpraw raw, uint8_t version, ovs_be32 xid,
667                struct ofpbuf *buf)
668 {
669     ofpraw_put__(raw, version, xid, 0, buf);
670 }
671
672 /* Same as ofpraw_put(), but obtains the OpenFlow version and transaction ID
673  * from 'request->version' and 'request->xid', respectively.
674  *
675  * Even though the version comes from 'request->version', the caller must still
676  * know what it is doing, by specifying a valid pairing of 'raw' and
677  * 'request->version', just like ofpraw_put(). */
678 void
679 ofpraw_put_reply(enum ofpraw raw, const struct ofp_header *request,
680                  struct ofpbuf *buf)
681 {
682     ofpraw_put__(raw, request->version, request->xid, 0, buf);
683 }
684
685 /* Appends to 'buf' an OpenFlow header that is a stats reply to the stats
686  * request in 'request', using the same OpenFlow version and transaction ID as
687  * 'request'.  Preallocate enough tailroom in 'buf for the stats reply's
688  * minimum body length, plus 'extra_tailroom' additional bytes.
689  *
690  * 'request' must be a stats request, that is, an OFPRAW_OFPST* or OFPRAW_NXST*
691  * value.  Every stats request has a corresponding reply, so the (raw, version)
692  * pairing pitfalls of the other ofpraw_alloc_*() functions don't apply here.
693  *
694  * In the returned ofpbuf, 'header' points to the beginning of the
695  * OpenFlow header and 'msg' points just after it, to where the
696  * message's body will start.  The caller must actually allocate the
697  * body into the space reserved for it, e.g. with ofpbuf_put_uninit().
698  *
699  * The caller owns the returned ofpbuf and must free it when it is no longer
700  * needed, e.g. with ofpbuf_delete(). */
701 void
702 ofpraw_put_stats_reply(const struct ofp_header *request, struct ofpbuf *buf)
703 {
704     enum ofperr error;
705     enum ofpraw raw;
706
707     error = ofpraw_decode_partial(&raw, request, ntohs(request->length));
708     ovs_assert(!error);
709
710     raw = ofpraw_stats_request_to_reply(raw, request->version);
711     ovs_assert(raw);
712
713     ofpraw_put__(raw, request->version, request->xid, 0, buf);
714 }
715
716 static void
717 ofpraw_put__(enum ofpraw raw, uint8_t version, ovs_be32 xid,
718              size_t extra_tailroom, struct ofpbuf *buf)
719 {
720     const struct raw_info *info = raw_info_get(raw);
721     const struct raw_instance *instance = raw_instance_get(info, version);
722     const struct ofphdrs *hdrs = &instance->hdrs;
723     struct ofp_header *oh;
724
725     ofpbuf_prealloc_tailroom(buf, (instance->hdrs_len + info->min_body
726                                    + extra_tailroom));
727     buf->header = ofpbuf_put_uninit(buf, instance->hdrs_len);
728     buf->msg = ofpbuf_tail(buf);
729
730     oh = buf->header;
731     oh->version = version;
732     oh->type = hdrs->type;
733     oh->length = htons(buf->size);
734     oh->xid = xid;
735
736     if (hdrs->type == OFPT_VENDOR) {
737         struct ofp_vendor_header *ovh = buf->header;
738
739         ovh->vendor = htonl(hdrs->vendor);
740         ovh->subtype = htonl(hdrs->subtype);
741     } else if (version == OFP10_VERSION
742                && (hdrs->type == OFPT10_STATS_REQUEST ||
743                    hdrs->type == OFPT10_STATS_REPLY)) {
744         struct ofp10_stats_msg *osm = buf->header;
745
746         osm->type = htons(hdrs->stat);
747         osm->flags = htons(0);
748
749         if (hdrs->stat == OFPST_VENDOR) {
750             struct ofp10_vendor_stats_msg *ovsm = buf->header;
751
752             ovsm->vendor = htonl(hdrs->vendor);
753             if (hdrs->vendor == NX_VENDOR_ID) {
754                 struct nicira10_stats_msg *nsm = buf->header;
755
756                 nsm->subtype = htonl(hdrs->subtype);
757                 memset(nsm->pad, 0, sizeof nsm->pad);
758             } else {
759                 OVS_NOT_REACHED();
760             }
761         }
762     } else if (version != OFP10_VERSION
763                && (hdrs->type == OFPT11_STATS_REQUEST ||
764                    hdrs->type == OFPT11_STATS_REPLY)) {
765         struct ofp11_stats_msg *osm = buf->header;
766
767         osm->type = htons(hdrs->stat);
768         osm->flags = htons(0);
769         memset(osm->pad, 0, sizeof osm->pad);
770
771         if (hdrs->stat == OFPST_VENDOR) {
772             struct ofp11_vendor_stats_msg *ovsm = buf->header;
773
774             ovsm->vendor = htonl(hdrs->vendor);
775             ovsm->subtype = htonl(hdrs->subtype);
776         }
777     }
778 }
779 \f
780 /* Returns 'raw''s name.
781  *
782  * The name is the name used for 'raw' in the OpenFlow specification.  For
783  * example, ofpraw_get_name(OFPRAW_OFPT10_FEATURES_REPLY) is
784  * "OFPT_FEATURES_REPLY".
785  *
786  * The caller must not modify or free the returned string. */
787 const char *
788 ofpraw_get_name(enum ofpraw raw)
789 {
790     return raw_info_get(raw)->name;
791 }
792
793 /* Returns the stats reply that corresponds to 'raw' in the given OpenFlow
794  * 'version'. */
795 enum ofpraw
796 ofpraw_stats_request_to_reply(enum ofpraw raw, uint8_t version)
797 {
798     const struct raw_info *info = raw_info_get(raw);
799     const struct raw_instance *instance = raw_instance_get(info, version);
800     enum ofpraw reply_raw;
801     struct ofphdrs hdrs;
802     enum ofperr error;
803
804     hdrs = instance->hdrs;
805     switch ((enum ofp_version)hdrs.version) {
806     case OFP10_VERSION:
807         ovs_assert(hdrs.type == OFPT10_STATS_REQUEST);
808         hdrs.type = OFPT10_STATS_REPLY;
809         break;
810     case OFP11_VERSION:
811     case OFP12_VERSION:
812     case OFP13_VERSION:
813     case OFP14_VERSION:
814     case OFP15_VERSION:
815         ovs_assert(hdrs.type == OFPT11_STATS_REQUEST);
816         hdrs.type = OFPT11_STATS_REPLY;
817         break;
818     default:
819         OVS_NOT_REACHED();
820     }
821
822     error = ofpraw_from_ofphdrs(&reply_raw, &hdrs);
823     ovs_assert(!error);
824
825     return reply_raw;
826 }
827 \f
828 /* Determines the OFPTYPE_* type of the OpenFlow message at 'oh', which has
829  * length 'oh->length'.  (The caller must ensure that 'oh->length' bytes of
830  * data are readable at 'oh'.)  On success, returns 0 and stores the type into
831  * '*typep'.  On failure, returns an OFPERR_* error code and zeros '*typep'.
832  *
833  * This function checks that 'oh' is a valid length for its particular type of
834  * message, and returns an error if not. */
835 enum ofperr
836 ofptype_decode(enum ofptype *typep, const struct ofp_header *oh)
837 {
838     enum ofperr error;
839     enum ofpraw raw;
840
841     error = ofpraw_decode(&raw, oh);
842     *typep = error ? 0 : ofptype_from_ofpraw(raw);
843     return error;
844 }
845
846 /* Determines the OFPTYPE_* type of the OpenFlow message in 'msg', which starts
847  * at 'msg->data' and has length 'msg->size' bytes.  On success,
848  * returns 0 and stores the type into '*typep'.  On failure, returns an
849  * OFPERR_* error code and zeros '*typep'.
850  *
851  * This function checks that the message has a valid length for its particular
852  * type of message, and returns an error if not.
853  *
854  * In addition to setting '*typep', this function pulls off the OpenFlow header
855  * (including the stats headers, vendor header, and any subtype header) with
856  * ofpbuf_pull().  It also sets 'msg->header' to the start of the OpenFlow
857  * header and 'msg->msg' just beyond the headers (that is, to the final value
858  * of msg->data). */
859 enum ofperr
860 ofptype_pull(enum ofptype *typep, struct ofpbuf *buf)
861 {
862     enum ofperr error;
863     enum ofpraw raw;
864
865     error = ofpraw_pull(&raw, buf);
866     *typep = error ? 0 : ofptype_from_ofpraw(raw);
867     return error;
868 }
869
870 /* Returns the OFPTYPE_* type that corresponds to 'raw'.
871  *
872  * (This is a one-way trip, because the mapping from ofpraw to ofptype is
873  * many-to-one.)  */
874 enum ofptype
875 ofptype_from_ofpraw(enum ofpraw raw)
876 {
877     return raw_info_get(raw)->type;
878 }
879
880 const char *
881 ofptype_get_name(enum ofptype type)
882 {
883     ovs_assert(type < ARRAY_SIZE(type_names));
884     return type_names[type];
885 }
886 \f
887 /* Updates the 'length' field of the OpenFlow message in 'buf' to
888  * 'buf->size'. */
889 void
890 ofpmsg_update_length(struct ofpbuf *buf)
891 {
892     struct ofp_header *oh = ofpbuf_at_assert(buf, 0, sizeof *oh);
893     oh->length = htons(buf->size);
894 }
895
896 /* Returns just past the OpenFlow header (including the stats headers, vendor
897  * header, and any subtype header) in 'oh'. */
898 const void *
899 ofpmsg_body(const struct ofp_header *oh)
900 {
901     struct ofphdrs hdrs;
902
903     ofphdrs_decode_assert(&hdrs, oh, ntohs(oh->length));
904     return (const uint8_t *) oh + ofphdrs_len(&hdrs);
905 }
906
907 /* Return if it's a stat/multipart (OFPST) request message. */
908 bool
909 ofpmsg_is_stat_request(const struct ofp_header *oh)
910 {
911     return ofp_is_stat_request(oh->version, oh->type);
912 }
913 \f
914 static ovs_be16 *ofpmp_flags__(const struct ofp_header *);
915
916 /* Initializes 'replies' as a new list of stats messages that reply to
917  * 'request', which must be a stats request message.  Initially the list will
918  * consist of only a single reply part without any body.  The caller should
919  * use calls to the other ofpmp_*() functions to add to the body and split the
920  * message into multiple parts, if necessary. */
921 void
922 ofpmp_init(struct ovs_list *replies, const struct ofp_header *request)
923 {
924     struct ofpbuf *msg;
925
926     list_init(replies);
927
928     msg = ofpraw_alloc_stats_reply(request, 1000);
929     list_push_back(replies, &msg->list_node);
930 }
931
932 /* Prepares to append up to 'len' bytes to the series of statistics replies in
933  * 'replies', which should have been initialized with ofpmp_init(), if
934  * necessary adding a new reply to the list.
935  *
936  * Returns an ofpbuf with at least 'len' bytes of tailroom.  The 'len' bytes
937  * have not actually been allocated, so the caller must do so with
938  * e.g. ofpbuf_put_uninit(). */
939 struct ofpbuf *
940 ofpmp_reserve(struct ovs_list *replies, size_t len)
941 {
942     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
943
944     if (msg->size + len <= UINT16_MAX) {
945         ofpbuf_prealloc_tailroom(msg, len);
946         return msg;
947     } else {
948         unsigned int hdrs_len;
949         struct ofpbuf *next;
950         struct ofphdrs hdrs;
951
952         ofphdrs_decode_assert(&hdrs, msg->data, msg->size);
953         hdrs_len = ofphdrs_len(&hdrs);
954
955         next = ofpbuf_new(MAX(1024, hdrs_len + len));
956         ofpbuf_put(next, msg->data, hdrs_len);
957         next->header = next->data;
958         next->msg = ofpbuf_tail(next);
959         list_push_back(replies, &next->list_node);
960
961         *ofpmp_flags__(msg->data) |= htons(OFPSF_REPLY_MORE);
962
963         return next;
964     }
965 }
966
967 /* Appends 'len' bytes to the series of statistics replies in 'replies', and
968  * returns the first byte. */
969 void *
970 ofpmp_append(struct ovs_list *replies, size_t len)
971 {
972     return ofpbuf_put_uninit(ofpmp_reserve(replies, len), len);
973 }
974
975 /* Sometimes, when composing stats replies, it's difficult to predict how long
976  * an individual reply chunk will be before actually encoding it into the reply
977  * buffer.  This function allows easy handling of this case: just encode the
978  * reply, then use this function to break the message into two pieces if it
979  * exceeds the OpenFlow message limit.
980  *
981  * In detail, if the final stats message in 'replies' is too long for OpenFlow,
982  * this function breaks it into two separate stats replies, the first one with
983  * the first 'start_ofs' bytes, the second one containing the bytes from that
984  * offset onward. */
985 void
986 ofpmp_postappend(struct ovs_list *replies, size_t start_ofs)
987 {
988     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
989
990     ovs_assert(start_ofs <= UINT16_MAX);
991     if (msg->size > UINT16_MAX) {
992         size_t len = msg->size - start_ofs;
993         memcpy(ofpmp_append(replies, len),
994                (const uint8_t *) msg->data + start_ofs, len);
995         msg->size = start_ofs;
996     }
997 }
998
999 /* Returns the OpenFlow version of the replies being constructed in 'replies',
1000  * which should have been initialized by ofpmp_init(). */
1001 enum ofp_version
1002 ofpmp_version(struct ovs_list *replies)
1003 {
1004     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
1005     const struct ofp_header *oh = msg->data;
1006
1007     return oh->version;
1008 }
1009
1010 /* Determines the OFPRAW_* type of the OpenFlow messages in 'replies', which
1011  * should have been initialized by ofpmp_init(). */
1012 enum ofpraw
1013 ofpmp_decode_raw(struct ovs_list *replies)
1014 {
1015     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
1016     enum ofperr error;
1017     enum ofpraw raw;
1018
1019     error = ofpraw_decode_partial(&raw, msg->data, msg->size);
1020     ovs_assert(!error);
1021     return raw;
1022 }
1023
1024 static ovs_be16 *
1025 ofpmp_flags__(const struct ofp_header *oh)
1026 {
1027     switch ((enum ofp_version)oh->version) {
1028     case OFP10_VERSION:
1029         return &((struct ofp10_stats_msg *) oh)->flags;
1030     case OFP11_VERSION:
1031     case OFP12_VERSION:
1032     case OFP13_VERSION:
1033     case OFP14_VERSION:
1034     case OFP15_VERSION:
1035         return &((struct ofp11_stats_msg *) oh)->flags;
1036     default:
1037         OVS_NOT_REACHED();
1038     }
1039 }
1040
1041 /* Returns the OFPSF_* flags found in the OpenFlow stats header of 'oh', which
1042  * must be an OpenFlow stats request or reply.
1043  *
1044  * (OFPSF_REPLY_MORE is the only defined flag.) */
1045 uint16_t
1046 ofpmp_flags(const struct ofp_header *oh)
1047 {
1048     return ntohs(*ofpmp_flags__(oh));
1049 }
1050
1051 /* Returns true if the OFPSF_REPLY_MORE flag is set in the OpenFlow stats
1052  * header of 'oh', which must be an OpenFlow stats request or reply, false if
1053  * it is not set. */
1054 bool
1055 ofpmp_more(const struct ofp_header *oh)
1056 {
1057     return (ofpmp_flags(oh) & OFPSF_REPLY_MORE) != 0;
1058 }
1059 \f
1060 static void ofpmsgs_init(void);
1061
1062 static const struct raw_info *
1063 raw_info_get(enum ofpraw raw)
1064 {
1065     ofpmsgs_init();
1066
1067     ovs_assert(raw < ARRAY_SIZE(raw_infos));
1068     return &raw_infos[raw];
1069 }
1070
1071 static struct raw_instance *
1072 raw_instance_get(const struct raw_info *info, uint8_t version)
1073 {
1074     ovs_assert(version >= info->min_version && version <= info->max_version);
1075     return &info->instances[version - info->min_version];
1076 }
1077
1078 static enum ofperr
1079 ofpraw_from_ofphdrs(enum ofpraw *raw, const struct ofphdrs *hdrs)
1080 {
1081     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
1082
1083     struct raw_instance *raw_hdrs;
1084     uint32_t hash;
1085
1086     ofpmsgs_init();
1087
1088     hash = ofphdrs_hash(hdrs);
1089     HMAP_FOR_EACH_WITH_HASH (raw_hdrs, hmap_node, hash, &raw_instance_map) {
1090         if (ofphdrs_equal(hdrs, &raw_hdrs->hdrs)) {
1091             *raw = raw_hdrs->raw;
1092             return 0;
1093         }
1094     }
1095
1096     if (!VLOG_DROP_WARN(&rl)) {
1097         struct ds s;
1098
1099         ds_init(&s);
1100         ds_put_format(&s, "version %"PRIu8", type %"PRIu8,
1101                       hdrs->version, hdrs->type);
1102         if (ofphdrs_is_stat(hdrs)) {
1103             ds_put_format(&s, ", stat %"PRIu16, hdrs->stat);
1104         }
1105         if (hdrs->vendor) {
1106             ds_put_format(&s, ", vendor 0x%"PRIx32", subtype %"PRIu32,
1107                           hdrs->vendor, hdrs->subtype);
1108         }
1109         VLOG_WARN("unknown OpenFlow message (%s)", ds_cstr(&s));
1110         ds_destroy(&s);
1111     }
1112
1113     return (hdrs->vendor ? OFPERR_OFPBRC_BAD_SUBTYPE
1114             : ofphdrs_is_stat(hdrs) ? OFPERR_OFPBRC_BAD_STAT
1115             : OFPERR_OFPBRC_BAD_TYPE);
1116 }
1117
1118 static void
1119 ofpmsgs_init(void)
1120 {
1121     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
1122     const struct raw_info *info;
1123
1124     if (!ovsthread_once_start(&once)) {
1125         return;
1126     }
1127
1128     hmap_init(&raw_instance_map);
1129     for (info = raw_infos; info < &raw_infos[ARRAY_SIZE(raw_infos)]; info++)
1130     {
1131         int n_instances = info->max_version - info->min_version + 1;
1132         struct raw_instance *inst;
1133
1134         for (inst = info->instances;
1135              inst < &info->instances[n_instances];
1136              inst++) {
1137             inst->hdrs_len = ofphdrs_len(&inst->hdrs);
1138             hmap_insert(&raw_instance_map, &inst->hmap_node,
1139                         ofphdrs_hash(&inst->hdrs));
1140         }
1141     }
1142
1143     ovsthread_once_done(&once);
1144 }