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