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-2024 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.4.4
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->settings.requestCallback != NULL)
180  {
181  //Invoke user callback function
182  error = context->settings.requestCallback(context, code,
183  context->uri);
184  }
185  else
186  {
187  //Generate a 4.04 piggybacked response
188  error = coapSetCode(&context->response, COAP_CODE_NOT_FOUND);
189  }
190  }
191  else if(code == COAP_CODE_EMPTY)
192  {
193  //Provoking a Reset message by sending an Empty Confirmable message
194  //can be used to check of the liveness of an endpoint (refer to
195  //RFC 7252, section 4.3)
196  error = coapServerRejectRequest(context);
197  }
198  else
199  {
200  //A request with an unrecognized or unsupported method code must
201  //generate a 4.05 piggybacked response (refer to RFC 7252, section
202  //5.8)
203  error = coapSetCode(&context->response, COAP_CODE_METHOD_NOT_ALLOWED);
204  }
205  }
206  else
207  {
208  //Recipients of Acknowledgement and Reset messages must not respond
209  //with either Acknowledgement or Reset messages
210  error = ERROR_INVALID_REQUEST;
211  }
212  }
213  else if(error == ERROR_INVALID_HEADER || error == ERROR_INVALID_VERSION)
214  {
215  //Messages with a size smaller than four bytes or with unknown version
216  //numbers must be silently ignored (refer to RFC 7252, section 3)
217  }
218  else
219  {
220  //Other message format errors, such as an incomplete datagram or the
221  //usage of reserved values, are rejected with a Reset message
222  error = coapServerRejectRequest(context);
223  }
224 
225  //Check status code
226  if(!error)
227  {
228  //Any response?
229  if(context->response.length > 0)
230  {
231  //Debug message
232  TRACE_INFO("CoAP Server: Sending CoAP message (%" PRIuSIZE " bytes)...\r\n",
233  context->response.length);
234 
235  //Dump the contents of the message for debugging purpose
236  coapDumpMessage(context->response.buffer, context->response.length);
237 
238  //Send CoAP response message
239  error = coapServerSendResponse(context, context->response.buffer,
240  context->response.length);
241  }
242  }
243 
244  //Return status code
245  return error;
246 }
247 
248 
249 /**
250  * @brief Reject a CoAP request
251  * @param[in] context Pointer to the CoAP server context
252  * @return Error code
253  **/
254 
256 {
257  error_t error;
258  const CoapMessageHeader *header;
259 
260  //Initialize status code
261  error = NO_ERROR;
262 
263  //Debug message
264  TRACE_INFO("CoAP Server: Rejecting CoAP message...\r\n");
265 
266  //Point to the CoAP message header
267  header = (CoapMessageHeader *) &context->request.buffer;
268 
269  //Check the type of the request
270  if(header->type == COAP_TYPE_CON)
271  {
272  //Rejecting a Confirmable message is effected by sending a matching
273  //Reset message
274  error = coapServerFormatReset(context, ntohs(header->mid));
275  }
276  else if(header->type == COAP_TYPE_NON)
277  {
278  //Rejecting a Non-confirmable message may involve sending a matching
279  //Reset message, and apart from the Reset message the rejected message
280  //must be silently ignored (refer to RFC 7252, section 4.3)
281  error = coapServerFormatReset(context, ntohs(header->mid));
282  }
283  else
284  {
285  //Rejecting an Acknowledgment or Reset message is effected by
286  //silently ignoring it (refer to RFC 7252, section 4.2)
287  context->response.length = 0;
288  }
289 
290  //Return status code
291  return error;
292 }
293 
294 
295 /**
296  * @brief Initialize CoAP response message
297  * @param[in] context Pointer to the CoAP server context
298  * @return Error code
299  **/
300 
302 {
303  CoapMessageHeader *requestHeader;
304  CoapMessageHeader *responseHeader;
305 
306  //Point to the CoAP request header
307  requestHeader = (CoapMessageHeader *) context->request.buffer;
308  //Point to the CoAP response header
309  responseHeader = (CoapMessageHeader *) context->response.buffer;
310 
311  //Format message header
312  responseHeader->version = COAP_VERSION_1;
313  responseHeader->tokenLen = requestHeader->tokenLen;
314  responseHeader->code = COAP_CODE_INTERNAL_SERVER;
315  responseHeader->mid = requestHeader->mid;
316 
317  //If immediately available, the response to a request carried in a
318  //Confirmable message is carried in an Acknowledgement (ACK) message
319  if(requestHeader->type == COAP_TYPE_CON)
320  {
321  responseHeader->type = COAP_TYPE_ACK;
322  }
323  else
324  {
325  responseHeader->type = COAP_TYPE_NON;
326  }
327 
328  //The token is used to match a response with a request
329  osMemcpy(responseHeader->token, requestHeader->token,
330  requestHeader->tokenLen);
331 
332  //Set the length of the CoAP message
333  context->response.length = sizeof(CoapMessageHeader) + responseHeader->tokenLen;
334  context->response.pos = 0;
335 
336  //Successful processing
337  return NO_ERROR;
338 }
339 
340 
341 /**
342  * @brief Send CoAP response
343  * @param[in] context Pointer to the CoAP server context
344  * @param[in] data Pointer to a buffer containing the response message
345  * @param[in] length Length of the response message, in bytes
346  * @return Error code
347  **/
348 
350  const void *data, size_t length)
351 {
352  error_t error;
353 
354 #if (COAP_SERVER_DTLS_SUPPORT == ENABLED)
355  //DTLS-secured communication?
356  if(context->settings.dtlsInitCallback != NULL)
357  {
358  uint_t i;
359  CoapDtlsSession *session;
360 
361  //Loop through DTLS sessions
362  for(i = 0; i < COAP_SERVER_MAX_SESSIONS; i++)
363  {
364  //Point to the current DTLS session
365  session = &context->session[i];
366 
367  //Valid DTLS session?
368  if(session->dtlsContext != NULL)
369  {
370  //Matching DTLS session?
371  if(ipCompAddr(&session->serverIpAddr, &context->serverIpAddr) &&
372  ipCompAddr(&session->clientIpAddr, &context->clientIpAddr) &&
373  session->clientPort == context->clientPort)
374  {
375  break;
376  }
377  }
378  }
379 
380  //Any matching DTLS session?
382  {
383  //Send DTLS datagram
384  error = tlsWrite(session->dtlsContext, data, length, NULL, 0);
385  }
386  else
387  {
388  //Report an error
389  error = ERROR_FAILURE;
390  }
391  }
392  else
393 #endif
394  {
395  //Send UDP datagram
396  error = socketSendTo(context->socket, &context->clientIpAddr,
397  context->clientPort, data, length, NULL, 0);
398  }
399 
400  //Return status code
401  return error;
402 }
403 
404 
405 /**
406  * @brief Format Reset message
407  * @param[in] context Pointer to the CoAP server context
408  * @param[in] mid Message ID
409  * @return Error code
410  **/
411 
413 {
414  CoapMessageHeader *header;
415 
416  //Point to the CoAP response header
417  header = (CoapMessageHeader *) context->response.buffer;
418 
419  //Format Reset message
420  header->version = COAP_VERSION_1;
421  header->type = COAP_TYPE_RST;
422  header->tokenLen = 0;
423  header->code = COAP_CODE_EMPTY;
424 
425  //The Reset message message must echo the message ID of the confirmable
426  //message and must be empty (refer to RFC 7252, section 4.2)
427  header->mid = htons(mid);
428 
429  //Set the length of the CoAP message
430  context->response.length = sizeof(CoapMessageHeader);
431 
432  //Successful processing
433  return NO_ERROR;
434 }
435 
436 #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:222
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:2307
void coapServerTick(CoapServerContext *context)
Handle periodic operations.
#define osMemcpy(dest, src, length)
Definition: os_port.h:141
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:317
@ 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:95
uint8_t length
Definition: tcp.h:368
@ 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:1854
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:1507
@ 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:50
@ COAP_TYPE_NON
Non-confirmable message.
Definition: coap_common.h:90
#define osStrcpy(s1, s2)
Definition: os_port.h:207
CoapCode
CoAP method and response codes.
Definition: coap_common.h:113
error_t tlsConnect(TlsContext *context)
Initiate the TLS handshake.
Definition: tls.c:1763
@ 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.