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