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.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_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  break;
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 #if (NET_RTOS_SUPPORT == ENABLED)
285  //Stop the CoAP server
286  context->stop = TRUE;
287  //Send a signal to the task to abort any blocking operation
288  osSetEvent(&context->event);
289 
290  //Wait for the task to terminate
291  while(context->running)
292  {
293  osDelayTask(1);
294  }
295 #endif
296 
297 #if (COAP_SERVER_DTLS_SUPPORT == ENABLED)
298  //Loop through DTLS sessions
299  for(i = 0; i < COAP_SERVER_MAX_SESSIONS; i++)
300  {
301  //Release DTLS session
302  coapServerDeleteSession(&context->session[i]);
303  }
304 #endif
305 
306  //Close the UDP socket
307  socketClose(context->socket);
308  context->socket = NULL;
309  }
310 
311  //Successful processing
312  return NO_ERROR;
313 }
314 
315 
316 /**
317  * @brief CoAP server task
318  * @param[in] context Pointer to the CoAP server context
319  **/
320 
322 {
323  error_t error;
324  SocketEventDesc eventDesc;
325 
326 #if (NET_RTOS_SUPPORT == ENABLED)
327  //Task prologue
328  osEnterTask();
329 
330  //Process events
331  while(1)
332  {
333 #endif
334  //Specify the events the application is interested in
335  eventDesc.socket = context->socket;
336  eventDesc.eventMask = SOCKET_EVENT_RX_READY;
337  eventDesc.eventFlags = 0;
338 
339  //Wait for an event
340  socketPoll(&eventDesc, 1, &context->event, COAP_SERVER_TICK_INTERVAL);
341 
342  //Stop request?
343  if(context->stop)
344  {
345  //Stop CoAP server operation
346  context->running = FALSE;
347  //Task epilogue
348  osExitTask();
349  //Kill ourselves
351  }
352 
353  //Any datagram received?
354  if(eventDesc.eventFlags != 0)
355  {
356  //Receive incoming datagram
357  error = socketReceiveEx(context->socket, &context->clientIpAddr,
358  &context->clientPort, &context->serverIpAddr, context->buffer,
359  COAP_SERVER_BUFFER_SIZE, &context->bufferLen, 0);
360 
361  //Check status code
362  if(!error)
363  {
364  //An endpoint must be prepared to receive multicast messages but may
365  //ignore them if multicast service discovery is not desired
366  if(!ipIsMulticastAddr(&context->serverIpAddr))
367  {
368  #if (COAP_SERVER_DTLS_SUPPORT == ENABLED)
369  //DTLS-secured communication?
370  if(context->settings.dtlsInitCallback != NULL)
371  {
372  //Demultiplexing of incoming datagrams into separate DTLS sessions
373  error = coapServerDemultiplexSession(context);
374  }
375  else
376  #endif
377  {
378  //Process the received CoAP message
379  error = coapServerProcessRequest(context, context->buffer,
380  context->bufferLen);
381  }
382  }
383  }
384  }
385 
386  //Handle periodic operations
387  coapServerTick(context);
388 #if (NET_RTOS_SUPPORT == ENABLED)
389  }
390 #endif
391 }
392 
393 
394 /**
395  * @brief Release CoAP server context
396  * @param[in] context Pointer to the CoAP server context
397  **/
398 
400 {
401  //Make sure the CoAP server context is valid
402  if(context != NULL)
403  {
404  //Free previously allocated resources
405  osDeleteEvent(&context->event);
406 
407  //Clear CoAP server context
408  osMemset(context, 0, sizeof(CoapServerContext));
409  }
410 }
411 
412 #endif
NetInterface * interface
Underlying network interface.
Definition: coap_server.h:169
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:1316
#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:2062
void coapServerTask(CoapServerContext *context)
CoAP server task.
Definition: coap_server.c:321
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:171
@ SOCKET_TYPE_DGRAM
Definition: socket.h:93
Helper functions for CoAP server.
#define OS_SELF_TASK_ID
Structure describing socket events.
Definition: socket.h:426
#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:170
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:141
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:250
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
const OsTaskParameters OS_TASK_DEFAULT_PARAMS
#define TRACE_INFO(...)
Definition: debug.h:95
Socket * socketOpen(uint_t type, uint_t protocol)
Create a socket (UDP or TCP)
Definition: socket.c:125
error_t coapServerInit(CoapServerContext *context, const CoapServerSettings *settings)
CoAP server initialization.
Definition: coap_server.c:84
#define osEnterTask()
uint_t eventFlags
Returned events.
Definition: socket.h:429
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:2149
#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:399
void coapServerGetDefaultSettings(CoapServerSettings *settings)
Initialize settings with default values.
Definition: coap_server.c:51
#define CoapServerContext
Definition: coap_server.h:121
CoapServerRequestCallback requestCallback
CoAP request callback.
Definition: coap_server.h:175
Transport protocol abstraction layer.
error_t coapServerSetCookieSecret(CoapServerContext *context, const uint8_t *cookieSecret, size_t cookieSecretLen)
Set cookie secret.
Definition: coap_server.c:140
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:1736
CoapServerDtlsInitCallback dtlsInitCallback
DTLS initialization callback.
Definition: coap_server.h:173
#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:427
unsigned int uint_t
Definition: compiler_port.h:50
#define osMemset(p, value, length)
Definition: os_port.h:135
error_t coapServerStop(CoapServerContext *context)
Stop CoAP server.
Definition: coap_server.c:268
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:148
#define COAP_SERVER_BUFFER_SIZE
Definition: coap_server.h:84
error_t coapServerStart(CoapServerContext *context)
Start CoAP server.
Definition: coap_server.c:170
uint_t eventMask
Requested events.
Definition: socket.h:428
@ ERROR_ALREADY_RUNNING
Definition: error.h:293
@ NO_ERROR
Success.
Definition: error.h:44
Debugging facilities.