coap_client_transport.c
Go to the documentation of this file.
1 /**
2  * @file coap_client_transport.c
3  * @brief Transport protocol abstraction layer
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 "core/net.h"
36 #include "coap/coap_client.h"
38 #include "debug.h"
39 
40 //Check TCP/IP stack configuration
41 #if (COAP_CLIENT_SUPPORT == ENABLED)
42 
43 
44 /**
45  * @brief Open network connection
46  * @param[in] context Pointer to the CoAP client context
47  * @return Error code
48  **/
49 
51 {
52  error_t error;
53 
54  //Open a UDP socket
55  context->socket = socketOpenEx(context->netContext, SOCKET_TYPE_DGRAM,
57  //Failed to open socket?
58  if(context->socket == NULL)
59  return ERROR_OPEN_FAILED;
60 
61  //Associate the socket with the relevant interface
62  error = socketBindToInterface(context->socket, context->interface);
63  //Any error to report?
64  if(error)
65  return error;
66 
67  //Force the socket to operate in non-blocking mode
68  error = socketSetTimeout(context->socket, 0);
69  //Any error to report?
70  if(error)
71  return error;
72 
73 #if (COAP_CLIENT_DTLS_SUPPORT == ENABLED)
74  //DTLS transport protocol?
75  if(context->transportProtocol == COAP_TRANSPORT_PROTOCOL_DTLS)
76  {
77  //Allocate DTLS context
78  context->dtlsContext = tlsInit();
79  //Failed to allocate DTLS context?
80  if(context->dtlsContext == NULL)
81  return ERROR_OPEN_FAILED;
82 
83  //Select client operation mode
84  error = tlsSetConnectionEnd(context->dtlsContext,
86  //Any error to report?
87  if(error)
88  return error;
89 
90  //Set the transport protocol to be used (DTLS)
91  error = tlsSetTransportProtocol(context->dtlsContext,
93  //Any error to report?
94  if(error)
95  return error;
96 
97  //Bind DTLS to the relevant socket
98  error = tlsSetSocket(context->dtlsContext, context->socket);
99  //Any error to report?
100  if(error)
101  return error;
102 
103  //Force DTLS to operate in non-blocking mode
104  error = tlsSetTimeout(context->dtlsContext, 0);
105  //Any error to report?
106  if(error)
107  return error;
108 
109  //Restore DTLS session, if any
110  error = tlsRestoreSessionState(context->dtlsContext, &context->dtlsSession);
111  //Any error to report?
112  if(error)
113  return error;
114 
115  //Invoke user-defined callback, if any
116  if(context->dtlsInitCallback != NULL)
117  {
118  //Perform DTLS related initialization
119  error = context->dtlsInitCallback(context, context->dtlsContext);
120  //Any error to report?
121  if(error)
122  return error;
123  }
124  }
125 #endif
126 
127  //Successful processing
128  return NO_ERROR;
129 }
130 
131 
132 /**
133  * @brief Establish network connection
134  * @param[in] context Pointer to the CoAP client context
135  * @param[in] serverIpAddr IP address of the CoAP server
136  * @param[in] serverPort UDP port number
137  * @return Error code
138  **/
139 
141  const IpAddr *serverIpAddr, uint16_t serverPort)
142 {
143  error_t error;
144 
145  //Only accept datagrams from the specified CoAP server
146  error = socketConnect(context->socket, serverIpAddr, serverPort);
147  //Any error to report?
148  if(error)
149  return error;
150 
151 #if (COAP_CLIENT_DTLS_SUPPORT == ENABLED)
152  //DTLS transport protocol?
153  if(context->transportProtocol == COAP_TRANSPORT_PROTOCOL_DTLS)
154  {
155  //Perform DTLS handshake
156  error = tlsConnect(context->dtlsContext);
157  //Any error to report?
158  if(error)
159  return error;
160 
161  //Save DTLS session
162  error = tlsSaveSessionState(context->dtlsContext, &context->dtlsSession);
163  //Any error to report?
164  if(error)
165  return error;
166  }
167 #endif
168 
169  //Successful processing
170  return NO_ERROR;
171 }
172 
173 
174 /**
175  * @brief Shutdown network connection
176  * @param[in] context Pointer to the CoAP client context
177  * @return Error code
178  **/
179 
181 {
182  error_t error;
183 
184  //Initialize status code
185  error = NO_ERROR;
186 
187 #if (COAP_CLIENT_DTLS_SUPPORT == ENABLED)
188  //DTLS transport protocol?
189  if(context->transportProtocol == COAP_TRANSPORT_PROTOCOL_DTLS)
190  {
191  //Shutdown DTLS session
192  error = tlsShutdown(context->dtlsContext);
193  }
194 #endif
195 
196  //Return status code
197  return error;
198 }
199 
200 
201 /**
202  * @brief Close network connection
203  * @param[in] context Pointer to the CoAP client context
204  **/
205 
207 {
208 #if (COAP_CLIENT_DTLS_SUPPORT == ENABLED)
209  //DTLS transport protocol?
210  if(context->transportProtocol == COAP_TRANSPORT_PROTOCOL_DTLS)
211  {
212  //Valid DTLS context?
213  if(context->dtlsContext != NULL)
214  {
215  //Release DTLS context
216  tlsFree(context->dtlsContext);
217  context->dtlsContext = NULL;
218  }
219  }
220 #endif
221 
222  //Valid socket?
223  if(context->socket != NULL)
224  {
225  //Close UDP socket
226  socketClose(context->socket);
227  context->socket = NULL;
228  }
229 }
230 
231 
232 /**
233  * @brief Send a datagram
234  * @param[in] context Pointer to the CoAP client context
235  * @param[in] data Pointer to a buffer containing the datagram to be transmitted
236  * @param[in] length Length of the datagram, in bytes
237  * @return Error code
238  **/
239 
241  const void *data, size_t length)
242 {
243  error_t error;
244 
245 #if (COAP_CLIENT_DTLS_SUPPORT == ENABLED)
246  //DTLS transport protocol?
247  if(context->transportProtocol == COAP_TRANSPORT_PROTOCOL_DTLS)
248  {
249  //Transmit datagram
250  error = tlsWrite(context->dtlsContext, data, length, NULL, 0);
251  }
252  else
253 #endif
254  //UDP transport protocol?
255  {
256  //Transmit datagram
257  error = socketSend(context->socket, data, length, NULL, 0);
258  }
259 
260  //Return status code
261  return error;
262 }
263 
264 
265 /**
266  * @brief Receive a datagram
267  * @param[in] context Pointer to the CoAP client context
268  * @param[out] data Buffer into which the received datagram will be placed
269  * @param[in] size Maximum number of bytes that can be received
270  * @param[out] received Number of bytes that have been received
271  * @return Error code
272  **/
273 
275  void *data, size_t size, size_t *received)
276 {
277  error_t error;
278 
279  //No data has been read yet
280  *received = 0;
281 
282 #if (COAP_CLIENT_DTLS_SUPPORT == ENABLED)
283  //DTLS transport protocol?
284  if(context->transportProtocol == COAP_TRANSPORT_PROTOCOL_DTLS)
285  {
286  //Receive datagram
287  error = tlsRead(context->dtlsContext, data, size, received, 0);
288  }
289  else
290 #endif
291  //UDP transport protocol?
292  {
293  //Receive datagram
294  error = socketReceive(context->socket, data, size, received, 0);
295  }
296 
297  //Return status code
298  return error;
299 }
300 
301 
302 /**
303  * @brief Wait for incoming datagrams
304  * @param[in] context Pointer to the CoAP client context
305  * @param[in] timeout Maximum time to wait before returning
306  * @return Error code
307  **/
308 
310  systime_t timeout)
311 {
312  error_t error;
313  SocketEventDesc eventDesc[1];
314 
315  //Initialize status code
316  error = ERROR_BUFFER_EMPTY;
317 
318 #if (COAP_CLIENT_DTLS_SUPPORT == ENABLED)
319  //DTLS transport protocol?
320  if(context->transportProtocol == COAP_TRANSPORT_PROTOCOL_DTLS)
321  {
322  //Check whether a datagram is pending in the receive buffer
323  if(tlsIsRxReady(context->dtlsContext))
324  {
325  //No need to poll the underlying socket for incoming traffic...
326  error = NO_ERROR;
327  }
328  }
329 #endif
330 
331  //Check status code
332  if(error == ERROR_BUFFER_EMPTY)
333  {
334  //Set the events the application is interested in
335  eventDesc[0].socket = context->socket;
336  eventDesc[0].eventMask = SOCKET_EVENT_RX_READY;
337 
338  //Release exclusive access to the CoAP client context
339  osReleaseMutex(&context->mutex);
340 
341  //Wait for incoming traffic
342  error = socketPoll(eventDesc, arraysize(eventDesc), &context->event,
343  timeout);
344 
345  //Acquire exclusive access to the CoAP client context
346  osAcquireMutex(&context->mutex);
347  }
348 
349  //Return status code
350  return error;
351 }
352 
353 #endif
error_t socketSend(Socket *socket, const void *data, size_t length, size_t *written, uint_t flags)
Send data to a connected socket.
Definition: socket.c:1514
TlsContext * tlsInit(void)
TLS context initialization.
Definition: tls.c:67
@ SOCKET_IP_PROTO_UDP
Definition: socket.h:108
error_t tlsSetConnectionEnd(TlsContext *context, TlsConnectionEnd entity)
Set operation mode (client or server)
Definition: tls.c:385
error_t tlsSetTransportProtocol(TlsContext *context, TlsTransportProtocol transportProtocol)
Set the transport protocol to be used.
Definition: tls.c:341
error_t coapClientSendDatagram(CoapClientContext *context, const void *data, size_t length)
Send a datagram.
IP network address.
Definition: ip.h:90
error_t coapClientShutdownConnection(CoapClientContext *context)
Shutdown network connection.
uint8_t data[]
Definition: ethernet.h:224
void socketClose(Socket *socket)
Close an existing socket.
Definition: socket.c:2094
@ TLS_TRANSPORT_PROTOCOL_DATAGRAM
Definition: tls.h:1000
@ SOCKET_TYPE_DGRAM
Definition: socket.h:93
error_t coapClientEstablishConnection(CoapClientContext *context, const IpAddr *serverIpAddr, uint16_t serverPort)
Establish network connection.
#define CoapClientContext
Definition: coap_client.h:144
Structure describing socket events.
Definition: socket.h:433
error_t tlsRestoreSessionState(TlsContext *context, const TlsSessionState *session)
Restore TLS session.
Definition: tls.c:3012
@ ERROR_OPEN_FAILED
Definition: error.h:75
error_t tlsShutdown(TlsContext *context)
Gracefully close TLS session.
Definition: tls.c:2603
#define tlsSetSocket(context, socket)
Definition: tls.h:970
error_t
Error codes.
Definition: error.h:43
error_t coapClientWaitForDatagram(CoapClientContext *context, systime_t timeout)
Wait for incoming datagrams.
error_t socketReceive(Socket *socket, void *data, size_t size, size_t *received, uint_t flags)
Receive data from a connected socket.
Definition: socket.c:1724
error_t coapClientReceiveDatagram(CoapClientContext *context, void *data, size_t size, size_t *received)
Receive a datagram.
error_t tlsSetTimeout(TlsContext *context, systime_t timeout)
Set timeout for blocking calls (for DTLS only)
Definition: tls.c:1633
error_t coapClientOpenConnection(CoapClientContext *context)
Open network connection.
CoAP client.
@ ERROR_BUFFER_EMPTY
Definition: error.h:142
error_t socketConnect(Socket *socket, const IpAddr *remoteIpAddr, uint16_t remotePort)
Establish a connection to a specified socket.
Definition: socket.c:1377
error_t tlsSaveSessionState(const TlsContext *context, TlsSessionState *session)
Save TLS session.
Definition: tls.c:2943
uint8_t length
Definition: tcp.h:375
error_t tlsRead(TlsContext *context, void *data, size_t size, size_t *received, uint_t flags)
Receive application data from a the remote host using TLS.
Definition: tls.c:2285
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
uint32_t systime_t
System time.
bool_t tlsIsRxReady(TlsContext *context)
Check whether some data is available in the receive buffer.
Definition: tls.c:2558
@ COAP_TRANSPORT_PROTOCOL_DTLS
DTLS protocol.
Definition: coap_common.h:79
@ SOCKET_EVENT_RX_READY
Definition: socket.h:179
void osAcquireMutex(OsMutex *mutex)
Acquire ownership of the specified mutex object.
void osReleaseMutex(OsMutex *mutex)
Release ownership of the specified mutex object.
Socket * socketOpenEx(NetContext *context, uint_t type, uint_t protocol)
Create a socket.
Definition: socket.c:146
@ TLS_CONNECTION_END_CLIENT
Definition: tls.h:1012
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
void tlsFree(TlsContext *context)
Release TLS context.
Definition: tls.c:2765
void coapClientCloseConnection(CoapClientContext *context)
Close network connection.
Transport protocol abstraction layer.
Socket * socket
Handle to a socket to monitor.
Definition: socket.h:434
TCP/IP stack core.
error_t socketSetTimeout(Socket *socket, systime_t timeout)
Set timeout value for blocking operations.
Definition: socket.c:169
error_t tlsConnect(TlsContext *context)
Initiate the TLS handshake.
Definition: tls.c:1819
uint_t eventMask
Requested events.
Definition: socket.h:435
@ NO_ERROR
Success.
Definition: error.h:44
Debugging facilities.
#define arraysize(a)
Definition: os_port.h:71