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