1 /*
2  *  Copyright (c) 2016, The OpenThread Authors.
3  *  All rights reserved.
4  *
5  *  Redistribution and use in source and binary forms, with or without
6  *  modification, are permitted provided that the following conditions are met:
7  *  1. Redistributions of source code must retain the above copyright
8  *     notice, this list of conditions and the following disclaimer.
9  *  2. Redistributions in binary form must reproduce the above copyright
10  *     notice, this list of conditions and the following disclaimer in the
11  *     documentation and/or other materials provided with the distribution.
12  *  3. Neither the name of the copyright holder nor the
13  *     names of its contributors may be used to endorse or promote products
14  *     derived from this software without specific prior written permission.
15  *
16  *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17  *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20  *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  *  POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 /**
30  * @file
31  *   This file includes definitions for generating and processing CoAP messages.
32  */
33 
34 #ifndef COAP_HEADER_HPP_
35 #define COAP_HEADER_HPP_
36 
37 #include "openthread-core-config.h"
38 
39 #include <openthread/coap.h>
40 
41 #include "common/as_core_type.hpp"
42 #include "common/clearable.hpp"
43 #include "common/code_utils.hpp"
44 #include "common/const_cast.hpp"
45 #include "common/encoding.hpp"
46 #include "common/message.hpp"
47 #include "net/ip6.hpp"
48 #include "net/ip6_address.hpp"
49 #include "net/udp6.hpp"
50 #include "thread/uri_paths.hpp"
51 
52 namespace ot {
53 
54 /**
55  * @namespace ot::Coap
56  * @brief
57  *   This namespace includes definitions for CoAP.
58  *
59  */
60 namespace Coap {
61 
62 /**
63  * @addtogroup core-coap
64  *
65  * @brief
66  *   This module includes definitions for CoAP.
67  *
68  * @{
69  *
70  */
71 
72 class Option;
73 
74 /**
75  * CoAP Type values.
76  *
77  */
78 enum Type : uint8_t
79 {
80     kTypeConfirmable    = OT_COAP_TYPE_CONFIRMABLE,     ///< Confirmable type.
81     kTypeNonConfirmable = OT_COAP_TYPE_NON_CONFIRMABLE, ///< Non-confirmable type.
82     kTypeAck            = OT_COAP_TYPE_ACKNOWLEDGMENT,  ///< Acknowledgment type.
83     kTypeReset          = OT_COAP_TYPE_RESET,           ///< Reset type.
84 };
85 
86 /**
87  * CoAP Code values.
88  *
89  */
90 enum Code : uint8_t
91 {
92     // Request Codes:
93 
94     kCodeEmpty  = OT_COAP_CODE_EMPTY,  ///< Empty message code
95     kCodeGet    = OT_COAP_CODE_GET,    ///< Get
96     kCodePost   = OT_COAP_CODE_POST,   ///< Post
97     kCodePut    = OT_COAP_CODE_PUT,    ///< Put
98     kCodeDelete = OT_COAP_CODE_DELETE, ///< Delete
99 
100     // Response Codes:
101 
102     kCodeResponseMin = OT_COAP_CODE_RESPONSE_MIN, ///< 2.00
103     kCodeCreated     = OT_COAP_CODE_CREATED,      ///< Created
104     kCodeDeleted     = OT_COAP_CODE_DELETED,      ///< Deleted
105     kCodeValid       = OT_COAP_CODE_VALID,        ///< Valid
106     kCodeChanged     = OT_COAP_CODE_CHANGED,      ///< Changed
107     kCodeContent     = OT_COAP_CODE_CONTENT,      ///< Content
108     kCodeContinue    = OT_COAP_CODE_CONTINUE,     ///< RFC7959 Continue
109 
110     // Client Error Codes:
111 
112     kCodeBadRequest         = OT_COAP_CODE_BAD_REQUEST,         ///< Bad Request
113     kCodeUnauthorized       = OT_COAP_CODE_UNAUTHORIZED,        ///< Unauthorized
114     kCodeBadOption          = OT_COAP_CODE_BAD_OPTION,          ///< Bad Option
115     kCodeForbidden          = OT_COAP_CODE_FORBIDDEN,           ///< Forbidden
116     kCodeNotFound           = OT_COAP_CODE_NOT_FOUND,           ///< Not Found
117     kCodeMethodNotAllowed   = OT_COAP_CODE_METHOD_NOT_ALLOWED,  ///< Method Not Allowed
118     kCodeNotAcceptable      = OT_COAP_CODE_NOT_ACCEPTABLE,      ///< Not Acceptable
119     kCodeRequestIncomplete  = OT_COAP_CODE_REQUEST_INCOMPLETE,  ///< RFC7959 Request Entity Incomplete
120     kCodePreconditionFailed = OT_COAP_CODE_PRECONDITION_FAILED, ///< Precondition Failed
121     kCodeRequestTooLarge    = OT_COAP_CODE_REQUEST_TOO_LARGE,   ///< Request Entity Too Large
122     kCodeUnsupportedFormat  = OT_COAP_CODE_UNSUPPORTED_FORMAT,  ///< Unsupported Content-Format
123 
124     // Server Error Codes:
125 
126     kCodeInternalError      = OT_COAP_CODE_INTERNAL_ERROR,      ///< Internal Server Error
127     kCodeNotImplemented     = OT_COAP_CODE_NOT_IMPLEMENTED,     ///< Not Implemented
128     kCodeBadGateway         = OT_COAP_CODE_BAD_GATEWAY,         ///< Bad Gateway
129     kCodeServiceUnavailable = OT_COAP_CODE_SERVICE_UNAVAILABLE, ///< Service Unavailable
130     kCodeGatewayTimeout     = OT_COAP_CODE_GATEWAY_TIMEOUT,     ///< Gateway Timeout
131     kCodeProxyNotSupported  = OT_COAP_CODE_PROXY_NOT_SUPPORTED, ///< Proxying Not Supported
132 };
133 
134 /**
135  * CoAP Option Numbers.
136  *
137  */
138 enum OptionNumber : uint16_t
139 {
140     kOptionIfMatch       = OT_COAP_OPTION_IF_MATCH,       ///< If-Match
141     kOptionUriHost       = OT_COAP_OPTION_URI_HOST,       ///< Uri-Host
142     kOptionETag          = OT_COAP_OPTION_E_TAG,          ///< ETag
143     kOptionIfNoneMatch   = OT_COAP_OPTION_IF_NONE_MATCH,  ///< If-None-Match
144     kOptionObserve       = OT_COAP_OPTION_OBSERVE,        ///< Observe [RFC7641]
145     kOptionUriPort       = OT_COAP_OPTION_URI_PORT,       ///< Uri-Port
146     kOptionLocationPath  = OT_COAP_OPTION_LOCATION_PATH,  ///< Location-Path
147     kOptionUriPath       = OT_COAP_OPTION_URI_PATH,       ///< Uri-Path
148     kOptionContentFormat = OT_COAP_OPTION_CONTENT_FORMAT, ///< Content-Format
149     kOptionMaxAge        = OT_COAP_OPTION_MAX_AGE,        ///< Max-Age
150     kOptionUriQuery      = OT_COAP_OPTION_URI_QUERY,      ///< Uri-Query
151     kOptionAccept        = OT_COAP_OPTION_ACCEPT,         ///< Accept
152     kOptionLocationQuery = OT_COAP_OPTION_LOCATION_QUERY, ///< Location-Query
153     kOptionBlock2        = OT_COAP_OPTION_BLOCK2,         ///< Block2 (RFC7959)
154     kOptionBlock1        = OT_COAP_OPTION_BLOCK1,         ///< Block1 (RFC7959)
155     kOptionSize2         = OT_COAP_OPTION_SIZE2,          ///< Size2 (RFC7959)
156     kOptionProxyUri      = OT_COAP_OPTION_PROXY_URI,      ///< Proxy-Uri
157     kOptionProxyScheme   = OT_COAP_OPTION_PROXY_SCHEME,   ///< Proxy-Scheme
158     kOptionSize1         = OT_COAP_OPTION_SIZE1,          ///< Size1
159 };
160 
161 /**
162  * Implements CoAP message generation and parsing.
163  *
164  */
165 class Message : public ot::Message
166 {
167     friend class Option;
168     friend class MessageQueue;
169 
170 public:
171     static constexpr uint8_t kDefaultTokenLength = OT_COAP_DEFAULT_TOKEN_LENGTH; ///< Default token length.
172     static constexpr uint8_t kMaxReceivedUriPath = 32;                           ///< Max URI path length on rx msgs.
173     static constexpr uint8_t kMaxTokenLength     = OT_COAP_MAX_TOKEN_LENGTH;     ///< Maximum token length.
174 
175     typedef ot::Coap::Type Type; ///< CoAP Type.
176     typedef ot::Coap::Code Code; ///< CoAP Code.
177 
178     /**
179      * CoAP Block1/Block2 Types
180      *
181      */
182     enum BlockType : uint8_t
183     {
184         kBlockType1 = 1,
185         kBlockType2 = 2,
186     };
187 
188     static constexpr uint8_t kBlockSzxBase = 4;
189 
190     /**
191      * Initializes the CoAP header.
192      *
193      */
194     void Init(void);
195 
196     /**
197      * Initializes the CoAP header with specific Type and Code.
198      *
199      * @param[in]  aType  The Type value.
200      * @param[in]  aCode  The Code value.
201      *
202      */
203     void Init(Type aType, Code aCode);
204 
205     /**
206      * Initializes the CoAP header with specific Type and Code.
207      *
208      * @param[in]  aType              The Type value.
209      * @param[in]  aCode              The Code value.
210      * @param[in]  aUri               The URI.
211      *
212      * @retval kErrorNone         Successfully appended the option.
213      * @retval kErrorNoBufs       The option length exceeds the buffer size.
214      *
215      */
216     Error Init(Type aType, Code aCode, Uri aUri);
217 
218     /**
219      * Initializes the CoAP header as `kCodePost` with a given URI Path with its type determined from a
220      * given destination IPv6 address.
221      *
222      * @param[in]  aDestination       The message destination IPv6 address used to determine the CoAP type,
223      *                                `kTypeNonConfirmable` if multicast address, `kTypeConfirmable` otherwise.
224      * @param[in]  aUri               The URI.
225      *
226      * @retval kErrorNone         Successfully appended the option.
227      * @retval kErrorNoBufs       The option length exceeds the buffer size.
228      *
229      */
230     Error InitAsPost(const Ip6::Address &aDestination, Uri aUri);
231 
232     /**
233      * Writes header to the message. This must be called before sending the message.
234      *
235      * Also checks whether the payload marker is set (`SetPayloadMarker()`) but the message contains no
236      * payload, and if so it removes the payload marker from the message.
237      *
238      */
239     void Finish(void);
240 
241     /**
242      * Returns the Version value.
243      *
244      * @returns The Version value.
245      *
246      */
GetVersion(void) const247     uint8_t GetVersion(void) const
248     {
249         return (GetHelpData().mHeader.mVersionTypeToken & kVersionMask) >> kVersionOffset;
250     }
251 
252     /**
253      * Sets the Version value.
254      *
255      * @param[in]  aVersion  The Version value.
256      *
257      */
SetVersion(uint8_t aVersion)258     void SetVersion(uint8_t aVersion)
259     {
260         GetHelpData().mHeader.mVersionTypeToken &= ~kVersionMask;
261         GetHelpData().mHeader.mVersionTypeToken |= aVersion << kVersionOffset;
262     }
263 
264     /**
265      * Returns the Type value.
266      *
267      * @returns The Type value.
268      *
269      */
GetType(void) const270     uint8_t GetType(void) const { return (GetHelpData().mHeader.mVersionTypeToken & kTypeMask) >> kTypeOffset; }
271 
272     /**
273      * Sets the Type value.
274      *
275      * @param[in]  aType  The Type value.
276      *
277      */
SetType(Type aType)278     void SetType(Type aType)
279     {
280         GetHelpData().mHeader.mVersionTypeToken &= ~kTypeMask;
281         GetHelpData().mHeader.mVersionTypeToken |= (static_cast<uint8_t>(aType) << kTypeOffset);
282     }
283 
284     /**
285      * Returns the Code value.
286      *
287      * @returns The Code value.
288      *
289      */
GetCode(void) const290     uint8_t GetCode(void) const { return static_cast<Code>(GetHelpData().mHeader.mCode); }
291 
292     /**
293      * Sets the Code value.
294      *
295      * @param[in]  aCode  The Code value.
296      *
297      */
SetCode(Code aCode)298     void SetCode(Code aCode) { GetHelpData().mHeader.mCode = static_cast<uint8_t>(aCode); }
299 
300 #if OPENTHREAD_CONFIG_COAP_API_ENABLE
301     /**
302      * Returns the CoAP Code as human readable string.
303      *
304      * @ returns The CoAP Code as string.
305      *
306      */
307     const char *CodeToString(void) const;
308 #endif // OPENTHREAD_CONFIG_COAP_API_ENABLE
309 
310     /**
311      * Returns the Message ID value.
312      *
313      * @returns The Message ID value.
314      *
315      */
GetMessageId(void) const316     uint16_t GetMessageId(void) const { return BigEndian::HostSwap16(GetHelpData().mHeader.mMessageId); }
317 
318     /**
319      * Sets the Message ID value.
320      *
321      * @param[in]  aMessageId  The Message ID value.
322      *
323      */
SetMessageId(uint16_t aMessageId)324     void SetMessageId(uint16_t aMessageId) { GetHelpData().mHeader.mMessageId = BigEndian::HostSwap16(aMessageId); }
325 
326     /**
327      * Returns the Token length.
328      *
329      * @returns The Token length.
330      *
331      */
GetTokenLength(void) const332     uint8_t GetTokenLength(void) const
333     {
334         return (GetHelpData().mHeader.mVersionTypeToken & kTokenLengthMask) >> kTokenLengthOffset;
335     }
336 
337     /**
338      * Returns a pointer to the Token value.
339      *
340      * @returns A pointer to the Token value.
341      *
342      */
GetToken(void) const343     const uint8_t *GetToken(void) const { return GetHelpData().mHeader.mToken; }
344 
345     /**
346      * Sets the Token value and length.
347      *
348      * @param[in]  aToken        A pointer to the Token value.
349      * @param[in]  aTokenLength  The Length of @p aToken.
350      *
351      * @retval kErrorNone    Successfully set the token value.
352      * @retval kErrorNoBufs  Insufficient message buffers available to set the token value.
353      *
354      */
355     Error SetToken(const uint8_t *aToken, uint8_t aTokenLength);
356 
357     /**
358      * Sets the Token value and length by copying it from another given message.
359      *
360      * @param[in] aMessage       The message to copy the Token from.
361      *
362      * @retval kErrorNone    Successfully set the token value.
363      * @retval kErrorNoBufs  Insufficient message buffers available to set the token value.
364      *
365      */
366     Error SetTokenFromMessage(const Message &aMessage);
367 
368     /**
369      * Sets the Token length and randomizes its value.
370      *
371      * @param[in]  aTokenLength  The Length of a Token to set.
372      *
373      * @retval kErrorNone    Successfully set the token value.
374      * @retval kErrorNoBufs  Insufficient message buffers available to set the token value.
375      *
376      */
377     Error GenerateRandomToken(uint8_t aTokenLength);
378 
379     /**
380      * Checks if Tokens in two CoAP headers are equal.
381      *
382      * @param[in]  aMessage  A header to compare.
383      *
384      * @retval TRUE   If two Tokens are equal.
385      * @retval FALSE  If Tokens differ in length or value.
386      *
387      */
388     bool IsTokenEqual(const Message &aMessage) const;
389 
390     /**
391      * Appends a CoAP option.
392      *
393      * @param[in] aNumber   The CoAP Option number.
394      * @param[in] aLength   The CoAP Option length.
395      * @param[in] aValue    A pointer to the CoAP Option value (@p aLength bytes are used as Option value).
396      *
397      * @retval kErrorNone         Successfully appended the option.
398      * @retval kErrorInvalidArgs  The option type is not equal or greater than the last option type.
399      * @retval kErrorNoBufs       The option length exceeds the buffer size.
400      *
401      */
402     Error AppendOption(uint16_t aNumber, uint16_t aLength, const void *aValue);
403 
404     /**
405      * Appends an unsigned integer CoAP option as specified in RFC-7252 section-3.2
406      *
407      * @param[in]  aNumber  The CoAP Option number.
408      * @param[in]  aValue   The CoAP Option unsigned integer value.
409      *
410      * @retval kErrorNone         Successfully appended the option.
411      * @retval kErrorInvalidArgs  The option type is not equal or greater than the last option type.
412      * @retval kErrorNoBufs       The option length exceeds the buffer size.
413      *
414      */
415     Error AppendUintOption(uint16_t aNumber, uint32_t aValue);
416 
417     /**
418      * Appends a string CoAP option.
419      *
420      * @param[in]  aNumber  The CoAP Option number.
421      * @param[in]  aValue   The CoAP Option string value.
422      *
423      * @retval kErrorNone         Successfully appended the option.
424      * @retval kErrorInvalidArgs  The option type is not equal or greater than the last option type.
425      * @retval kErrorNoBufs       The option length exceeds the buffer size.
426      *
427      */
428     Error AppendStringOption(uint16_t aNumber, const char *aValue);
429 
430     /**
431      * Appends an Observe option.
432      *
433      * @param[in]  aObserve  Observe field value.
434      *
435      * @retval kErrorNone         Successfully appended the option.
436      * @retval kErrorInvalidArgs  The option type is not equal or greater than the last option type.
437      * @retval kErrorNoBufs       The option length exceeds the buffer size.
438      */
AppendObserveOption(uint32_t aObserve)439     Error AppendObserveOption(uint32_t aObserve) { return AppendUintOption(kOptionObserve, aObserve & kObserveMask); }
440 
441     /**
442      * Appends a Uri-Path option.
443      *
444      * @param[in]  aUriPath           A pointer to a null-terminated string.
445      *
446      * @retval kErrorNone         Successfully appended the option.
447      * @retval kErrorInvalidArgs  The option type is not equal or greater than the last option type.
448      * @retval kErrorNoBufs       The option length exceeds the buffer size.
449      *
450      */
451     Error AppendUriPathOptions(const char *aUriPath);
452 
453     /**
454      * Reads the Uri-Path options and constructs the URI path in the buffer referenced by @p `aUriPath`.
455      *
456      * @param[in] aUriPath  A reference to the buffer for storing URI path.
457      *                      NOTE: The buffer size must be `kMaxReceivedUriPath + 1`.
458      *
459      * @retval  kErrorNone   Successfully read the Uri-Path options.
460      * @retval  kErrorParse  CoAP Option header not well-formed.
461      *
462      */
463     Error ReadUriPathOptions(char (&aUriPath)[kMaxReceivedUriPath + 1]) const;
464 
465     /**
466      * Appends a Block option
467      *
468      * @param[in]  aType              Type of block option, 1 or 2.
469      * @param[in]  aNum               Current block number.
470      * @param[in]  aMore              Boolean to indicate more blocks are to be sent.
471      * @param[in]  aSize              Maximum block size.
472      *
473      * @retval kErrorNone         Successfully appended the option.
474      * @retval kErrorInvalidArgs  The option type is not equal or greater than the last option type.
475      * @retval kErrorNoBufs       The option length exceeds the buffer size.
476      *
477      */
478     Error AppendBlockOption(BlockType aType, uint32_t aNum, bool aMore, otCoapBlockSzx aSize);
479 
480     /**
481      * Appends a Proxy-Uri option.
482      *
483      * @param[in]  aProxyUri          A pointer to a null-terminated string.
484      *
485      * @retval kErrorNone         Successfully appended the option.
486      * @retval kErrorInvalidArgs  The option type is not equal or greater than the last option type.
487      * @retval kErrorNoBufs       The option length exceeds the buffer size.
488      *
489      */
AppendProxyUriOption(const char * aProxyUri)490     Error AppendProxyUriOption(const char *aProxyUri) { return AppendStringOption(kOptionProxyUri, aProxyUri); }
491 
492     /**
493      * Appends a Content-Format option.
494      *
495      * @param[in]  aContentFormat  The Content Format value.
496      *
497      * @retval kErrorNone         Successfully appended the option.
498      * @retval kErrorInvalidArgs  The option type is not equal or greater than the last option type.
499      * @retval kErrorNoBufs       The option length exceeds the buffer size.
500      *
501      */
AppendContentFormatOption(otCoapOptionContentFormat aContentFormat)502     Error AppendContentFormatOption(otCoapOptionContentFormat aContentFormat)
503     {
504         return AppendUintOption(kOptionContentFormat, static_cast<uint32_t>(aContentFormat));
505     }
506 
507     /**
508      * Appends a Max-Age option.
509      *
510      * @param[in]  aMaxAge  The Max-Age value.
511      *
512      * @retval kErrorNone         Successfully appended the option.
513      * @retval kErrorInvalidArgs  The option type is not equal or greater than the last option type.
514      * @retval kErrorNoBufs       The option length exceeds the buffer size.
515      */
AppendMaxAgeOption(uint32_t aMaxAge)516     Error AppendMaxAgeOption(uint32_t aMaxAge) { return AppendUintOption(kOptionMaxAge, aMaxAge); }
517 
518     /**
519      * Appends a single Uri-Query option.
520      *
521      * @param[in]  aUriQuery  A pointer to null-terminated string, which should contain a single key=value pair.
522      *
523      * @retval kErrorNone         Successfully appended the option.
524      * @retval kErrorInvalidArgs  The option type is not equal or greater than the last option type.
525      * @retval kErrorNoBufs       The option length exceeds the buffer size.
526      */
AppendUriQueryOption(const char * aUriQuery)527     Error AppendUriQueryOption(const char *aUriQuery) { return AppendStringOption(kOptionUriQuery, aUriQuery); }
528 
529 #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE
530     /**
531      * Reads the information contained in a Block1 or Block2 option and set it in
532      * the HelpData of the message.
533      *
534      * @param[in]   aBlockType  Block1 or Block2 option value.
535      *
536      * @retval  kErrorNone          The option has been found and is valid.
537      * @retval  kErrorNotFound      The option has not been found.
538      * @retval  kErrorInvalidArgs   The option is invalid.
539      */
540     Error ReadBlockOptionValues(uint16_t aBlockType);
541 
542     /**
543      * Returns the current header length of a message.
544      *
545      * @returns The length of the message header.
546      *
547      */
GetHeaderLength(void) const548     uint16_t GetHeaderLength(void) const { return GetHelpData().mHeaderLength; }
549 
550     /**
551      * Returns the block number of a CoAP block-wise transfer message.
552      *
553      * @returns The block number.
554      *
555      */
GetBlockWiseBlockNumber(void) const556     uint32_t GetBlockWiseBlockNumber(void) const { return GetHelpData().mBlockWiseData.mBlockNumber; }
557 
558     /**
559      * Checks if the More Blocks flag is set.
560      *
561      * @retval TRUE   More Blocks flag is set.
562      * @retval FALSE  More Blocks flag is not set.
563      *
564      */
IsMoreBlocksFlagSet(void) const565     bool IsMoreBlocksFlagSet(void) const { return GetHelpData().mBlockWiseData.mMoreBlocks; }
566 
567     /**
568      * Returns the block size of a CoAP block-wise transfer message.
569      *
570      * @returns The block size.
571      *
572      */
GetBlockWiseBlockSize(void) const573     otCoapBlockSzx GetBlockWiseBlockSize(void) const { return GetHelpData().mBlockWiseData.mBlockSize; }
574 #endif // OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE
575 
576     /**
577      * Reads and reassembles the URI path string and fills it into @p aUriPath.
578      *
579      * @retval  kErrorNone      URI path string has been reassembled.
580      * @retval  kErrorNoBufs    URI path string is too long.
581      *
582      */
583     Error GetUriPath(char *aUriPath) const;
584 
585     /**
586      * Adds Payload Marker indicating beginning of the payload to the CoAP header.
587      *
588      * It also set offset to the start of payload.
589      *
590      * @retval kErrorNone    Payload Marker successfully added.
591      * @retval kErrorNoBufs  Message Payload Marker exceeds the buffer size.
592      *
593      */
594     Error SetPayloadMarker(void);
595 
596     /**
597      * Returns the offset of the first CoAP option.
598      *
599      * @returns The offset of the first CoAP option.
600      *
601      */
GetOptionStart(void) const602     uint16_t GetOptionStart(void) const { return kMinHeaderLength + GetTokenLength(); }
603 
604     /**
605      * Parses CoAP header and moves offset end of CoAP header.
606      *
607      * @retval  kErrorNone   Successfully parsed CoAP header from the message.
608      * @retval  kErrorParse  Failed to parse the CoAP header.
609      *
610      */
611     Error ParseHeader(void);
612 
613     /**
614      * Sets a default response header based on request header.
615      *
616      * @param[in]  aRequest  The request message.
617      *
618      * @retval kErrorNone    Successfully set the default response header.
619      * @retval kErrorNoBufs  Insufficient message buffers available to set the default response header.
620      *
621      */
622     Error SetDefaultResponseHeader(const Message &aRequest);
623 
624 #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE
625 
626     /**
627      * Sets the block number value in the message HelpData.
628      *
629      * @param[in]   aBlockNumber    Block number value to set.
630      *
631      */
SetBlockWiseBlockNumber(uint32_t aBlockNumber)632     void SetBlockWiseBlockNumber(uint32_t aBlockNumber) { GetHelpData().mBlockWiseData.mBlockNumber = aBlockNumber; }
633 
634     /**
635      * Sets the More Blocks flag in the message HelpData.
636      *
637      * @param[in]   aMoreBlocks    TRUE or FALSE.
638      *
639      */
SetMoreBlocksFlag(bool aMoreBlocks)640     void SetMoreBlocksFlag(bool aMoreBlocks) { GetHelpData().mBlockWiseData.mMoreBlocks = aMoreBlocks; }
641 
642     /**
643      * Sets the block size value in the message HelpData.
644      *
645      * @param[in]   aBlockSize    Block size value to set.
646      *
647      */
SetBlockWiseBlockSize(otCoapBlockSzx aBlockSize)648     void SetBlockWiseBlockSize(otCoapBlockSzx aBlockSize) { GetHelpData().mBlockWiseData.mBlockSize = aBlockSize; }
649 #endif // OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE
650 
651     /**
652      * Checks if a header is an empty message header.
653      *
654      * @retval TRUE   Message is an empty message header.
655      * @retval FALSE  Message is not an empty message header.
656      *
657      */
IsEmpty(void) const658     bool IsEmpty(void) const { return (GetCode() == kCodeEmpty); }
659 
660     /**
661      * Checks if a header is a request header.
662      *
663      * @retval TRUE   Message is a request header.
664      * @retval FALSE  Message is not a request header.
665      *
666      */
IsRequest(void) const667     bool IsRequest(void) const { return (GetCode() >= kCodeGet) && (GetCode() <= kCodeDelete); }
668 
669     /**
670      * Indicates whether or not the CoAP code in header is "Get" request.
671      *
672      * @retval TRUE   Message is a Get request.
673      * @retval FALSE  Message is not a Get request.
674      *
675      */
IsGetRequest(void) const676     bool IsGetRequest(void) const { return GetCode() == kCodeGet; }
677 
678     /**
679      * Indicates whether or not the CoAP code in header is "Post" request.
680      *
681      * @retval TRUE   Message is a Post request.
682      * @retval FALSE  Message is not a Post request.
683      *
684      */
IsPostRequest(void) const685     bool IsPostRequest(void) const { return GetCode() == kCodePost; }
686 
687     /**
688      * Indicates whether or not the CoAP code in header is "Put" request.
689      *
690      * @retval TRUE   Message is a Put request.
691      * @retval FALSE  Message is not a Put request.
692      *
693      */
IsPutRequest(void) const694     bool IsPutRequest(void) const { return GetCode() == kCodePut; }
695 
696     /**
697      * Indicates whether or not the CoAP code in header is "Delete" request.
698      *
699      * @retval TRUE   Message is a Delete request.
700      * @retval FALSE  Message is not a Delete request.
701      *
702      */
IsDeleteRequest(void) const703     bool IsDeleteRequest(void) const { return GetCode() == kCodeDelete; }
704 
705     /**
706      * Checks if a header is a response header.
707      *
708      * @retval TRUE   Message is a response header.
709      * @retval FALSE  Message is not a response header.
710      *
711      */
IsResponse(void) const712     bool IsResponse(void) const { return GetCode() >= OT_COAP_CODE_RESPONSE_MIN; }
713 
714     /**
715      * Checks if a header is a CON message header.
716      *
717      * @retval TRUE   Message is a CON message header.
718      * @retval FALSE  Message is not is a CON message header.
719      *
720      */
IsConfirmable(void) const721     bool IsConfirmable(void) const { return (GetType() == kTypeConfirmable); }
722 
723     /**
724      * Checks if a header is a NON message header.
725      *
726      * @retval TRUE   Message is a NON message header.
727      * @retval FALSE  Message is not is a NON message header.
728      *
729      */
IsNonConfirmable(void) const730     bool IsNonConfirmable(void) const { return (GetType() == kTypeNonConfirmable); }
731 
732     /**
733      * Checks if a header is a ACK message header.
734      *
735      * @retval TRUE   Message is a ACK message header.
736      * @retval FALSE  Message is not is a ACK message header.
737      *
738      */
IsAck(void) const739     bool IsAck(void) const { return (GetType() == kTypeAck); }
740 
741     /**
742      * Checks if a header is a RST message header.
743      *
744      * @retval TRUE   Message is a RST message header.
745      * @retval FALSE  Message is not is a RST message header.
746      *
747      */
IsReset(void) const748     bool IsReset(void) const { return (GetType() == kTypeReset); }
749 
750     /**
751      * Indicates whether or not the header is a confirmable Put request (i.e, `kTypeConfirmable` with
752      *  `kCodePost`).
753      *
754      * @retval TRUE   Message is a confirmable Post request.
755      * @retval FALSE  Message is not a confirmable Post request.
756      *
757      */
758     bool IsConfirmablePostRequest(void) const;
759 
760     /**
761      * Indicates whether or not the header is a non-confirmable Put request (i.e, `kTypeNonConfirmable` with
762      *  `kCodePost`).
763      *
764      * @retval TRUE   Message is a non-confirmable Post request.
765      * @retval FALSE  Message is not a non-confirmable Post request.
766      *
767      */
768     bool IsNonConfirmablePostRequest(void) const;
769 
770     /**
771      * Creates a copy of this CoAP message.
772      *
773      * It allocates the new message from the same message pool as the original one and copies @p aLength octets
774      * of the payload. The `Type`, `SubType`, `LinkSecurity`, `Offset`, `InterfaceId`, and `Priority` fields on the
775      * cloned message are also copied from the original one.
776      *
777      * @param[in] aLength  Number of payload bytes to copy.
778      *
779      * @returns A pointer to the message or `nullptr` if insufficient message buffers are available.
780      *
781      */
782     Message *Clone(uint16_t aLength) const;
783 
784     /**
785      * Creates a copy of the message.
786      *
787      * It allocates the new message from the same message pool as the original one and copies the entire payload. The
788      * `Type`, `SubType`, `LinkSecurity`, `Offset`, `InterfaceId`, and `Priority` fields on the cloned message are also
789      * copied from the original one.
790      *
791      * @returns A pointer to the message or `nullptr` if insufficient message buffers are available.
792      *
793      */
Clone(void) const794     Message *Clone(void) const { return Clone(GetLength()); }
795 
796     /**
797      * Returns the minimal reserved bytes required for CoAP message.
798      *
799      */
GetHelpDataReserved(void)800     static uint16_t GetHelpDataReserved(void) { return sizeof(HelpData) + kHelpDataAlignment; }
801 
802     /**
803      * Returns a pointer to the next message after this as a `Coap::Message`.
804      *
805      * Should be used when the message is in a `Coap::MessageQueue` (i.e., a queue containing only CoAP
806      * messages).
807      *
808      * @returns A pointer to the next message in the queue or `nullptr` if at the end of the queue.
809      *
810      */
GetNextCoapMessage(void)811     Message *GetNextCoapMessage(void) { return static_cast<Message *>(GetNext()); }
812 
813     /**
814      * Returns a pointer to the next message after this as a `Coap::Message`.
815      *
816      * Should be used when the message is in a `Coap::MessageQueue` (i.e., a queue containing only CoAP
817      * messages).
818      *
819      * @returns A pointer to the next message in the queue or `nullptr` if at the end of the queue.
820      *
821      */
GetNextCoapMessage(void) const822     const Message *GetNextCoapMessage(void) const { return static_cast<const Message *>(GetNext()); }
823 
824 private:
825     /*
826      * Header field first byte (RFC 7252).
827      *
828      *    7 6 5 4 3 2 1 0
829      *   +-+-+-+-+-+-+-+-+
830      *   |Ver| T |  TKL  |  (Version, Type and Token Length).
831      *   +-+-+-+-+-+-+-+-+
832      */
833     static constexpr uint8_t kVersionOffset     = 6;
834     static constexpr uint8_t kVersionMask       = 0x3 << kVersionOffset;
835     static constexpr uint8_t kVersion1          = 1;
836     static constexpr uint8_t kTypeOffset        = 4;
837     static constexpr uint8_t kTypeMask          = 0x3 << kTypeOffset;
838     static constexpr uint8_t kTokenLengthOffset = 0;
839     static constexpr uint8_t kTokenLengthMask   = 0xf << kTokenLengthOffset;
840 
841     /*
842      *
843      * Option Format (RFC 7252).
844      *
845      *      7   6   5   4   3   2   1   0
846      *    +---------------+---------------+
847      *    |  Option Delta | Option Length |   1 byte
848      *    +---------------+---------------+
849      *    /         Option Delta          /   0-2 bytes
850      *    \          (extended)           \
851      *    +-------------------------------+
852      *    /         Option Length         /   0-2 bytes
853      *    \          (extended)           \
854      *    +-------------------------------+
855      *    /         Option Value          /   0 or more bytes
856      *    +-------------------------------+
857      *
858      */
859 
860     static constexpr uint8_t kOptionDeltaOffset  = 4;
861     static constexpr uint8_t kOptionDeltaMask    = 0xf << kOptionDeltaOffset;
862     static constexpr uint8_t kOptionLengthOffset = 0;
863     static constexpr uint8_t kOptionLengthMask   = 0xf << kOptionLengthOffset;
864 
865     static constexpr uint8_t kMaxOptionHeaderSize = 5;
866 
867     static constexpr uint8_t kOption1ByteExtension = 13; // Indicates a one-byte extension.
868     static constexpr uint8_t kOption2ByteExtension = 14; // Indicates a two-byte extension.
869 
870     static constexpr uint8_t kPayloadMarker = 0xff;
871 
872     static constexpr uint8_t kHelpDataAlignment = sizeof(uint16_t); // Alignment of help data.
873 
874     static constexpr uint16_t kMinHeaderLength = 4;
875     static constexpr uint16_t kMaxHeaderLength = 512;
876 
877     static constexpr uint16_t kOption1ByteExtensionOffset = 13;  // Delta/Length offset as specified (RFC 7252).
878     static constexpr uint16_t kOption2ByteExtensionOffset = 269; // Delta/Length offset as specified (RFC 7252).
879 
880     static constexpr uint8_t kBlockSzxOffset = 0;
881     static constexpr uint8_t kBlockMOffset   = 3;
882     static constexpr uint8_t kBlockNumOffset = 4;
883 
884     static constexpr uint32_t kObserveMask = 0xffffff;
885     static constexpr uint32_t kBlockNumMax = 0xffff;
886 
887 #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE
888     struct BlockWiseData
889     {
890         uint32_t       mBlockNumber;
891         bool           mMoreBlocks;
892         otCoapBlockSzx mBlockSize;
893     };
894 #endif
895 
896     /**
897      * Represents a CoAP header excluding CoAP options.
898      *
899      */
900     OT_TOOL_PACKED_BEGIN
901     struct Header
902     {
903         uint8_t  mVersionTypeToken;       ///< The CoAP Version, Type, and Token Length
904         uint8_t  mCode;                   ///< The CoAP Code
905         uint16_t mMessageId;              ///< The CoAP Message ID
906         uint8_t  mToken[kMaxTokenLength]; ///< The CoAP Token
907     } OT_TOOL_PACKED_END;
908 
909     /**
910      * Represents a HelpData used by this CoAP message.
911      *
912      */
913     struct HelpData : public Clearable<HelpData>
914     {
915         Header   mHeader;
916         uint16_t mOptionLast;
917         uint16_t mHeaderOffset; ///< The byte offset for the CoAP Header
918         uint16_t mHeaderLength;
919         bool     mPayloadMarkerSet;
920 #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE
921         BlockWiseData mBlockWiseData;
922 #endif
923     };
924 
925     class ConstIterator : public ot::Message::ConstIterator
926     {
927     public:
928         using ot::Message::ConstIterator::ConstIterator;
929 
operator *(void)930         const Message &operator*(void) { return static_cast<const Message &>(ot::Message::ConstIterator::operator*()); }
operator ->(void)931         const Message *operator->(void)
932         {
933             return static_cast<const Message *>(ot::Message::ConstIterator::operator->());
934         }
935     };
936 
937     class Iterator : public ot::Message::Iterator
938     {
939     public:
940         using ot::Message::Iterator::Iterator;
941 
operator *(void)942         Message &operator*(void) { return static_cast<Message &>(ot::Message::Iterator::operator*()); }
operator ->(void)943         Message *operator->(void) { return static_cast<Message *>(ot::Message::Iterator::operator->()); }
944     };
945 
946     static_assert(sizeof(HelpData) <= sizeof(Ip6::Header) + sizeof(Ip6::HopByHopHeader) + sizeof(Ip6::MplOption) +
947                                           sizeof(Ip6::Udp::Header),
948                   "HelpData size exceeds the size of the reserved region in the message");
949 
GetHelpData(void) const950     const HelpData &GetHelpData(void) const
951     {
952         static_assert(sizeof(HelpData) + kHelpDataAlignment <= kHeadBufferDataSize,
953                       "Insufficient buffer size for CoAP processing! Increase OPENTHREAD_CONFIG_MESSAGE_BUFFER_SIZE.");
954 
955         return *static_cast<const HelpData *>(OT_ALIGN(GetFirstData(), kHelpDataAlignment));
956     }
957 
GetHelpData(void)958     HelpData &GetHelpData(void) { return AsNonConst(AsConst(this)->GetHelpData()); }
959 
GetToken(void)960     uint8_t *GetToken(void) { return GetHelpData().mHeader.mToken; }
961 
SetTokenLength(uint8_t aTokenLength)962     void SetTokenLength(uint8_t aTokenLength)
963     {
964         GetHelpData().mHeader.mVersionTypeToken &= ~kTokenLengthMask;
965         GetHelpData().mHeader.mVersionTypeToken |= ((aTokenLength << kTokenLengthOffset) & kTokenLengthMask);
966     }
967 
968     uint8_t WriteExtendedOptionField(uint16_t aValue, uint8_t *&aBuffer);
969 };
970 
971 /**
972  * Implements a CoAP message queue.
973  *
974  */
975 class MessageQueue : public ot::MessageQueue
976 {
977 public:
978     /**
979      * Initializes the message queue.
980      *
981      */
982     MessageQueue(void) = default;
983 
984     /**
985      * Returns a pointer to the first message.
986      *
987      * @returns A pointer to the first message.
988      *
989      */
GetHead(void)990     Message *GetHead(void) { return static_cast<Message *>(ot::MessageQueue::GetHead()); }
991 
992     /**
993      * Returns a pointer to the first message.
994      *
995      * @returns A pointer to the first message.
996      *
997      */
GetHead(void) const998     const Message *GetHead(void) const { return static_cast<const Message *>(ot::MessageQueue::GetHead()); }
999 
1000     /**
1001      * Adds a message to the end of the queue.
1002      *
1003      * @param[in]  aMessage  The message to add.
1004      *
1005      */
Enqueue(Message & aMessage)1006     void Enqueue(Message &aMessage) { Enqueue(aMessage, kQueuePositionTail); }
1007 
1008     /**
1009      * Adds a message at a given position (head/tail) of the queue.
1010      *
1011      * @param[in]  aMessage  The message to add.
1012      * @param[in]  aPosition The position (head or tail) where to add the message.
1013      *
1014      */
Enqueue(Message & aMessage,QueuePosition aPosition)1015     void Enqueue(Message &aMessage, QueuePosition aPosition) { ot::MessageQueue::Enqueue(aMessage, aPosition); }
1016 
1017     /**
1018      * Removes a message from the queue.
1019      *
1020      * @param[in]  aMessage  The message to remove.
1021      *
1022      */
Dequeue(Message & aMessage)1023     void Dequeue(Message &aMessage) { ot::MessageQueue::Dequeue(aMessage); }
1024 
1025     /**
1026      * Removes a message from the queue and frees it.
1027      *
1028      * @param[in]  aMessage  The message to remove and free.
1029      *
1030      */
DequeueAndFree(Message & aMessage)1031     void DequeueAndFree(Message &aMessage) { ot::MessageQueue::DequeueAndFree(aMessage); }
1032 
1033     // The following methods are intended to support range-based `for`
1034     // loop iteration over the queue entries and should not be used
1035     // directly. The range-based `for` works correctly even if the
1036     // current entry is removed from the queue during iteration.
1037 
1038     Message::Iterator begin(void);
end(void)1039     Message::Iterator end(void) { return Message::Iterator(); }
1040 
1041     Message::ConstIterator begin(void) const;
end(void) const1042     Message::ConstIterator end(void) const { return Message::ConstIterator(); }
1043 };
1044 
1045 /**
1046  * Represents a CoAP option.
1047  *
1048  */
1049 class Option : public otCoapOption
1050 {
1051 public:
1052     /**
1053      * Represents an iterator for CoAP options.
1054      *
1055      */
1056     class Iterator : public otCoapOptionIterator
1057     {
1058     public:
1059         /**
1060          * Initializes the iterator to iterate over CoAP Options in a CoAP message.
1061          *
1062          * The iterator MUST be initialized before any other methods are used, otherwise its behavior is undefined.
1063          *
1064          * After initialization, the iterator is either updated to point to the first option, or it is marked as done
1065          * (i.e., `IsDone()` returns `true`) when there is no option or if there is a parse error.
1066          *
1067          * @param[in] aMessage  The CoAP message.
1068          *
1069          * @retval kErrorNone   Successfully initialized. Iterator is either at the first option or done.
1070          * @retval kErrorParse  CoAP Option header in @p aMessage is not well-formed.
1071          *
1072          */
1073         Error Init(const Message &aMessage);
1074 
1075         /**
1076          * Initializes the iterator to iterate over CoAP Options in a CoAP message matching a given Option
1077          * Number value.
1078          *
1079          * The iterator MUST be initialized before any other methods are used, otherwise its behavior is undefined.
1080          *
1081          * After initialization, the iterator is either updated to point to the first option matching the given Option
1082          * Number value, or it is marked as done (i.e., `IsDone()` returns `true`) when there is no matching option or
1083          * if there is a parse error.
1084          *
1085          * @param[in] aMessage  The CoAP message.
1086          * @param[in] aNumber   The CoAP Option Number.
1087          *
1088          * @retval  kErrorNone   Successfully initialized. Iterator is either at the first matching option or done.
1089          * @retval  kErrorParse  CoAP Option header in @p aMessage is not well-formed.
1090          *
1091          */
Init(const Message & aMessage,uint16_t aNumber)1092         Error Init(const Message &aMessage, uint16_t aNumber) { return InitOrAdvance(&aMessage, aNumber); }
1093 
1094         /**
1095          * Indicates whether or not the iterator is done (i.e., has reached the end of CoAP Option Header).
1096          *
1097          * @retval TRUE   Iterator is done (reached end of Option header).
1098          * @retval FALSE  Iterator is not done and currently pointing to a CoAP Option.
1099          *
1100          */
IsDone(void) const1101         bool IsDone(void) const { return mOption.mLength == kIteratorDoneLength; }
1102 
1103         /**
1104          * Indicates whether or not there was a earlier parse error (i.e., whether the iterator is valid).
1105          *
1106          * After a parse errors, iterator would also be marked as done.
1107          *
1108          * @retval TRUE   There was an earlier parse error and the iterator is not valid.
1109          * @retval FALSE  There was no earlier parse error and the iterator is valid.
1110          *
1111          */
HasParseErrored(void) const1112         bool HasParseErrored(void) const { return mNextOptionOffset == kNextOptionOffsetParseError; }
1113 
1114         /**
1115          * Advances the iterator to the next CoAP Option in the header.
1116          *
1117          * The iterator is updated to point to the next option or marked as done when there are no more options.
1118          *
1119          * @retval  kErrorNone   Successfully advanced the iterator.
1120          * @retval  kErrorParse  CoAP Option header is not well-formed.
1121          *
1122          */
1123         Error Advance(void);
1124 
1125         /**
1126          * Advances the iterator to the next CoAP Option in the header matching a given Option Number value.
1127          *
1128          * The iterator is updated to point to the next matching option or marked as done when there are no more
1129          * matching options.
1130          *
1131          * @param[in] aNumber   The CoAP Option Number.
1132          *
1133          * @retval  kErrorNone   Successfully advanced the iterator.
1134          * @retval  kErrorParse  CoAP Option header is not well-formed.
1135          *
1136          */
Advance(uint16_t aNumber)1137         Error Advance(uint16_t aNumber) { return InitOrAdvance(nullptr, aNumber); }
1138 
1139         /**
1140          * Gets the CoAP message associated with the iterator.
1141          *
1142          * @returns A reference to the CoAP message.
1143          *
1144          */
GetMessage(void) const1145         const Message &GetMessage(void) const { return *static_cast<const Message *>(mMessage); }
1146 
1147         /**
1148          * Gets a pointer to the current CoAP Option to which the iterator is currently pointing.
1149          *
1150          * @returns A pointer to the current CoAP Option, or `nullptr` if iterator is done (or there was an earlier
1151          *          parse error).
1152          *
1153          */
GetOption(void) const1154         const Option *GetOption(void) const { return IsDone() ? nullptr : static_cast<const Option *>(&mOption); }
1155 
1156         /**
1157          * Reads the current Option Value into a given buffer.
1158          *
1159          * @param[out]  aValue   The pointer to a buffer to copy the Option Value. The buffer is assumed to be
1160          *                       sufficiently large (i.e. at least `GetOption()->GetLength()` bytes).
1161          *
1162          * @retval kErrorNone       Successfully read and copied the Option Value into given buffer.
1163          * @retval kErrorNotFound   Iterator is done (not pointing to any option).
1164          *
1165          */
1166         Error ReadOptionValue(void *aValue) const;
1167 
1168         /**
1169          * Read the current Option Value which is assumed to be an unsigned integer.
1170          *
1171          * @param[out]  aUintValue      A reference to `uint64_t` to output the read Option Value.
1172          *
1173          * @retval kErrorNone       Successfully read the Option value.
1174          * @retval kErrorNoBufs     Value is too long to fit in an `uint64_t`.
1175          * @retval kErrorNotFound   Iterator is done (not pointing to any option).
1176          *
1177          */
1178         Error ReadOptionValue(uint64_t &aUintValue) const;
1179 
1180         /**
1181          * Gets the offset of beginning of the CoAP message payload (after the CoAP header).
1182          *
1183          * MUST be used after the iterator is done (i.e. iterated through all options).
1184          *
1185          * @returns The offset of beginning of the CoAP message payload
1186          *
1187          */
GetPayloadMessageOffset(void) const1188         uint16_t GetPayloadMessageOffset(void) const { return mNextOptionOffset; }
1189 
1190     private:
1191         // `mOption.mLength` value to indicate iterator is done.
1192         static constexpr uint16_t kIteratorDoneLength = 0xffff;
1193 
1194         // Special `mNextOptionOffset` value to indicate a parse error.
1195         static constexpr uint16_t kNextOptionOffsetParseError = 0;
1196 
MarkAsDone(void)1197         void MarkAsDone(void) { mOption.mLength = kIteratorDoneLength; }
MarkAsParseErrored(void)1198         void MarkAsParseErrored(void) { MarkAsDone(), mNextOptionOffset = kNextOptionOffsetParseError; }
1199 
1200         Error Read(uint16_t aLength, void *aBuffer);
1201         Error ReadExtendedOptionField(uint16_t &aValue);
1202         Error InitOrAdvance(const Message *aMessage, uint16_t aNumber);
1203     };
1204 
1205     /**
1206      * Gets the CoAP Option Number.
1207      *
1208      * @returns The CoAP Option Number.
1209      *
1210      */
GetNumber(void) const1211     uint16_t GetNumber(void) const { return mNumber; }
1212 
1213     /**
1214      * Gets the CoAP Option Length (length of Option Value in bytes).
1215      *
1216      * @returns The CoAP Option Length (in bytes).
1217      *
1218      */
GetLength(void) const1219     uint16_t GetLength(void) const { return mLength; }
1220 };
1221 
1222 /**
1223  * @}
1224  *
1225  */
1226 
1227 } // namespace Coap
1228 
1229 DefineCoreType(otCoapOption, Coap::Option);
1230 DefineCoreType(otCoapOptionIterator, Coap::Option::Iterator);
1231 DefineMapEnum(otCoapType, Coap::Type);
1232 DefineMapEnum(otCoapCode, Coap::Code);
1233 
1234 /**
1235  * Casts an `otMessage` pointer to a `Coap::Message` reference.
1236  *
1237  * @param[in] aMessage   A pointer to an `otMessage`.
1238  *
1239  * @returns A reference to `Coap::Message` matching @p aMessage.
1240  *
1241  */
AsCoapMessage(otMessage * aMessage)1242 inline Coap::Message &AsCoapMessage(otMessage *aMessage) { return *static_cast<Coap::Message *>(aMessage); }
1243 
1244 /**
1245  * Casts an `otMessage` pointer to a `Coap::Message` reference.
1246  *
1247  * @param[in] aMessage   A pointer to an `otMessage`.
1248  *
1249  * @returns A reference to `Coap::Message` matching @p aMessage.
1250  *
1251  */
AsCoapMessagePtr(otMessage * aMessage)1252 inline Coap::Message *AsCoapMessagePtr(otMessage *aMessage) { return static_cast<Coap::Message *>(aMessage); }
1253 
1254 /**
1255  * Casts an `otMessage` pointer to a `Coap::Message` pointer.
1256  *
1257  * @param[in] aMessage   A pointer to an `otMessage`.
1258  *
1259  * @returns A pointer to `Coap::Message` matching @p aMessage.
1260  *
1261  */
AsCoapMessage(const otMessage * aMessage)1262 inline const Coap::Message &AsCoapMessage(const otMessage *aMessage)
1263 {
1264     return *static_cast<const Coap::Message *>(aMessage);
1265 }
1266 
1267 /**
1268  * Casts an `otMessage` pointer to a `Coap::Message` reference.
1269  *
1270  * @param[in] aMessage   A pointer to an `otMessage`.
1271  *
1272  * @returns A pointer to `Coap::Message` matching @p aMessage.
1273  *
1274  */
AsCoapMessagePtr(const otMessage * aMessage)1275 inline const Coap::Message *AsCoapMessagePtr(const otMessage *aMessage)
1276 {
1277     return static_cast<const Coap::Message *>(aMessage);
1278 }
1279 
1280 } // namespace ot
1281 
1282 #endif // COAP_HEADER_HPP_
1283