coap_server.c
Go to the documentation of this file.
1 /**
2  * @file coap_server.c
3  * @brief 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_debug.h"
40 #include "debug.h"
41 
42 //Check TCP/IP stack configuration
43 #if (COAP_SERVER_SUPPORT == ENABLED)
44 
45 
46 /**
47  * @brief Initialize settings with default values
48  * @param[out] settings Structure that contains CoAP server settings
49  **/
50 
52 {
53  //Default task parameters
54  settings->task = OS_TASK_DEFAULT_PARAMS;
57 
58  //TCP/IP stack context
59  settings->netContext = NULL;
60  //The CoAP server is not bound to any interface
61  settings->interface = NULL;
62 
63  //CoAP port number
64  settings->port = COAP_PORT;
65 
66  //UDP initialization callback
67  settings->udpInitCallback = NULL;
68 
69 #if (COAP_SERVER_DTLS_SUPPORT == ENABLED)
70  //DTLS initialization callback function
71  settings->dtlsInitCallback = NULL;
72 #endif
73 
74  //CoAP request callback function
75  settings->requestCallback = NULL;
76 }
77 
78 
79 /**
80  * @brief CoAP server initialization
81  * @param[in] context Pointer to the CoAP server context
82  * @param[in] settings CoAP server specific settings
83  * @return Error code
84  **/
85 
87  const CoapServerSettings *settings)
88 {
89  error_t error;
90 
91  //Debug message
92  TRACE_INFO("Initializing CoAP server...\r\n");
93 
94  //Ensure the parameters are valid
95  if(context == NULL || settings == NULL)
97 
98  //Initialize status code
99  error = NO_ERROR;
100 
101  //Clear the CoAP server context
102  osMemset(context, 0, sizeof(CoapServerContext));
103 
104  //Initialize task parameters
105  context->taskParams = settings->task;
106  context->taskId = OS_INVALID_TASK_ID;
107 
108  //Attach TCP/IP stack context
109  if(settings->netContext != NULL)
110  {
111  context->netContext = settings->netContext;
112  }
113  else if(settings->interface != NULL)
114  {
115  context->netContext = settings->interface->netContext;
116  }
117  else
118  {
119  context->netContext = netGetDefaultContext();
120  }
121 
122  //Save user settings
123  context->interface = settings->interface;
124  context->port = settings->port;
125  context->udpInitCallback = settings->udpInitCallback;
126 #if (COAP_SERVER_DTLS_SUPPORT == ENABLED)
127  context->dtlsInitCallback = settings->dtlsInitCallback;
128 #endif
129  context->requestCallback = settings->requestCallback;
130 
131  //Create an event object to poll the state of the UDP socket
132  if(!osCreateEvent(&context->event))
133  {
134  //Failed to create event
135  error = ERROR_OUT_OF_RESOURCES;
136  }
137 
138  //Check status code
139  if(error)
140  {
141  //Clean up side effects
142  coapServerDeinit(context);
143  }
144 
145  //Return status code
146  return error;
147 }
148 
149 
150 /**
151  * @brief Set cookie secret
152  *
153  * This function specifies the cookie secret used while generating and
154  * verifying a cookie during the DTLS handshake
155  *
156  * @param[in] context Pointer to the CoAP server context
157  * @param[in] cookieSecret Pointer to the secret key
158  * @param[in] cookieSecretLen Length of the secret key, in bytes
159  * @return Error code
160  **/
161 
163  const uint8_t *cookieSecret, size_t cookieSecretLen)
164 {
165 #if (COAP_SERVER_DTLS_SUPPORT == ENABLED)
166  //Ensure the parameters are valid
167  if(context == NULL || cookieSecret == NULL)
169  if(cookieSecretLen > COAP_SERVER_MAX_COOKIE_SECRET_SIZE)
171 
172  //Save the secret key
173  osMemcpy(context->cookieSecret, cookieSecret, cookieSecretLen);
174  //Save the length of the secret key
175  context->cookieSecretLen = cookieSecretLen;
176 
177  //Successful processing
178  return NO_ERROR;
179 #else
180  //Not implemented
181  return ERROR_NOT_IMPLEMENTED;
182 #endif
183 }
184 
185 
186 /**
187  * @brief Start CoAP server
188  * @param[in] context Pointer to the CoAP server context
189  * @return Error code
190  **/
191 
193 {
194  error_t error;
195 
196  //Make sure the CoAP server context is valid
197  if(context == NULL)
199 
200  //Debug message
201  TRACE_INFO("Starting CoAP server...\r\n");
202 
203  //Make sure the CoAP server is not already running
204  if(context->running)
205  return ERROR_ALREADY_RUNNING;
206 
207  //Start of exception handling block
208  do
209  {
210  //Open a UDP socket
211  context->socket = socketOpenEx(context->netContext, SOCKET_TYPE_DGRAM,
213  //Failed to open socket?
214  if(context->socket == NULL)
215  {
216  //Report an error
217  error = ERROR_OPEN_FAILED;
218  break;
219  }
220 
221  //Force the socket to operate in non-blocking mode
222  error = socketSetTimeout(context->socket, 0);
223  //Any error to report?
224  if(error)
225  break;
226 
227  //Associate the socket with the relevant interface
228  error = socketBindToInterface(context->socket, context->interface);
229  //Unable to bind the socket to the desired interface?
230  if(error)
231  break;
232 
233  //The CoAP server listens for datagrams on port 5683
234  error = socketBind(context->socket, &IP_ADDR_ANY, context->port);
235  //Unable to bind the socket to the desired port?
236  if(error)
237  break;
238 
239  //Any registered callback?
240  if(context->udpInitCallback != NULL)
241  {
242  //Invoke user callback function
243  error = context->udpInitCallback(context, context->socket);
244  //Any error to report?
245  if(error)
246  break;
247  }
248 
249  //Start the CoAP server
250  context->stop = FALSE;
251  context->running = TRUE;
252 
253  //Create a task
254  context->taskId = osCreateTask("CoAP Server", (OsTaskCode) coapServerTask,
255  context, &context->taskParams);
256 
257  //Failed to create task?
258  if(context->taskId == OS_INVALID_TASK_ID)
259  {
260  //Report an error
261  error = ERROR_OUT_OF_RESOURCES;
262  break;
263  }
264 
265  //End of exception handling block
266  } while(0);
267 
268  //Any error to report?
269  if(error)
270  {
271  //Clean up side effects
272  context->running = FALSE;
273 
274  //Close the UDP socket
275  socketClose(context->socket);
276  context->socket = NULL;
277  }
278 
279  //Return status code
280  return error;
281 }
282 
283 
284 /**
285  * @brief Stop CoAP server
286  * @param[in] context Pointer to the CoAP server context
287  * @return Error code
288  **/
289 
291 {
292 #if (COAP_SERVER_DTLS_SUPPORT == ENABLED)
293  uint_t i;
294 #endif
295 
296  //Make sure the CoAP server context is valid
297  if(context == NULL)
299 
300  //Debug message
301  TRACE_INFO("Stopping CoAP server...\r\n");
302 
303  //Check whether the CoAP server is running
304  if(context->running)
305  {
306 #if (NET_RTOS_SUPPORT == ENABLED)
307  //Stop the CoAP server
308  context->stop = TRUE;
309  //Send a signal to the task to abort any blocking operation
310  osSetEvent(&context->event);
311 
312  //Wait for the task to terminate
313  while(context->running)
314  {
315  osDelayTask(1);
316  }
317 #endif
318 
319 #if (COAP_SERVER_DTLS_SUPPORT == ENABLED)
320  //Loop through DTLS sessions
321  for(i = 0; i < COAP_SERVER_MAX_SESSIONS; i++)
322  {
323  //Release DTLS session
324  coapServerDeleteSession(&context->session[i]);
325  }
326 #endif
327 
328  //Close the UDP socket
329  socketClose(context->socket);
330  context->socket = NULL;
331  }
332 
333  //Successful processing
334  return NO_ERROR;
335 }
336 
337 
338 /**
339  * @brief CoAP server task
340  * @param[in] context Pointer to the CoAP server context
341  **/
342 
344 {
345  error_t error;
346  SocketEventDesc eventDesc;
347 
348 #if (NET_RTOS_SUPPORT == ENABLED)
349  //Task prologue
350  osEnterTask();
351 
352  //Process events
353  while(1)
354  {
355 #endif
356  //Specify the events the application is interested in
357  eventDesc.socket = context->socket;
358  eventDesc.eventMask = SOCKET_EVENT_RX_READY;
359  eventDesc.eventFlags = 0;
360 
361  //Wait for an event
362  socketPoll(&eventDesc, 1, &context->event, COAP_SERVER_TICK_INTERVAL);
363 
364  //Stop request?
365  if(context->stop)
366  {
367  //Stop CoAP server operation
368  context->running = FALSE;
369  //Task epilogue
370  osExitTask();
371  //Kill ourselves
373  }
374 
375  //Any datagram received?
376  if(eventDesc.eventFlags != 0)
377  {
378  //Receive incoming datagram
379  error = socketReceiveEx(context->socket, &context->clientIpAddr,
380  &context->clientPort, &context->serverIpAddr, context->buffer,
381  COAP_SERVER_BUFFER_SIZE, &context->bufferLen, 0);
382 
383  //Check status code
384  if(!error)
385  {
386  //An endpoint must be prepared to receive multicast messages but may
387  //ignore them if multicast service discovery is not desired
388  if(!ipIsMulticastAddr(&context->serverIpAddr))
389  {
390  #if (COAP_SERVER_DTLS_SUPPORT == ENABLED)
391  //DTLS-secured communication?
392  if(context->dtlsInitCallback != NULL)
393  {
394  //Demultiplexing of incoming datagrams into separate DTLS sessions
395  error = coapServerDemultiplexSession(context);
396  }
397  else
398  #endif
399  {
400  //Process the received CoAP message
401  error = coapServerProcessRequest(context, context->buffer,
402  context->bufferLen);
403  }
404  }
405  }
406  }
407 
408  //Handle periodic operations
409  coapServerTick(context);
410 #if (NET_RTOS_SUPPORT == ENABLED)
411  }
412 #endif
413 }
414 
415 
416 /**
417  * @brief Release CoAP server context
418  * @param[in] context Pointer to the CoAP server context
419  **/
420 
422 {
423  //Make sure the CoAP server context is valid
424  if(context != NULL)
425  {
426  //Free previously allocated resources
427  osDeleteEvent(&context->event);
428 
429  //Clear CoAP server context
430  osMemset(context, 0, sizeof(CoapServerContext));
431  }
432 }
433 
434 #endif
NetInterface * interface
Underlying network interface.
Definition: coap_server.h:170
OsTaskId osCreateTask(const char_t *name, OsTaskCode taskCode, void *arg, const OsTaskParameters *params)
Create a task.
@ SOCKET_IP_PROTO_UDP
Definition: socket.h:108
error_t socketBind(Socket *socket, const IpAddr *localIpAddr, uint16_t localPort)
Associate a local address with a socket.
Definition: socket.c:1344
#define osExitTask()
@ ERROR_NOT_IMPLEMENTED
Definition: error.h:66
#define TRUE
Definition: os_port.h:50
#define OS_INVALID_TASK_ID
void socketClose(Socket *socket)
Close an existing socket.
Definition: socket.c:2094
void coapServerTask(CoapServerContext *context)
CoAP server task.
Definition: coap_server.c:343
error_t coapServerProcessRequest(CoapServerContext *context, const uint8_t *data, size_t length)
Process CoAP request.
@ ERROR_OUT_OF_RESOURCES
Definition: error.h:64
CoapServerUdpInitCallback udpInitCallback
UDP initialization callback.
Definition: coap_server.h:172
@ SOCKET_TYPE_DGRAM
Definition: socket.h:93
Helper functions for CoAP server.
#define OS_SELF_TASK_ID
Structure describing socket events.
Definition: socket.h:433
#define COAP_SERVER_MAX_SESSIONS
Definition: coap_server.h:63
#define COAP_SERVER_TICK_INTERVAL
Definition: coap_server.h:70
@ ERROR_OPEN_FAILED
Definition: error.h:75
uint16_t port
CoAP port number.
Definition: coap_server.h:171
OsTaskParameters task
Task parameters.
Definition: coap_server.h:168
const IpAddr IP_ADDR_ANY
Definition: ip.c:53
void osDeleteTask(OsTaskId taskId)
Delete a task.
#define FALSE
Definition: os_port.h:46
void coapServerTick(CoapServerContext *context)
Handle periodic operations.
@ ERROR_INVALID_PARAMETER
Invalid parameter.
Definition: error.h:47
#define osMemcpy(dest, src, length)
Definition: os_port.h:144
error_t
Error codes.
Definition: error.h:43
bool_t ipIsMulticastAddr(const IpAddr *ipAddr)
Determine whether an IP address is a multicast address.
Definition: ip.c:251
void(* OsTaskCode)(void *arg)
Task routine.
#define COAP_SERVER_PRIORITY
Definition: coap_server.h:105
void coapServerDeleteSession(CoapDtlsSession *session)
Delete DTLS session.
void osDeleteEvent(OsEvent *event)
Delete an event object.
#define COAP_PORT
Definition: coap_common.h:38
NetContext * netGetDefaultContext(void)
Get default TCP/IP stack context.
Definition: net.c:527
const OsTaskParameters OS_TASK_DEFAULT_PARAMS
#define TRACE_INFO(...)
Definition: debug.h:105
error_t coapServerInit(CoapServerContext *context, const CoapServerSettings *settings)
CoAP server initialization.
Definition: coap_server.c:86
#define osEnterTask()
uint_t eventFlags
Returned events.
Definition: socket.h:436
NetContext * netContext
TCP/IP stack context.
Definition: coap_server.h:169
error_t socketPoll(SocketEventDesc *eventDesc, uint_t size, OsEvent *extEvent, systime_t timeout)
Wait for one of a set of sockets to become ready to perform I/O.
Definition: socket.c:2182
#define socketBindToInterface
Definition: net_legacy.h:193
CoAP server.
error_t coapServerDemultiplexSession(CoapServerContext *context)
DTLS session demultiplexing.
@ SOCKET_EVENT_RX_READY
Definition: socket.h:179
Data logging functions for debugging purpose (CoAP)
void coapServerDeinit(CoapServerContext *context)
Release CoAP server context.
Definition: coap_server.c:421
void coapServerGetDefaultSettings(CoapServerSettings *settings)
Initialize settings with default values.
Definition: coap_server.c:51
Socket * socketOpenEx(NetContext *context, uint_t type, uint_t protocol)
Create a socket.
Definition: socket.c:146
#define CoapServerContext
Definition: coap_server.h:121
CoapServerRequestCallback requestCallback
CoAP request callback.
Definition: coap_server.h:176
Transport protocol abstraction layer.
error_t coapServerSetCookieSecret(CoapServerContext *context, const uint8_t *cookieSecret, size_t cookieSecretLen)
Set cookie secret.
Definition: coap_server.c:162
bool_t osCreateEvent(OsEvent *event)
Create an event object.
void osDelayTask(systime_t delay)
Delay routine.
void osSetEvent(OsEvent *event)
Set the specified event object to the signaled state.
error_t socketReceiveEx(Socket *socket, IpAddr *srcIpAddr, uint16_t *srcPort, IpAddr *destIpAddr, void *data, size_t size, size_t *received, uint_t flags)
Receive a datagram.
Definition: socket.c:1768
CoapServerDtlsInitCallback dtlsInitCallback
DTLS initialization callback.
Definition: coap_server.h:174
#define COAP_SERVER_STACK_SIZE
Definition: coap_server.h:56
#define COAP_SERVER_MAX_COOKIE_SECRET_SIZE
Definition: coap_server.h:91
Socket * socket
Handle to a socket to monitor.
Definition: socket.h:434
unsigned int uint_t
Definition: compiler_port.h:57
#define osMemset(p, value, length)
Definition: os_port.h:138
error_t coapServerStop(CoapServerContext *context)
Stop CoAP server.
Definition: coap_server.c:290
CoAP server settings.
Definition: coap_server.h:167
error_t socketSetTimeout(Socket *socket, systime_t timeout)
Set timeout value for blocking operations.
Definition: socket.c:169
#define COAP_SERVER_BUFFER_SIZE
Definition: coap_server.h:84
error_t coapServerStart(CoapServerContext *context)
Start CoAP server.
Definition: coap_server.c:192
uint_t eventMask
Requested events.
Definition: socket.h:435
@ ERROR_ALREADY_RUNNING
Definition: error.h:294
@ NO_ERROR
Success.
Definition: error.h:44
Debugging facilities.