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