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