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-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 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, 0);
202 
203  //Check status code
204  if(error == NO_ERROR || error == ERROR_TIMEOUT)
205  {
206  //Advance data pointer
207  connection->bufferPos += n;
208 
209  //Update time stamp
210  connection->timestamp = osGetSystemTime();
211  }
212  }
213  else
214  {
215  //Receive more data
216  error = socketReceive(connection->socket, connection->buffer,
218 
219  //Check status code
220  if(error == NO_ERROR)
221  {
222  //Data has been successfully received
223  connection->bufferLen = n;
224  connection->bufferPos = 0;
225 
226  //Update time stamp
227  connection->timestamp = osGetSystemTime();
228  }
229  else if(error == ERROR_END_OF_STREAM)
230  {
231  //Debug message
232  TRACE_INFO("Echo server: Closing TCP connection...\r\n");
233  //Close the TCP connection
234  echoServerCloseTcpConnection(connection);
235  }
236  else
237  {
238  //Just for sanity
239  }
240  }
241  }
242 }
243 
244 
245 /**
246  * @brief Close TCP connection
247  * @param[in] connection Pointer to the TCP connection
248  **/
249 
251 {
252  //Close TCP connection
253  if(connection->socket != NULL)
254  {
255  socketClose(connection->socket);
256  connection->socket = NULL;
257  }
258 
259  //Mark the connection as closed
261 }
262 
263 
264 /**
265  * @brief Process incoming UDP datagram
266  * @param[in] context Pointer to the Echo server context
267  **/
268 
270 {
271 #if (ECHO_SERVER_UDP_SUPPORT == ENABLED)
272  error_t error;
273  size_t length;
274  IpAddr clientIpAddr;
275  uint16_t clientPort;
276 
277  //Receive incoming datagram
278  error = socketReceiveFrom(context->udpSocket, &clientIpAddr, &clientPort,
280 
281  //Check status code
282  if(!error)
283  {
284  //Debug message
285  TRACE_DEBUG("Echo server: UDP datagram received from %s port %" PRIu16
286  " (%" PRIuSIZE " bytes)\r\n",
287  ipAddrToString(&clientIpAddr, NULL), clientPort, length);
288 
289  //When a datagram is received, the data from it is sent back in an
290  //answering datagram
291  error = socketSendTo(context->udpSocket, &clientIpAddr, clientPort,
292  context->udpBuffer, length, NULL, 0);
293  }
294 #endif
295 }
296 
297 #endif
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
unsigned int uint_t
Definition: compiler_port.h:50
#define PRIuSIZE
Debugging facilities.
#define TRACE_DEBUG(...)
Definition: debug.h:107
#define TRACE_INFO(...)
Definition: debug.h:95
uint8_t n
uint32_t time
Echo server.
#define ECHO_SERVER_TIMEOUT
Definition: echo_server.h:94
#define ECHO_SERVER_UDP_BUFFER_SIZE
Definition: echo_server.h:87
@ ECHO_TCP_CONNECTION_STATE_OPEN
Definition: echo_server.h:127
@ ECHO_TCP_CONNECTION_STATE_CLOSED
Definition: echo_server.h:126
#define ECHO_SERVER_MAX_TCP_CONNECTIONS
Definition: echo_server.h:66
#define ECHO_SERVER_TCP_BUFFER_SIZE
Definition: echo_server.h:73
void echoServerProcessUdpDatagram(EchoServerContext *context)
Process incoming UDP datagram.
void echoServerCloseTcpConnection(EchoTcpConnection *connection)
Close TCP connection.
void echoServerRegisterTcpConnectionEvents(EchoTcpConnection *connection, SocketEventDesc *eventDesc)
Register TCP connection events.
void echoServerProcessTcpConnectionEvents(EchoTcpConnection *connection)
Connection event handler.
void echoServerTick(EchoServerContext *context)
Handle periodic operations.
void echoServerAcceptTcpConnection(EchoServerContext *context)
Accept connection request.
Helper functions for Echo server.
error_t
Error codes.
Definition: error.h:43
@ ERROR_TIMEOUT
Definition: error.h:95
@ ERROR_END_OF_STREAM
Definition: error.h:210
@ NO_ERROR
Success.
Definition: error.h:44
char_t * ipAddrToString(const IpAddr *ipAddr, char_t *str)
Convert a binary IP address to a string representation.
Definition: ip.c:838
TCP/IP stack core.
#define osMemset(p, value, length)
Definition: os_port.h:135
#define timeCompare(t1, t2)
Definition: os_port.h:40
systime_t osGetSystemTime(void)
Retrieve system time.
uint32_t systime_t
System time.
Socket * socketAccept(Socket *socket, IpAddr *clientIpAddr, uint16_t *clientPort)
Permit an incoming connection attempt on a socket.
Definition: socket.c:912
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:1174
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:967
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:1152
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:946
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
#define Socket
Definition: socket.h:36
@ SOCKET_EVENT_TX_READY
Definition: socket.h:165
@ SOCKET_EVENT_RX_READY
Definition: socket.h:169
Echo server context.
Definition: echo_server.h:163
EchoTcpConnection tcpConnection[ECHO_SERVER_MAX_TCP_CONNECTIONS]
TCP connections.
Definition: echo_server.h:172
Socket * tcpSocket
Listening TCP socket.
Definition: echo_server.h:171
char_t udpBuffer[ECHO_SERVER_UDP_BUFFER_SIZE]
Memory buffer for input/output operations (UDP)
Definition: echo_server.h:176
Socket * udpSocket
UDP socket.
Definition: echo_server.h:175
Echo TCP connection.
Definition: echo_server.h:148
systime_t timestamp
Time stamp.
Definition: echo_server.h:151
char_t buffer[ECHO_SERVER_TCP_BUFFER_SIZE]
Memory buffer for input/output operations (TCP)
Definition: echo_server.h:152
size_t bufferPos
Current position in the buffer.
Definition: echo_server.h:154
EchoTcpConnectionState state
Connection state.
Definition: echo_server.h:149
size_t bufferLen
Length of the buffer, in bytes.
Definition: echo_server.h:153
Socket * socket
Underlying TCP socket.
Definition: echo_server.h:150
IP network address.
Definition: ip.h:79
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
uint8_t length
Definition: tcp.h:368