echo_server_misc.c
Go to the documentation of this file.
1 /**
2  * @file echo_server_misc.c
3  * @brief Helper functions for Echo server
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2010-2025 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.5.2
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL ECHO_TRACE_LEVEL
33 
34 //Dependencies
35 #include "core/net.h"
36 #include "echo/echo_server.h"
37 #include "echo/echo_server_misc.h"
38 #include "debug.h"
39 
40 //Check TCP/IP stack configuration
41 #if (ECHO_SERVER_SUPPORT == ENABLED)
42 
43 
44 /**
45  * @brief Handle periodic operations
46  * @param[in] context Pointer to the Echo server context
47  **/
48 
50 {
51 #if (ECHO_SERVER_TCP_SUPPORT == ENABLED)
52  uint_t i;
54  EchoTcpConnection *connection;
55 
56  //Get current time
58 
59  //Loop through the connection table
60  for(i = 0; i < ECHO_SERVER_MAX_TCP_CONNECTIONS; i++)
61  {
62  //Point to the current entry
63  connection = &context->tcpConnection[i];
64 
65  //Check the state of the current connection
66  if(connection->state != ECHO_TCP_CONNECTION_STATE_CLOSED)
67  {
68  //Disconnect inactive client after idle timeout
69  if(timeCompare(time, connection->timestamp + ECHO_SERVER_TIMEOUT) >= 0)
70  {
71  //Debug message
72  TRACE_INFO("Echo server: Closing inactive TCP connection...\r\n");
73  //Close the TCP connection
74  echoServerCloseTcpConnection(connection);
75  }
76  }
77  }
78 #endif
79 }
80 
81 
82 /**
83  * @brief Accept connection request
84  * @param[in] context Pointer to the Echo server context
85  **/
86 
88 {
89 #if (ECHO_SERVER_TCP_SUPPORT == ENABLED)
90  uint_t i;
91  Socket *socket;
92  IpAddr clientIpAddr;
93  uint16_t clientPort;
94  EchoTcpConnection *connection;
95 
96  //Accept incoming connection
97  socket = socketAccept(context->tcpSocket, &clientIpAddr, &clientPort);
98 
99  //Make sure the socket handle is valid
100  if(socket != NULL)
101  {
102  //Force the socket to operate in non-blocking mode
104 
105  //Initialize pointer
106  connection = NULL;
107 
108  //Loop through the TCP connection table
109  for(i = 0; i < ECHO_SERVER_MAX_TCP_CONNECTIONS; i++)
110  {
111  //Check the state of the current connection
113  {
114  //The current entry is free
115  connection = &context->tcpConnection[i];
116  break;
117  }
118  }
119 
120  //If the connection table runs out of space, then the client's connection
121  //request is rejected
122  if(connection != NULL)
123  {
124  //Debug message
125  TRACE_INFO("Echo Server: TCP connection established with client %s port %"
126  PRIu16 "...\r\n", ipAddrToString(&clientIpAddr, NULL), clientPort);
127 
128  //Clear the structure describing the connection
129  osMemset(connection, 0, sizeof(EchoTcpConnection));
130 
131  //Save socket handle
132  connection->socket = socket;
133  //Initialize time stamp
134  connection->timestamp = osGetSystemTime();
135 
136  //Wait for incoming data
138  }
139  else
140  {
141  //Debug message
142  TRACE_INFO("Echo Server: TCP connection refused with client %s port %"
143  PRIu16 "...\r\n", ipAddrToString(&clientIpAddr, NULL), clientPort);
144 
145  //The Echo server cannot accept the incoming connection request
147  }
148  }
149 #endif
150 }
151 
152 
153 /**
154  * @brief Register TCP connection events
155  * @param[in] connection Pointer to the TCP connection
156  * @param[in] eventDesc Socket events to be registered
157  **/
158 
160  SocketEventDesc *eventDesc)
161 {
162  //Check the state of the TCP connection
163  if(connection->state == ECHO_TCP_CONNECTION_STATE_OPEN)
164  {
165  //Any data pending in the send buffer?
166  if(connection->bufferPos < connection->bufferLen)
167  {
168  //Wait until there is more room in the send buffer
169  eventDesc->socket = connection->socket;
170  eventDesc->eventMask = SOCKET_EVENT_TX_READY;
171  }
172  else
173  {
174  //Wait for data to be available for reading
175  eventDesc->socket = connection->socket;
176  eventDesc->eventMask = SOCKET_EVENT_RX_READY;
177  }
178  }
179 }
180 
181 
182 /**
183  * @brief Connection event handler
184  * @param[in] connection Pointer to the TCP connection
185  **/
186 
188 {
189  error_t error;
190  size_t n;
191 
192  //Check the state of the TCP connection
193  if(connection->state == ECHO_TCP_CONNECTION_STATE_OPEN)
194  {
195  //Any data pending in the send buffer?
196  if(connection->bufferPos < connection->bufferLen)
197  {
198  //Send more data
199  error = socketSend(connection->socket,
200  connection->buffer + connection->bufferPos,
201  connection->bufferLen - connection->bufferPos, &n,
203 
204  //Check status code
205  if(error == NO_ERROR || error == ERROR_TIMEOUT)
206  {
207  //Advance data pointer
208  connection->bufferPos += n;
209 
210  //Update time stamp
211  connection->timestamp = osGetSystemTime();
212  }
213  }
214  else
215  {
216  //Receive more data
217  error = socketReceive(connection->socket, connection->buffer,
219 
220  //Check status code
221  if(error == NO_ERROR)
222  {
223  //Data has been successfully received
224  connection->bufferLen = n;
225  connection->bufferPos = 0;
226 
227  //Update time stamp
228  connection->timestamp = osGetSystemTime();
229  }
230  else if(error == ERROR_END_OF_STREAM)
231  {
232  //Debug message
233  TRACE_INFO("Echo server: Closing TCP connection...\r\n");
234  //Close the TCP connection
235  echoServerCloseTcpConnection(connection);
236  }
237  else
238  {
239  //Just for sanity
240  }
241  }
242  }
243 }
244 
245 
246 /**
247  * @brief Close TCP connection
248  * @param[in] connection Pointer to the TCP connection
249  **/
250 
252 {
253  //Close TCP connection
254  if(connection->socket != NULL)
255  {
256  socketClose(connection->socket);
257  connection->socket = NULL;
258  }
259 
260  //Mark the connection as closed
262 }
263 
264 
265 /**
266  * @brief Process incoming UDP datagram
267  * @param[in] context Pointer to the Echo server context
268  **/
269 
271 {
272 #if (ECHO_SERVER_UDP_SUPPORT == ENABLED)
273  error_t error;
274  size_t length;
275  IpAddr clientIpAddr;
276  uint16_t clientPort;
277 
278  //Receive incoming datagram
279  error = socketReceiveFrom(context->udpSocket, &clientIpAddr, &clientPort,
281 
282  //Check status code
283  if(!error)
284  {
285  //Debug message
286  TRACE_DEBUG("Echo server: UDP datagram received from %s port %" PRIu16
287  " (%" PRIuSIZE " bytes)\r\n",
288  ipAddrToString(&clientIpAddr, NULL), clientPort, length);
289 
290  //When a datagram is received, the data from it is sent back in an
291  //answering datagram
292  error = socketSendTo(context->udpSocket, &clientIpAddr, clientPort,
293  context->udpBuffer, length, NULL, 0);
294  }
295 #endif
296 }
297 
298 #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:1491
#define ECHO_SERVER_UDP_BUFFER_SIZE
Definition: echo_server.h:87
char_t buffer[ECHO_SERVER_TCP_BUFFER_SIZE]
Memory buffer for input/output operations (TCP)
Definition: echo_server.h:152
IP network address.
Definition: ip.h:90
void socketClose(Socket *socket)
Close an existing socket.
Definition: socket.c:2071
char_t * ipAddrToString(const IpAddr *ipAddr, char_t *str)
Convert a binary IP address to a string representation.
Definition: ip.c:804
@ ERROR_END_OF_STREAM
Definition: error.h:211
#define timeCompare(t1, t2)
Definition: os_port.h:40
Structure describing socket events.
Definition: socket.h:432
Echo TCP connection.
Definition: echo_server.h:148
Socket * socket
Underlying TCP socket.
Definition: echo_server.h:150
@ ECHO_TCP_CONNECTION_STATE_CLOSED
Definition: echo_server.h:126
@ ECHO_TCP_CONNECTION_STATE_OPEN
Definition: echo_server.h:127
void echoServerProcessTcpConnectionEvents(EchoTcpConnection *connection)
Connection event handler.
void echoServerAcceptTcpConnection(EchoServerContext *context)
Accept connection request.
error_t
Error codes.
Definition: error.h:43
Echo server.
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:1701
int_t socket(int_t family, int_t type, int_t protocol)
Create a socket that is bound to a specific transport service provider.
Definition: bsd_socket.c:65
@ SOCKET_EVENT_TX_READY
Definition: socket.h:175
size_t bufferPos
Current position in the buffer.
Definition: echo_server.h:154
Socket * tcpSocket
Listening TCP socket.
Definition: echo_server.h:171
error_t socketReceiveFrom(Socket *socket, IpAddr *srcIpAddr, uint16_t *srcPort, void *data, size_t size, size_t *received, uint_t flags)
Receive a datagram from a connectionless socket.
Definition: socket.c:1723
#define ECHO_SERVER_MAX_TCP_CONNECTIONS
Definition: echo_server.h:66
#define TRACE_INFO(...)
Definition: debug.h:105
uint8_t length
Definition: tcp.h:375
void echoServerTick(EchoServerContext *context)
Handle periodic operations.
EchoTcpConnection tcpConnection[ECHO_SERVER_MAX_TCP_CONNECTIONS]
TCP connections.
Definition: echo_server.h:172
#define ECHO_SERVER_TIMEOUT
Definition: echo_server.h:94
Socket * socketAccept(Socket *socket, IpAddr *clientIpAddr, uint16_t *clientPort)
Permit an incoming connection attempt on a socket.
Definition: socket.c:1456
uint32_t systime_t
System time.
#define TRACE_DEBUG(...)
Definition: debug.h:119
@ ERROR_TIMEOUT
Definition: error.h:95
Socket * udpSocket
UDP socket.
Definition: echo_server.h:175
uint32_t time
Echo server context.
Definition: echo_server.h:163
#define ECHO_SERVER_TCP_BUFFER_SIZE
Definition: echo_server.h:73
@ SOCKET_FLAG_NO_DELAY
Definition: socket.h:143
@ SOCKET_EVENT_RX_READY
Definition: socket.h:179
uint8_t n
#define Socket
Definition: socket.h:36
Helper functions for Echo server.
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:1512
void echoServerRegisterTcpConnectionEvents(EchoTcpConnection *connection, SocketEventDesc *eventDesc)
Register TCP connection events.
void echoServerCloseTcpConnection(EchoTcpConnection *connection)
Close TCP connection.
Socket * socket
Handle to a socket to monitor.
Definition: socket.h:433
#define PRIuSIZE
unsigned int uint_t
Definition: compiler_port.h:57
#define osMemset(p, value, length)
Definition: os_port.h:138
void echoServerProcessUdpDatagram(EchoServerContext *context)
Process incoming UDP datagram.
TCP/IP stack core.
systime_t timestamp
Time stamp.
Definition: echo_server.h:151
EchoTcpConnectionState state
Connection state.
Definition: echo_server.h:149
char_t udpBuffer[ECHO_SERVER_UDP_BUFFER_SIZE]
Memory buffer for input/output operations (UDP)
Definition: echo_server.h:176
error_t socketSetTimeout(Socket *socket, systime_t timeout)
Set timeout value for blocking operations.
Definition: socket.c:148
size_t bufferLen
Length of the buffer, in bytes.
Definition: echo_server.h:153
uint_t eventMask
Requested events.
Definition: socket.h:434
@ NO_ERROR
Success.
Definition: error.h:44
Debugging facilities.
systime_t osGetSystemTime(void)
Retrieve system time.