coap_server_misc.c
Go to the documentation of this file.
1 /**
2  * @file coap_server_misc.c
3  * @brief Helper functions for CoAP server
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2010-2026 Oryx Embedded SARL. All rights reserved.
10  *
11  * This file is part of CycloneTCP Open.
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version 2
16  * of the License, or (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26  *
27  * @author Oryx Embedded SARL (www.oryx-embedded.com)
28  * @version 2.6.0
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL COAP_TRACE_LEVEL
33 
34 //Dependencies
35 #include <stdlib.h>
36 #include "coap/coap_server.h"
38 #include "coap/coap_server_misc.h"
39 #include "coap/coap_common.h"
40 #include "coap/coap_debug.h"
41 #include "debug.h"
42 
43 //Check TCP/IP stack configuration
44 #if (COAP_SERVER_SUPPORT == ENABLED)
45 
46 
47 /**
48  * @brief Handle periodic operations
49  * @param[in] context Pointer to the CoAP server context
50  **/
51 
53 {
54 #if (COAP_SERVER_DTLS_SUPPORT == ENABLED)
55  error_t error;
56  uint_t i;
58  CoapDtlsSession *session;
59 
60  //Get current time
62 
63  //Loop through DTLS sessions
64  for(i = 0; i < COAP_SERVER_MAX_SESSIONS; i++)
65  {
66  //Point to the current DTLS session
67  session = &context->session[i];
68 
69  //Valid DTLS session?
70  if(session->dtlsContext != NULL)
71  {
72  //Implementations should limit the lifetime of established sessions
73  if(timeCompare(time, session->timestamp + COAP_SERVER_SESSION_TIMEOUT) >= 0)
74  {
75  //Debug message
76  TRACE_INFO("CoAP Server: DTLS session timeout!\r\n");
77 
78  //Send a close notify alert to the client
79  tlsShutdown(session->dtlsContext);
80  //Release DTLS session
81  coapServerDeleteSession(session);
82  }
83  else
84  {
85  //Continue DTLS handshake
86  error = tlsConnect(session->dtlsContext);
87 
88  //Any error to report?
89  if(error != NO_ERROR &&
90  error != ERROR_TIMEOUT &&
91  error != ERROR_WOULD_BLOCK)
92  {
93  //Debug message
94  TRACE_INFO("CoAP Server: DTLS handshake failed!\r\n");
95 
96  //Release DTLS session
97  coapServerDeleteSession(session);
98  }
99  }
100  }
101  }
102 #endif
103 }
104 
105 
106 /**
107  * @brief Process CoAP request
108  * @param[in] context Pointer to the CoAP server context
109  * @param[in] data Pointer to the incoming CoAP message
110  * @param[in] length Length of the CoAP message, in bytes
111  * @return Error code
112  **/
113 
115  const uint8_t *data, size_t length)
116 {
117  error_t error;
118  CoapCode code;
120 
121  //Check the length of the CoAP message
123  return ERROR_INVALID_LENGTH;
124 
125  //Copy the request message
126  osMemcpy(context->request.buffer, data, length);
127 
128  //Save the length of the request message
129  context->request.length = length;
130  context->request.pos = 0;
131 
132  //Parse the received message
133  error = coapParseMessage(&context->request);
134 
135  //Valid CoAP message?
136  if(error == NO_ERROR)
137  {
138  //Terminate the payload with a NULL character
139  context->request.buffer[context->request.length] = '\0';
140 
141  //Debug message
142  TRACE_INFO("CoAP Server: CoAP message received (%" PRIuSIZE " bytes)...\r\n",
143  context->request.length);
144 
145  //Dump the contents of the message for debugging purpose
146  coapDumpMessage(context->request.buffer, context->request.length);
147 
148  //Retrieve message type and method code
149  coapGetType(&context->request, &type);
150  coapGetCode(&context->request, &code);
151 
152  //Initialize CoAP response message
153  coapServerInitResponse(context);
154 
155  //Check the type of the request
156  if(type == COAP_TYPE_CON || type == COAP_TYPE_NON)
157  {
158  //Check message code
159  if(code == COAP_CODE_GET ||
160  code == COAP_CODE_POST ||
161  code == COAP_CODE_PUT ||
162  code == COAP_CODE_DELETE ||
163  code == COAP_CODE_FETCH ||
164  code == COAP_CODE_PATCH ||
166  {
167  //Reconstruct the path component from Uri-Path options
168  coapJoinRepeatableOption(&context->request, COAP_OPT_URI_PATH,
169  context->uri, COAP_SERVER_MAX_URI_LEN, '/');
170 
171  //If the resource name is the empty string, set it to a single "/"
172  //character (refer to RFC 7252, section 6.5)
173  if(context->uri[0] == '\0')
174  {
175  osStrcpy(context->uri, "/");
176  }
177 
178  //Any registered callback?
179  if(context->requestCallback != NULL)
180  {
181  //Invoke user callback function
182  error = context->requestCallback(context, code, context->uri);
183  }
184  else
185  {
186  //Generate a 4.04 piggybacked response
187  error = coapSetCode(&context->response, COAP_CODE_NOT_FOUND);
188  }
189  }
190  else if(code == COAP_CODE_EMPTY)
191  {
192  //Provoking a Reset message by sending an Empty Confirmable message
193  //can be used to check of the liveness of an endpoint (refer to
194  //RFC 7252, section 4.3)
195  error = coapServerRejectRequest(context);
196  }
197  else
198  {
199  //A request with an unrecognized or unsupported method code must
200  //generate a 4.05 piggybacked response (refer to RFC 7252, section
201  //5.8)
202  error = coapSetCode(&context->response, COAP_CODE_METHOD_NOT_ALLOWED);
203  }
204  }
205  else
206  {
207  //Recipients of Acknowledgement and Reset messages must not respond
208  //with either Acknowledgement or Reset messages
209  error = ERROR_INVALID_REQUEST;
210  }
211  }
212  else if(error == ERROR_INVALID_HEADER || error == ERROR_INVALID_VERSION)
213  {
214  //Messages with a size smaller than four bytes or with unknown version
215  //numbers must be silently ignored (refer to RFC 7252, section 3)
216  }
217  else
218  {
219  //Other message format errors, such as an incomplete datagram or the
220  //usage of reserved values, are rejected with a Reset message
221  error = coapServerRejectRequest(context);
222  }
223 
224  //Check status code
225  if(!error)
226  {
227  //Any response?
228  if(context->response.length > 0)
229  {
230  //Debug message
231  TRACE_INFO("CoAP Server: Sending CoAP message (%" PRIuSIZE " bytes)...\r\n",
232  context->response.length);
233 
234  //Dump the contents of the message for debugging purpose
235  coapDumpMessage(context->response.buffer, context->response.length);
236 
237  //Send CoAP response message
238  error = coapServerSendResponse(context, context->response.buffer,
239  context->response.length);
240  }
241  }
242 
243  //Return status code
244  return error;
245 }
246 
247 
248 /**
249  * @brief Reject a CoAP request
250  * @param[in] context Pointer to the CoAP server context
251  * @return Error code
252  **/
253 
255 {
256  error_t error;
257  const CoapMessageHeader *header;
258 
259  //Initialize status code
260  error = NO_ERROR;
261 
262  //Debug message
263  TRACE_INFO("CoAP Server: Rejecting CoAP message...\r\n");
264 
265  //Point to the CoAP message header
266  header = (CoapMessageHeader *) &context->request.buffer;
267 
268  //Check the type of the request
269  if(header->type == COAP_TYPE_CON)
270  {
271  //Rejecting a Confirmable message is effected by sending a matching
272  //Reset message
273  error = coapServerFormatReset(context, ntohs(header->mid));
274  }
275  else if(header->type == COAP_TYPE_NON)
276  {
277  //Rejecting a Non-confirmable message may involve sending a matching
278  //Reset message, and apart from the Reset message the rejected message
279  //must be silently ignored (refer to RFC 7252, section 4.3)
280  error = coapServerFormatReset(context, ntohs(header->mid));
281  }
282  else
283  {
284  //Rejecting an Acknowledgment or Reset message is effected by
285  //silently ignoring it (refer to RFC 7252, section 4.2)
286  context->response.length = 0;
287  }
288 
289  //Return status code
290  return error;
291 }
292 
293 
294 /**
295  * @brief Initialize CoAP response message
296  * @param[in] context Pointer to the CoAP server context
297  * @return Error code
298  **/
299 
301 {
302  CoapMessageHeader *requestHeader;
303  CoapMessageHeader *responseHeader;
304 
305  //Point to the CoAP request header
306  requestHeader = (CoapMessageHeader *) context->request.buffer;
307  //Point to the CoAP response header
308  responseHeader = (CoapMessageHeader *) context->response.buffer;
309 
310  //Format message header
311  responseHeader->version = COAP_VERSION_1;
312  responseHeader->tokenLen = requestHeader->tokenLen;
313  responseHeader->code = COAP_CODE_INTERNAL_SERVER;
314  responseHeader->mid = requestHeader->mid;
315 
316  //If immediately available, the response to a request carried in a
317  //Confirmable message is carried in an Acknowledgement (ACK) message
318  if(requestHeader->type == COAP_TYPE_CON)
319  {
320  responseHeader->type = COAP_TYPE_ACK;
321  }
322  else
323  {
324  responseHeader->type = COAP_TYPE_NON;
325  }
326 
327  //The token is used to match a response with a request
328  osMemcpy(responseHeader->token, requestHeader->token,
329  requestHeader->tokenLen);
330 
331  //Set the length of the CoAP message
332  context->response.length = sizeof(CoapMessageHeader) + responseHeader->tokenLen;
333  context->response.pos = 0;
334 
335  //Successful processing
336  return NO_ERROR;
337 }
338 
339 
340 /**
341  * @brief Send CoAP response
342  * @param[in] context Pointer to the CoAP server context
343  * @param[in] data Pointer to a buffer containing the response message
344  * @param[in] length Length of the response message, in bytes
345  * @return Error code
346  **/
347 
349  const void *data, size_t length)
350 {
351  error_t error;
352 
353 #if (COAP_SERVER_DTLS_SUPPORT == ENABLED)
354  //DTLS-secured communication?
355  if(context->dtlsInitCallback != NULL)
356  {
357  uint_t i;
358  CoapDtlsSession *session;
359 
360  //Loop through DTLS sessions
361  for(i = 0; i < COAP_SERVER_MAX_SESSIONS; i++)
362  {
363  //Point to the current DTLS session
364  session = &context->session[i];
365 
366  //Valid DTLS session?
367  if(session->dtlsContext != NULL)
368  {
369  //Matching DTLS session?
370  if(ipCompAddr(&session->serverIpAddr, &context->serverIpAddr) &&
371  ipCompAddr(&session->clientIpAddr, &context->clientIpAddr) &&
372  session->clientPort == context->clientPort)
373  {
374  break;
375  }
376  }
377  }
378 
379  //Any matching DTLS session?
381  {
382  //Send DTLS datagram
383  error = tlsWrite(session->dtlsContext, data, length, NULL, 0);
384  }
385  else
386  {
387  //Report an error
388  error = ERROR_FAILURE;
389  }
390  }
391  else
392 #endif
393  {
394  //Send UDP datagram
395  error = socketSendTo(context->socket, &context->clientIpAddr,
396  context->clientPort, data, length, NULL, 0);
397  }
398 
399  //Return status code
400  return error;
401 }
402 
403 
404 /**
405  * @brief Format Reset message
406  * @param[in] context Pointer to the CoAP server context
407  * @param[in] mid Message ID
408  * @return Error code
409  **/
410 
412 {
413  CoapMessageHeader *header;
414 
415  //Point to the CoAP response header
416  header = (CoapMessageHeader *) context->response.buffer;
417 
418  //Format Reset message
419  header->version = COAP_VERSION_1;
420  header->type = COAP_TYPE_RST;
421  header->tokenLen = 0;
422  header->code = COAP_CODE_EMPTY;
423 
424  //The Reset message message must echo the message ID of the confirmable
425  //message and must be empty (refer to RFC 7252, section 4.2)
426  header->mid = htons(mid);
427 
428  //Set the length of the CoAP message
429  context->response.length = sizeof(CoapMessageHeader);
430 
431  //Successful processing
432  return NO_ERROR;
433 }
434 
435 #endif
error_t coapServerFormatReset(CoapServerContext *context, uint16_t mid)
Format Reset message.
error_t coapSetCode(CoapMessage *message, CoapCode code)
Set method or response code.
Definition: coap_message.c:201
#define htons(value)
Definition: cpu_endian.h:413
#define COAP_MAX_MSG_SIZE
Definition: coap_message.h:40
uint8_t code
Definition: coap_common.h:179
@ ERROR_WOULD_BLOCK
Definition: error.h:96
@ COAP_CODE_METHOD_NOT_ALLOWED
Definition: coap_common.h:133
error_t coapServerRejectRequest(CoapServerContext *context)
Reject a CoAP request.
uint8_t data[]
Definition: ethernet.h:224
error_t coapServerProcessRequest(CoapServerContext *context, const uint8_t *data, size_t length)
Process CoAP request.
error_t coapServerSendResponse(CoapServerContext *context, const void *data, size_t length)
Send CoAP response.
@ ERROR_INVALID_HEADER
Definition: error.h:87
error_t coapJoinRepeatableOption(const CoapMessage *message, uint16_t optionNum, char_t *optionValue, size_t maxLen, char_t separator)
Decode a path or query component from multiple repeatable options.
Definition: coap_option.c:877
uint8_t type
Definition: coap_common.h:176
Helper functions for CoAP server.
@ COAP_CODE_POST
Definition: coap_common.h:116
#define COAP_SERVER_SESSION_TIMEOUT
Definition: coap_server.h:77
@ ERROR_INVALID_VERSION
Definition: error.h:118
#define timeCompare(t1, t2)
Definition: os_port.h:40
#define COAP_SERVER_MAX_SESSIONS
Definition: coap_server.h:63
@ COAP_VERSION_1
CoAP version 1.
Definition: coap_common.h:69
error_t tlsShutdown(TlsContext *context)
Gracefully close TLS session.
Definition: tls.c:2603
void coapServerTick(CoapServerContext *context)
Handle periodic operations.
#define osMemcpy(dest, src, length)
Definition: os_port.h:144
error_t coapGetType(const CoapMessage *message, CoapMessageType *type)
Get message type.
Definition: coap_message.c:176
uint16_t mid
Definition: coap_common.h:180
error_t
Error codes.
Definition: error.h:43
bool_t ipCompAddr(const IpAddr *ipAddr1, const IpAddr *ipAddr2)
Compare IP addresses.
Definition: ip.c:318
@ COAP_CODE_PUT
Definition: coap_common.h:117
@ ERROR_FAILURE
Generic error code.
Definition: error.h:45
void coapServerDeleteSession(CoapDtlsSession *session)
Delete DTLS session.
@ ERROR_INVALID_LENGTH
Definition: error.h:111
@ COAP_TYPE_ACK
Acknowledgment message.
Definition: coap_common.h:91
@ COAP_CODE_NOT_FOUND
Definition: coap_common.h:132
#define TRACE_INFO(...)
Definition: debug.h:105
uint8_t length
Definition: tcp.h:375
@ COAP_TYPE_CON
Confirmable message.
Definition: coap_common.h:89
@ COAP_OPT_URI_PATH
Definition: coap_option.h:99
#define CoapDtlsSession
Definition: coap_server.h:125
@ COAP_TYPE_RST
Reset message.
Definition: coap_common.h:92
uint32_t systime_t
System time.
CoAP server.
#define ntohs(value)
Definition: cpu_endian.h:421
@ COAP_CODE_FETCH
Definition: coap_common.h:119
@ ERROR_TIMEOUT
Definition: error.h:95
error_t coapGetCode(const CoapMessage *message, CoapCode *code)
Get method or response code.
Definition: coap_message.c:226
uint32_t time
@ COAP_CODE_GET
Definition: coap_common.h:115
CoapMessageType
CoAP message types.
Definition: coap_common.h:88
Data logging functions for debugging purpose (CoAP)
#define COAP_SERVER_MAX_URI_LEN
Definition: coap_server.h:98
@ COAP_CODE_INTERNAL_SERVER
Definition: coap_common.h:141
#define CoapServerContext
Definition: coap_server.h:121
Transport protocol abstraction layer.
@ COAP_CODE_DELETE
Definition: coap_common.h:118
error_t tlsWrite(TlsContext *context, const void *data, size_t length, size_t *written, uint_t flags)
Send application data to the remote host using TLS.
Definition: tls.c:2148
error_t socketSendTo(Socket *socket, const IpAddr *destIpAddr, uint16_t destPort, const void *data, size_t length, size_t *written, uint_t flags)
Send a datagram to a specific destination.
Definition: socket.c:1535
@ COAP_CODE_EMPTY
Definition: coap_common.h:114
error_t coapParseMessage(const CoapMessage *message)
Parse CoAP message.
Definition: coap_message.c:51
@ COAP_CODE_IPATCH
Definition: coap_common.h:121
@ COAP_CODE_PATCH
Definition: coap_common.h:120
#define PRIuSIZE
unsigned int uint_t
Definition: compiler_port.h:57
@ COAP_TYPE_NON
Non-confirmable message.
Definition: coap_common.h:90
#define osStrcpy(s1, s2)
Definition: os_port.h:210
CoapCode
CoAP method and response codes.
Definition: coap_common.h:113
error_t tlsConnect(TlsContext *context)
Initiate the TLS handshake.
Definition: tls.c:1819
@ ERROR_INVALID_REQUEST
Definition: error.h:65
Definitions common to CoAP client and server.
error_t coapServerInitResponse(CoapServerContext *context)
Initialize CoAP response message.
@ NO_ERROR
Success.
Definition: error.h:44
CoapMessageHeader
Definition: coap_common.h:182
Debugging facilities.
error_t coapDumpMessage(const void *message, size_t length)
Dump CoAP message for debugging purpose.
Definition: coap_debug.c:122
systime_t osGetSystemTime(void)
Retrieve system time.