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 a CoAP option reading Option value from another or potentially the same message.
406      *
407      * @param[in] aNumber   The CoAP Option number.
408      * @param[in] aLength   The CoAP Option length.
409      * @param[in] aMessage  The message to read the CoAP Option value from (it can be the same as the current message).
410      * @param[in] aOffset   The offset in @p aMessage to start reading the CoAP Option value from (@p aLength bytes are
411      *                      used as Option value).
412      *
413      * @retval kErrorNone         Successfully appended the option.
414      * @retval kErrorInvalidArgs  The option type is not equal or greater than the last option type.
415      * @retval kErrorNoBufs       The option length exceeds the buffer size.
416      * @retval kErrorParse        Not enough bytes in @p aMessage to read @p aLength bytes from @p aOffset.
417      *
418      */
419     Error AppendOptionFromMessage(uint16_t aNumber, uint16_t aLength, const Message &aMessage, uint16_t aOffset);
420 
421     /**
422      * Appends an unsigned integer CoAP option as specified in RFC-7252 section-3.2
423      *
424      * @param[in]  aNumber  The CoAP Option number.
425      * @param[in]  aValue   The CoAP Option unsigned integer value.
426      *
427      * @retval kErrorNone         Successfully appended the option.
428      * @retval kErrorInvalidArgs  The option type is not equal or greater than the last option type.
429      * @retval kErrorNoBufs       The option length exceeds the buffer size.
430      *
431      */
432     Error AppendUintOption(uint16_t aNumber, uint32_t aValue);
433 
434     /**
435      * Appends a string CoAP option.
436      *
437      * @param[in]  aNumber  The CoAP Option number.
438      * @param[in]  aValue   The CoAP Option string value.
439      *
440      * @retval kErrorNone         Successfully appended the option.
441      * @retval kErrorInvalidArgs  The option type is not equal or greater than the last option type.
442      * @retval kErrorNoBufs       The option length exceeds the buffer size.
443      *
444      */
445     Error AppendStringOption(uint16_t aNumber, const char *aValue);
446 
447     /**
448      * Appends an Observe option.
449      *
450      * @param[in]  aObserve  Observe field value.
451      *
452      * @retval kErrorNone         Successfully appended the option.
453      * @retval kErrorInvalidArgs  The option type is not equal or greater than the last option type.
454      * @retval kErrorNoBufs       The option length exceeds the buffer size.
455      */
AppendObserveOption(uint32_t aObserve)456     Error AppendObserveOption(uint32_t aObserve) { return AppendUintOption(kOptionObserve, aObserve & kObserveMask); }
457 
458     /**
459      * Appends a Uri-Path option.
460      *
461      * @param[in]  aUriPath           A pointer to a null-terminated string.
462      *
463      * @retval kErrorNone         Successfully appended the option.
464      * @retval kErrorInvalidArgs  The option type is not equal or greater than the last option type.
465      * @retval kErrorNoBufs       The option length exceeds the buffer size.
466      *
467      */
468     Error AppendUriPathOptions(const char *aUriPath);
469 
470     /**
471      * Reads the Uri-Path options and constructs the URI path in the buffer referenced by @p `aUriPath`.
472      *
473      * @param[in] aUriPath  A reference to the buffer for storing URI path.
474      *                      NOTE: The buffer size must be `kMaxReceivedUriPath + 1`.
475      *
476      * @retval  kErrorNone   Successfully read the Uri-Path options.
477      * @retval  kErrorParse  CoAP Option header not well-formed.
478      *
479      */
480     Error ReadUriPathOptions(char (&aUriPath)[kMaxReceivedUriPath + 1]) const;
481 
482     /**
483      * Appends a Block option
484      *
485      * @param[in]  aType              Type of block option, 1 or 2.
486      * @param[in]  aNum               Current block number.
487      * @param[in]  aMore              Boolean to indicate more blocks are to be sent.
488      * @param[in]  aSize              Maximum block size.
489      *
490      * @retval kErrorNone         Successfully appended the option.
491      * @retval kErrorInvalidArgs  The option type is not equal or greater than the last option type.
492      * @retval kErrorNoBufs       The option length exceeds the buffer size.
493      *
494      */
495     Error AppendBlockOption(BlockType aType, uint32_t aNum, bool aMore, otCoapBlockSzx aSize);
496 
497     /**
498      * Appends a Proxy-Uri option.
499      *
500      * @param[in]  aProxyUri          A pointer to a null-terminated string.
501      *
502      * @retval kErrorNone         Successfully appended the option.
503      * @retval kErrorInvalidArgs  The option type is not equal or greater than the last option type.
504      * @retval kErrorNoBufs       The option length exceeds the buffer size.
505      *
506      */
AppendProxyUriOption(const char * aProxyUri)507     Error AppendProxyUriOption(const char *aProxyUri) { return AppendStringOption(kOptionProxyUri, aProxyUri); }
508 
509     /**
510      * Appends a Content-Format option.
511      *
512      * @param[in]  aContentFormat  The Content Format value.
513      *
514      * @retval kErrorNone         Successfully appended the option.
515      * @retval kErrorInvalidArgs  The option type is not equal or greater than the last option type.
516      * @retval kErrorNoBufs       The option length exceeds the buffer size.
517      *
518      */
AppendContentFormatOption(otCoapOptionContentFormat aContentFormat)519     Error AppendContentFormatOption(otCoapOptionContentFormat aContentFormat)
520     {
521         return AppendUintOption(kOptionContentFormat, static_cast<uint32_t>(aContentFormat));
522     }
523 
524     /**
525      * Appends a Max-Age option.
526      *
527      * @param[in]  aMaxAge  The Max-Age value.
528      *
529      * @retval kErrorNone         Successfully appended the option.
530      * @retval kErrorInvalidArgs  The option type is not equal or greater than the last option type.
531      * @retval kErrorNoBufs       The option length exceeds the buffer size.
532      */
AppendMaxAgeOption(uint32_t aMaxAge)533     Error AppendMaxAgeOption(uint32_t aMaxAge) { return AppendUintOption(kOptionMaxAge, aMaxAge); }
534 
535     /**
536      * Appends a single Uri-Query option.
537      *
538      * @param[in]  aUriQuery  A pointer to null-terminated string, which should contain a single key=value pair.
539      *
540      * @retval kErrorNone         Successfully appended the option.
541      * @retval kErrorInvalidArgs  The option type is not equal or greater than the last option type.
542      * @retval kErrorNoBufs       The option length exceeds the buffer size.
543      */
AppendUriQueryOption(const char * aUriQuery)544     Error AppendUriQueryOption(const char *aUriQuery) { return AppendStringOption(kOptionUriQuery, aUriQuery); }
545 
546 #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE
547     /**
548      * Reads the information contained in a Block1 or Block2 option and set it in
549      * the HelpData of the message.
550      *
551      * @param[in]   aBlockType  Block1 or Block2 option value.
552      *
553      * @retval  kErrorNone          The option has been found and is valid.
554      * @retval  kErrorNotFound      The option has not been found.
555      * @retval  kErrorInvalidArgs   The option is invalid.
556      */
557     Error ReadBlockOptionValues(uint16_t aBlockType);
558 
559     /**
560      * Returns the current header length of a message.
561      *
562      * @returns The length of the message header.
563      *
564      */
GetHeaderLength(void) const565     uint16_t GetHeaderLength(void) const { return GetHelpData().mHeaderLength; }
566 
567     /**
568      * Returns the block number of a CoAP block-wise transfer message.
569      *
570      * @returns The block number.
571      *
572      */
GetBlockWiseBlockNumber(void) const573     uint32_t GetBlockWiseBlockNumber(void) const { return GetHelpData().mBlockWiseData.mBlockNumber; }
574 
575     /**
576      * Checks if the More Blocks flag is set.
577      *
578      * @retval TRUE   More Blocks flag is set.
579      * @retval FALSE  More Blocks flag is not set.
580      *
581      */
IsMoreBlocksFlagSet(void) const582     bool IsMoreBlocksFlagSet(void) const { return GetHelpData().mBlockWiseData.mMoreBlocks; }
583 
584     /**
585      * Returns the block size of a CoAP block-wise transfer message.
586      *
587      * @returns The block size.
588      *
589      */
GetBlockWiseBlockSize(void) const590     otCoapBlockSzx GetBlockWiseBlockSize(void) const { return GetHelpData().mBlockWiseData.mBlockSize; }
591 #endif // OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE
592 
593     /**
594      * Reads and reassembles the URI path string and fills it into @p aUriPath.
595      *
596      * @retval  kErrorNone      URI path string has been reassembled.
597      * @retval  kErrorNoBufs    URI path string is too long.
598      *
599      */
600     Error GetUriPath(char *aUriPath) const;
601 
602     /**
603      * Adds Payload Marker indicating beginning of the payload to the CoAP header.
604      *
605      * It also set offset to the start of payload.
606      *
607      * @retval kErrorNone    Payload Marker successfully added.
608      * @retval kErrorNoBufs  Message Payload Marker exceeds the buffer size.
609      *
610      */
611     Error SetPayloadMarker(void);
612 
613     /**
614      * Returns the offset of the first CoAP option.
615      *
616      * @returns The offset of the first CoAP option.
617      *
618      */
GetOptionStart(void) const619     uint16_t GetOptionStart(void) const { return kMinHeaderLength + GetTokenLength(); }
620 
621     /**
622      * Parses CoAP header and moves offset end of CoAP header.
623      *
624      * @retval  kErrorNone   Successfully parsed CoAP header from the message.
625      * @retval  kErrorParse  Failed to parse the CoAP header.
626      *
627      */
628     Error ParseHeader(void);
629 
630     /**
631      * Sets a default response header based on request header.
632      *
633      * @param[in]  aRequest  The request message.
634      *
635      * @retval kErrorNone    Successfully set the default response header.
636      * @retval kErrorNoBufs  Insufficient message buffers available to set the default response header.
637      *
638      */
639     Error SetDefaultResponseHeader(const Message &aRequest);
640 
641 #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE
642 
643     /**
644      * Sets the block number value in the message HelpData.
645      *
646      * @param[in]   aBlockNumber    Block number value to set.
647      *
648      */
SetBlockWiseBlockNumber(uint32_t aBlockNumber)649     void SetBlockWiseBlockNumber(uint32_t aBlockNumber) { GetHelpData().mBlockWiseData.mBlockNumber = aBlockNumber; }
650 
651     /**
652      * Sets the More Blocks flag in the message HelpData.
653      *
654      * @param[in]   aMoreBlocks    TRUE or FALSE.
655      *
656      */
SetMoreBlocksFlag(bool aMoreBlocks)657     void SetMoreBlocksFlag(bool aMoreBlocks) { GetHelpData().mBlockWiseData.mMoreBlocks = aMoreBlocks; }
658 
659     /**
660      * Sets the block size value in the message HelpData.
661      *
662      * @param[in]   aBlockSize    Block size value to set.
663      *
664      */
SetBlockWiseBlockSize(otCoapBlockSzx aBlockSize)665     void SetBlockWiseBlockSize(otCoapBlockSzx aBlockSize) { GetHelpData().mBlockWiseData.mBlockSize = aBlockSize; }
666 #endif // OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE
667 
668     /**
669      * Checks if a header is an empty message header.
670      *
671      * @retval TRUE   Message is an empty message header.
672      * @retval FALSE  Message is not an empty message header.
673      *
674      */
IsEmpty(void) const675     bool IsEmpty(void) const { return (GetCode() == kCodeEmpty); }
676 
677     /**
678      * Checks if a header is a request header.
679      *
680      * @retval TRUE   Message is a request header.
681      * @retval FALSE  Message is not a request header.
682      *
683      */
IsRequest(void) const684     bool IsRequest(void) const { return (GetCode() >= kCodeGet) && (GetCode() <= kCodeDelete); }
685 
686     /**
687      * Indicates whether or not the CoAP code in header is "Get" request.
688      *
689      * @retval TRUE   Message is a Get request.
690      * @retval FALSE  Message is not a Get request.
691      *
692      */
IsGetRequest(void) const693     bool IsGetRequest(void) const { return GetCode() == kCodeGet; }
694 
695     /**
696      * Indicates whether or not the CoAP code in header is "Post" request.
697      *
698      * @retval TRUE   Message is a Post request.
699      * @retval FALSE  Message is not a Post request.
700      *
701      */
IsPostRequest(void) const702     bool IsPostRequest(void) const { return GetCode() == kCodePost; }
703 
704     /**
705      * Indicates whether or not the CoAP code in header is "Put" request.
706      *
707      * @retval TRUE   Message is a Put request.
708      * @retval FALSE  Message is not a Put request.
709      *
710      */
IsPutRequest(void) const711     bool IsPutRequest(void) const { return GetCode() == kCodePut; }
712 
713     /**
714      * Indicates whether or not the CoAP code in header is "Delete" request.
715      *
716      * @retval TRUE   Message is a Delete request.
717      * @retval FALSE  Message is not a Delete request.
718      *
719      */
IsDeleteRequest(void) const720     bool IsDeleteRequest(void) const { return GetCode() == kCodeDelete; }
721 
722     /**
723      * Checks if a header is a response header.
724      *
725      * @retval TRUE   Message is a response header.
726      * @retval FALSE  Message is not a response header.
727      *
728      */
IsResponse(void) const729     bool IsResponse(void) const { return GetCode() >= OT_COAP_CODE_RESPONSE_MIN; }
730 
731     /**
732      * Checks if a header is a CON message header.
733      *
734      * @retval TRUE   Message is a CON message header.
735      * @retval FALSE  Message is not is a CON message header.
736      *
737      */
IsConfirmable(void) const738     bool IsConfirmable(void) const { return (GetType() == kTypeConfirmable); }
739 
740     /**
741      * Checks if a header is a NON message header.
742      *
743      * @retval TRUE   Message is a NON message header.
744      * @retval FALSE  Message is not is a NON message header.
745      *
746      */
IsNonConfirmable(void) const747     bool IsNonConfirmable(void) const { return (GetType() == kTypeNonConfirmable); }
748 
749     /**
750      * Checks if a header is a ACK message header.
751      *
752      * @retval TRUE   Message is a ACK message header.
753      * @retval FALSE  Message is not is a ACK message header.
754      *
755      */
IsAck(void) const756     bool IsAck(void) const { return (GetType() == kTypeAck); }
757 
758     /**
759      * Checks if a header is a RST message header.
760      *
761      * @retval TRUE   Message is a RST message header.
762      * @retval FALSE  Message is not is a RST message header.
763      *
764      */
IsReset(void) const765     bool IsReset(void) const { return (GetType() == kTypeReset); }
766 
767     /**
768      * Indicates whether or not the header is a confirmable Put request (i.e, `kTypeConfirmable` with
769      *  `kCodePost`).
770      *
771      * @retval TRUE   Message is a confirmable Post request.
772      * @retval FALSE  Message is not a confirmable Post request.
773      *
774      */
775     bool IsConfirmablePostRequest(void) const;
776 
777     /**
778      * Indicates whether or not the header is a non-confirmable Put request (i.e, `kTypeNonConfirmable` with
779      *  `kCodePost`).
780      *
781      * @retval TRUE   Message is a non-confirmable Post request.
782      * @retval FALSE  Message is not a non-confirmable Post request.
783      *
784      */
785     bool IsNonConfirmablePostRequest(void) const;
786 
787     /**
788      * Creates a copy of this CoAP message.
789      *
790      * It allocates the new message from the same message pool as the original one and copies @p aLength octets
791      * of the payload. The `Type`, `SubType`, `LinkSecurity`, `Offset`, `InterfaceId`, and `Priority` fields on the
792      * cloned message are also copied from the original one.
793      *
794      * @param[in] aLength  Number of payload bytes to copy.
795      *
796      * @returns A pointer to the message or `nullptr` if insufficient message buffers are available.
797      *
798      */
799     Message *Clone(uint16_t aLength) const;
800 
801     /**
802      * Creates a copy of the message.
803      *
804      * It allocates the new message from the same message pool as the original one and copies the entire payload. The
805      * `Type`, `SubType`, `LinkSecurity`, `Offset`, `InterfaceId`, and `Priority` fields on the cloned message are also
806      * copied from the original one.
807      *
808      * @returns A pointer to the message or `nullptr` if insufficient message buffers are available.
809      *
810      */
Clone(void) const811     Message *Clone(void) const { return Clone(GetLength()); }
812 
813     /**
814      * Returns the minimal reserved bytes required for CoAP message.
815      *
816      */
GetHelpDataReserved(void)817     static uint16_t GetHelpDataReserved(void) { return sizeof(HelpData) + kHelpDataAlignment; }
818 
819     /**
820      * Returns a pointer to the next message after this as a `Coap::Message`.
821      *
822      * Should be used when the message is in a `Coap::MessageQueue` (i.e., a queue containing only CoAP
823      * messages).
824      *
825      * @returns A pointer to the next message in the queue or `nullptr` if at the end of the queue.
826      *
827      */
GetNextCoapMessage(void)828     Message *GetNextCoapMessage(void) { return static_cast<Message *>(GetNext()); }
829 
830     /**
831      * Returns a pointer to the next message after this as a `Coap::Message`.
832      *
833      * Should be used when the message is in a `Coap::MessageQueue` (i.e., a queue containing only CoAP
834      * messages).
835      *
836      * @returns A pointer to the next message in the queue or `nullptr` if at the end of the queue.
837      *
838      */
GetNextCoapMessage(void) const839     const Message *GetNextCoapMessage(void) const { return static_cast<const Message *>(GetNext()); }
840 
841 private:
842     /*
843      * Header field first byte (RFC 7252).
844      *
845      *    7 6 5 4 3 2 1 0
846      *   +-+-+-+-+-+-+-+-+
847      *   |Ver| T |  TKL  |  (Version, Type and Token Length).
848      *   +-+-+-+-+-+-+-+-+
849      */
850     static constexpr uint8_t kVersionOffset     = 6;
851     static constexpr uint8_t kVersionMask       = 0x3 << kVersionOffset;
852     static constexpr uint8_t kVersion1          = 1;
853     static constexpr uint8_t kTypeOffset        = 4;
854     static constexpr uint8_t kTypeMask          = 0x3 << kTypeOffset;
855     static constexpr uint8_t kTokenLengthOffset = 0;
856     static constexpr uint8_t kTokenLengthMask   = 0xf << kTokenLengthOffset;
857 
858     /*
859      *
860      * Option Format (RFC 7252).
861      *
862      *      7   6   5   4   3   2   1   0
863      *    +---------------+---------------+
864      *    |  Option Delta | Option Length |   1 byte
865      *    +---------------+---------------+
866      *    /         Option Delta          /   0-2 bytes
867      *    \          (extended)           \
868      *    +-------------------------------+
869      *    /         Option Length         /   0-2 bytes
870      *    \          (extended)           \
871      *    +-------------------------------+
872      *    /         Option Value          /   0 or more bytes
873      *    +-------------------------------+
874      *
875      */
876 
877     static constexpr uint8_t kOptionDeltaOffset  = 4;
878     static constexpr uint8_t kOptionDeltaMask    = 0xf << kOptionDeltaOffset;
879     static constexpr uint8_t kOptionLengthOffset = 0;
880     static constexpr uint8_t kOptionLengthMask   = 0xf << kOptionLengthOffset;
881 
882     static constexpr uint8_t kMaxOptionHeaderSize = 5;
883 
884     static constexpr uint8_t kOption1ByteExtension = 13; // Indicates a one-byte extension.
885     static constexpr uint8_t kOption2ByteExtension = 14; // Indicates a two-byte extension.
886 
887     static constexpr uint8_t kPayloadMarker = 0xff;
888 
889     static constexpr uint8_t kHelpDataAlignment = sizeof(uint16_t); // Alignment of help data.
890 
891     static constexpr uint16_t kMinHeaderLength = 4;
892     static constexpr uint16_t kMaxHeaderLength = 512;
893 
894     static constexpr uint16_t kOption1ByteExtensionOffset = 13;  // Delta/Length offset as specified (RFC 7252).
895     static constexpr uint16_t kOption2ByteExtensionOffset = 269; // Delta/Length offset as specified (RFC 7252).
896 
897     static constexpr uint8_t kBlockSzxOffset = 0;
898     static constexpr uint8_t kBlockMOffset   = 3;
899     static constexpr uint8_t kBlockNumOffset = 4;
900 
901     static constexpr uint32_t kObserveMask = 0xffffff;
902     static constexpr uint32_t kBlockNumMax = 0xffff;
903 
904 #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE
905     struct BlockWiseData
906     {
907         uint32_t       mBlockNumber;
908         bool           mMoreBlocks;
909         otCoapBlockSzx mBlockSize;
910     };
911 #endif
912 
913     /**
914      * Represents a CoAP header excluding CoAP options.
915      *
916      */
917     OT_TOOL_PACKED_BEGIN
918     struct Header
919     {
920         uint8_t  mVersionTypeToken;       ///< The CoAP Version, Type, and Token Length
921         uint8_t  mCode;                   ///< The CoAP Code
922         uint16_t mMessageId;              ///< The CoAP Message ID
923         uint8_t  mToken[kMaxTokenLength]; ///< The CoAP Token
924     } OT_TOOL_PACKED_END;
925 
926     /**
927      * Represents a HelpData used by this CoAP message.
928      *
929      */
930     struct HelpData : public Clearable<HelpData>
931     {
932         Header   mHeader;
933         uint16_t mOptionLast;
934         uint16_t mHeaderOffset; ///< The byte offset for the CoAP Header
935         uint16_t mHeaderLength;
936         bool     mPayloadMarkerSet;
937 #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE
938         BlockWiseData mBlockWiseData;
939 #endif
940     };
941 
942     class ConstIterator : public ot::Message::ConstIterator
943     {
944     public:
945         using ot::Message::ConstIterator::ConstIterator;
946 
operator *(void)947         const Message &operator*(void) { return static_cast<const Message &>(ot::Message::ConstIterator::operator*()); }
operator ->(void)948         const Message *operator->(void)
949         {
950             return static_cast<const Message *>(ot::Message::ConstIterator::operator->());
951         }
952     };
953 
954     class Iterator : public ot::Message::Iterator
955     {
956     public:
957         using ot::Message::Iterator::Iterator;
958 
operator *(void)959         Message &operator*(void) { return static_cast<Message &>(ot::Message::Iterator::operator*()); }
operator ->(void)960         Message *operator->(void) { return static_cast<Message *>(ot::Message::Iterator::operator->()); }
961     };
962 
963     static_assert(sizeof(HelpData) <= sizeof(Ip6::Header) + sizeof(Ip6::HopByHopHeader) + sizeof(Ip6::MplOption) +
964                                           sizeof(Ip6::Udp::Header),
965                   "HelpData size exceeds the size of the reserved region in the message");
966 
GetHelpData(void) const967     const HelpData &GetHelpData(void) const
968     {
969         static_assert(sizeof(HelpData) + kHelpDataAlignment <= kHeadBufferDataSize,
970                       "Insufficient buffer size for CoAP processing! Increase OPENTHREAD_CONFIG_MESSAGE_BUFFER_SIZE.");
971 
972         return *static_cast<const HelpData *>(OT_ALIGN(GetFirstData(), kHelpDataAlignment));
973     }
974 
GetHelpData(void)975     HelpData &GetHelpData(void) { return AsNonConst(AsConst(this)->GetHelpData()); }
976 
GetToken(void)977     uint8_t *GetToken(void) { return GetHelpData().mHeader.mToken; }
978 
SetTokenLength(uint8_t aTokenLength)979     void SetTokenLength(uint8_t aTokenLength)
980     {
981         GetHelpData().mHeader.mVersionTypeToken &= ~kTokenLengthMask;
982         GetHelpData().mHeader.mVersionTypeToken |= ((aTokenLength << kTokenLengthOffset) & kTokenLengthMask);
983     }
984 
985     uint8_t WriteExtendedOptionField(uint16_t aValue, uint8_t *&aBuffer);
986 
987     Error AppendOptionHeader(uint16_t aNumber, uint16_t aLength);
988 };
989 
990 /**
991  * Implements a CoAP message queue.
992  *
993  */
994 class MessageQueue : public ot::MessageQueue
995 {
996 public:
997     /**
998      * Initializes the message queue.
999      *
1000      */
1001     MessageQueue(void) = default;
1002 
1003     /**
1004      * Returns a pointer to the first message.
1005      *
1006      * @returns A pointer to the first message.
1007      *
1008      */
GetHead(void)1009     Message *GetHead(void) { return static_cast<Message *>(ot::MessageQueue::GetHead()); }
1010 
1011     /**
1012      * Returns a pointer to the first message.
1013      *
1014      * @returns A pointer to the first message.
1015      *
1016      */
GetHead(void) const1017     const Message *GetHead(void) const { return static_cast<const Message *>(ot::MessageQueue::GetHead()); }
1018 
1019     /**
1020      * Adds a message to the end of the queue.
1021      *
1022      * @param[in]  aMessage  The message to add.
1023      *
1024      */
Enqueue(Message & aMessage)1025     void Enqueue(Message &aMessage) { Enqueue(aMessage, kQueuePositionTail); }
1026 
1027     /**
1028      * Adds a message at a given position (head/tail) of the queue.
1029      *
1030      * @param[in]  aMessage  The message to add.
1031      * @param[in]  aPosition The position (head or tail) where to add the message.
1032      *
1033      */
Enqueue(Message & aMessage,QueuePosition aPosition)1034     void Enqueue(Message &aMessage, QueuePosition aPosition) { ot::MessageQueue::Enqueue(aMessage, aPosition); }
1035 
1036     /**
1037      * Removes a message from the queue.
1038      *
1039      * @param[in]  aMessage  The message to remove.
1040      *
1041      */
Dequeue(Message & aMessage)1042     void Dequeue(Message &aMessage) { ot::MessageQueue::Dequeue(aMessage); }
1043 
1044     /**
1045      * Removes a message from the queue and frees it.
1046      *
1047      * @param[in]  aMessage  The message to remove and free.
1048      *
1049      */
DequeueAndFree(Message & aMessage)1050     void DequeueAndFree(Message &aMessage) { ot::MessageQueue::DequeueAndFree(aMessage); }
1051 
1052     // The following methods are intended to support range-based `for`
1053     // loop iteration over the queue entries and should not be used
1054     // directly. The range-based `for` works correctly even if the
1055     // current entry is removed from the queue during iteration.
1056 
1057     Message::Iterator begin(void);
end(void)1058     Message::Iterator end(void) { return Message::Iterator(); }
1059 
1060     Message::ConstIterator begin(void) const;
end(void) const1061     Message::ConstIterator end(void) const { return Message::ConstIterator(); }
1062 };
1063 
1064 /**
1065  * Represents a CoAP option.
1066  *
1067  */
1068 class Option : public otCoapOption
1069 {
1070 public:
1071     /**
1072      * Represents an iterator for CoAP options.
1073      *
1074      */
1075     class Iterator : public otCoapOptionIterator
1076     {
1077     public:
1078         /**
1079          * Initializes the iterator to iterate over CoAP Options in a CoAP message.
1080          *
1081          * The iterator MUST be initialized before any other methods are used, otherwise its behavior is undefined.
1082          *
1083          * After initialization, the iterator is either updated to point to the first option, or it is marked as done
1084          * (i.e., `IsDone()` returns `true`) when there is no option or if there is a parse error.
1085          *
1086          * @param[in] aMessage  The CoAP message.
1087          *
1088          * @retval kErrorNone   Successfully initialized. Iterator is either at the first option or done.
1089          * @retval kErrorParse  CoAP Option header in @p aMessage is not well-formed.
1090          *
1091          */
1092         Error Init(const Message &aMessage);
1093 
1094         /**
1095          * Initializes the iterator to iterate over CoAP Options in a CoAP message matching a given Option
1096          * Number value.
1097          *
1098          * The iterator MUST be initialized before any other methods are used, otherwise its behavior is undefined.
1099          *
1100          * After initialization, the iterator is either updated to point to the first option matching the given Option
1101          * Number value, or it is marked as done (i.e., `IsDone()` returns `true`) when there is no matching option or
1102          * if there is a parse error.
1103          *
1104          * @param[in] aMessage  The CoAP message.
1105          * @param[in] aNumber   The CoAP Option Number.
1106          *
1107          * @retval  kErrorNone   Successfully initialized. Iterator is either at the first matching option or done.
1108          * @retval  kErrorParse  CoAP Option header in @p aMessage is not well-formed.
1109          *
1110          */
Init(const Message & aMessage,uint16_t aNumber)1111         Error Init(const Message &aMessage, uint16_t aNumber) { return InitOrAdvance(&aMessage, aNumber); }
1112 
1113         /**
1114          * Indicates whether or not the iterator is done (i.e., has reached the end of CoAP Option Header).
1115          *
1116          * @retval TRUE   Iterator is done (reached end of Option header).
1117          * @retval FALSE  Iterator is not done and currently pointing to a CoAP Option.
1118          *
1119          */
IsDone(void) const1120         bool IsDone(void) const { return mOption.mLength == kIteratorDoneLength; }
1121 
1122         /**
1123          * Indicates whether or not there was a earlier parse error (i.e., whether the iterator is valid).
1124          *
1125          * After a parse errors, iterator would also be marked as done.
1126          *
1127          * @retval TRUE   There was an earlier parse error and the iterator is not valid.
1128          * @retval FALSE  There was no earlier parse error and the iterator is valid.
1129          *
1130          */
HasParseErrored(void) const1131         bool HasParseErrored(void) const { return mNextOptionOffset == kNextOptionOffsetParseError; }
1132 
1133         /**
1134          * Advances the iterator to the next CoAP Option in the header.
1135          *
1136          * The iterator is updated to point to the next option or marked as done when there are no more options.
1137          *
1138          * @retval  kErrorNone   Successfully advanced the iterator.
1139          * @retval  kErrorParse  CoAP Option header is not well-formed.
1140          *
1141          */
1142         Error Advance(void);
1143 
1144         /**
1145          * Advances the iterator to the next CoAP Option in the header matching a given Option Number value.
1146          *
1147          * The iterator is updated to point to the next matching option or marked as done when there are no more
1148          * matching options.
1149          *
1150          * @param[in] aNumber   The CoAP Option Number.
1151          *
1152          * @retval  kErrorNone   Successfully advanced the iterator.
1153          * @retval  kErrorParse  CoAP Option header is not well-formed.
1154          *
1155          */
Advance(uint16_t aNumber)1156         Error Advance(uint16_t aNumber) { return InitOrAdvance(nullptr, aNumber); }
1157 
1158         /**
1159          * Gets the CoAP message associated with the iterator.
1160          *
1161          * @returns A reference to the CoAP message.
1162          *
1163          */
GetMessage(void) const1164         const Message &GetMessage(void) const { return *static_cast<const Message *>(mMessage); }
1165 
1166         /**
1167          * Gets a pointer to the current CoAP Option to which the iterator is currently pointing.
1168          *
1169          * @returns A pointer to the current CoAP Option, or `nullptr` if iterator is done (or there was an earlier
1170          *          parse error).
1171          *
1172          */
GetOption(void) const1173         const Option *GetOption(void) const { return IsDone() ? nullptr : static_cast<const Option *>(&mOption); }
1174 
1175         /**
1176          * Reads the current Option Value into a given buffer.
1177          *
1178          * @param[out]  aValue   The pointer to a buffer to copy the Option Value. The buffer is assumed to be
1179          *                       sufficiently large (i.e. at least `GetOption()->GetLength()` bytes).
1180          *
1181          * @retval kErrorNone       Successfully read and copied the Option Value into given buffer.
1182          * @retval kErrorNotFound   Iterator is done (not pointing to any option).
1183          *
1184          */
1185         Error ReadOptionValue(void *aValue) const;
1186 
1187         /**
1188          * Read the current Option Value which is assumed to be an unsigned integer.
1189          *
1190          * @param[out]  aUintValue      A reference to `uint64_t` to output the read Option Value.
1191          *
1192          * @retval kErrorNone       Successfully read the Option value.
1193          * @retval kErrorNoBufs     Value is too long to fit in an `uint64_t`.
1194          * @retval kErrorNotFound   Iterator is done (not pointing to any option).
1195          *
1196          */
1197         Error ReadOptionValue(uint64_t &aUintValue) const;
1198 
1199         /**
1200          * Gets the offset of beginning of the CoAP message payload (after the CoAP header).
1201          *
1202          * MUST be used after the iterator is done (i.e. iterated through all options).
1203          *
1204          * @returns The offset of beginning of the CoAP message payload
1205          *
1206          */
GetPayloadMessageOffset(void) const1207         uint16_t GetPayloadMessageOffset(void) const { return mNextOptionOffset; }
1208 
1209         /**
1210          * Gets the offset of beginning of the CoAP Option Value.
1211          *
1212          * MUST be used during the iterator is in progress.
1213          *
1214          * @returns The offset of beginning of the CoAP Option Value
1215          *
1216          */
GetOptionValueMessageOffset(void) const1217         uint16_t GetOptionValueMessageOffset(void) const { return mNextOptionOffset - mOption.mLength; }
1218 
1219     private:
1220         // `mOption.mLength` value to indicate iterator is done.
1221         static constexpr uint16_t kIteratorDoneLength = 0xffff;
1222 
1223         // Special `mNextOptionOffset` value to indicate a parse error.
1224         static constexpr uint16_t kNextOptionOffsetParseError = 0;
1225 
MarkAsDone(void)1226         void MarkAsDone(void) { mOption.mLength = kIteratorDoneLength; }
MarkAsParseErrored(void)1227         void MarkAsParseErrored(void) { MarkAsDone(), mNextOptionOffset = kNextOptionOffsetParseError; }
1228 
1229         Error Read(uint16_t aLength, void *aBuffer);
1230         Error ReadExtendedOptionField(uint16_t &aValue);
1231         Error InitOrAdvance(const Message *aMessage, uint16_t aNumber);
1232     };
1233 
1234     /**
1235      * Gets the CoAP Option Number.
1236      *
1237      * @returns The CoAP Option Number.
1238      *
1239      */
GetNumber(void) const1240     uint16_t GetNumber(void) const { return mNumber; }
1241 
1242     /**
1243      * Gets the CoAP Option Length (length of Option Value in bytes).
1244      *
1245      * @returns The CoAP Option Length (in bytes).
1246      *
1247      */
GetLength(void) const1248     uint16_t GetLength(void) const { return mLength; }
1249 };
1250 
1251 /**
1252  * @}
1253  *
1254  */
1255 
1256 } // namespace Coap
1257 
1258 DefineCoreType(otCoapOption, Coap::Option);
1259 DefineCoreType(otCoapOptionIterator, Coap::Option::Iterator);
1260 DefineMapEnum(otCoapType, Coap::Type);
1261 DefineMapEnum(otCoapCode, Coap::Code);
1262 
1263 /**
1264  * Casts an `otMessage` pointer to a `Coap::Message` reference.
1265  *
1266  * @param[in] aMessage   A pointer to an `otMessage`.
1267  *
1268  * @returns A reference to `Coap::Message` matching @p aMessage.
1269  *
1270  */
AsCoapMessage(otMessage * aMessage)1271 inline Coap::Message &AsCoapMessage(otMessage *aMessage) { return *static_cast<Coap::Message *>(aMessage); }
1272 
1273 /**
1274  * Casts an `otMessage` pointer to a `Coap::Message` reference.
1275  *
1276  * @param[in] aMessage   A pointer to an `otMessage`.
1277  *
1278  * @returns A reference to `Coap::Message` matching @p aMessage.
1279  *
1280  */
AsCoapMessagePtr(otMessage * aMessage)1281 inline Coap::Message *AsCoapMessagePtr(otMessage *aMessage) { return static_cast<Coap::Message *>(aMessage); }
1282 
1283 /**
1284  * Casts an `otMessage` pointer to a `Coap::Message` pointer.
1285  *
1286  * @param[in] aMessage   A pointer to an `otMessage`.
1287  *
1288  * @returns A pointer to `Coap::Message` matching @p aMessage.
1289  *
1290  */
AsCoapMessage(const otMessage * aMessage)1291 inline const Coap::Message &AsCoapMessage(const otMessage *aMessage)
1292 {
1293     return *static_cast<const Coap::Message *>(aMessage);
1294 }
1295 
1296 /**
1297  * Casts an `otMessage` pointer to a `Coap::Message` reference.
1298  *
1299  * @param[in] aMessage   A pointer to an `otMessage`.
1300  *
1301  * @returns A pointer to `Coap::Message` matching @p aMessage.
1302  *
1303  */
AsCoapMessagePtr(const otMessage * aMessage)1304 inline const Coap::Message *AsCoapMessagePtr(const otMessage *aMessage)
1305 {
1306     return static_cast<const Coap::Message *>(aMessage);
1307 }
1308 
1309 } // namespace ot
1310 
1311 #endif // COAP_HEADER_HPP_
1312