F´ Flight Software - C/C++ Documentation
A framework for building embedded system applications to NASA flight quality standards.
IpSocket.cpp
Go to the documentation of this file.
1 // ======================================================================
2 // \title IpSocket.cpp
3 // \author mstarch, crsmith
4 // \brief cpp file for IpSocket core implementation classes
5 //
6 // \copyright
7 // Copyright 2009-2020, by the California Institute of Technology.
8 // ALL RIGHTS RESERVED. United States Government Sponsorship
9 // acknowledged.
10 //
11 // ======================================================================
12 #include <Drv/Ip/IpSocket.hpp>
13 #include <Fw/FPrimeBasicTypes.hpp>
14 #include <Fw/Types/Assert.hpp>
15 #include <Fw/Types/StringUtils.hpp>
16 #include <cerrno>
17 #include <cstring>
18 
19 // This implementation has primarily implemented to isolate
20 // the socket interface from the F' Fw::Buffer class.
21 // There is a macro in VxWorks (m_data) that collides with
22 // the m_data member in Fw::Buffer.
23 
24 namespace Drv {
25 
26 IpSocket::IpSocket() : m_timeoutSeconds(0), m_timeoutMicroseconds(0), m_port(0) {
27  (void)::memset(this->m_ipv4_address, 0, sizeof(this->m_ipv4_address));
28 }
29 
30 SocketIpStatus IpSocket::configure(const char* const ipv4_address,
31  const U16 port,
32  const U32 timeout_seconds,
33  const U32 timeout_microseconds) {
34  FW_ASSERT(timeout_microseconds < 1000000, static_cast<FwAssertArgType>(timeout_microseconds));
35  FW_ASSERT(this->isValidPort(port), static_cast<FwAssertArgType>(port));
36  FW_ASSERT(ipv4_address != nullptr);
37  // Defense-in-depth: reject inputs that would have been silently truncated by string_copy.
38  FW_ASSERT(Fw::StringUtils::string_length(ipv4_address, static_cast<FwSizeType>(SOCKET_MAX_IPV4_ADDRESS_SIZE)) <
39  static_cast<FwSizeType>(SOCKET_MAX_IPV4_ADDRESS_SIZE));
40  this->m_timeoutSeconds = timeout_seconds;
41  this->m_timeoutMicroseconds = timeout_microseconds;
42  this->m_port = port;
43  (void)Fw::StringUtils::string_copy(this->m_ipv4_address, ipv4_address,
44  static_cast<FwSizeType>(SOCKET_MAX_IPV4_ADDRESS_SIZE));
45  // Post-condition: NUL termination guaranteed by Fw::StringUtils::string_copy contract.
47  return SOCK_SUCCESS;
48 }
49 
50 bool IpSocket::isValidPort(U16 port) const {
51  return true;
52 }
53 
55 // Get the IP address from host
56 #ifdef TGT_OS_TYPE_VXWORKS
57  // No timeouts set on Vxworks
58 #else
59  // Set timeout socket option
60  struct timeval timeout;
61  timeout.tv_sec = static_cast<time_t>(this->m_timeoutSeconds);
62  timeout.tv_usec = static_cast<suseconds_t>(this->m_timeoutMicroseconds);
63  // set socket write to timeout after 1 sec
64  if (setsockopt(socketFd, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<char*>(&timeout), sizeof(timeout)) < 0) {
66  }
67 #endif
68  return SOCK_SUCCESS;
69 }
70 
72 #ifdef SO_NOSIGPIPE
73  constexpr int enable = 1;
74  if (setsockopt(socketFd, SOL_SOCKET, SO_NOSIGPIPE, &enable, sizeof(enable)) < 0) {
76  }
77 #else
78  (void)socketFd;
79 #endif
80  return SOCK_SUCCESS;
81 }
82 
83 SocketIpStatus IpSocket::addressToIp4(const char* const ipv4_address, void* const out) {
84  FW_ASSERT(ipv4_address != nullptr);
85  FW_ASSERT(out != nullptr);
86  // Pre-zero the destination so that on failure, callers cannot accidentally consume
87  // uninitialized memory. This is a defense-in-depth measure for safety-critical use.
88  (void)::memset(out, 0, sizeof(struct in_addr));
89  // Get the IP address from host
90 #ifdef TGT_OS_TYPE_VXWORKS
91  int ip = inet_addr(ipv4_address);
92  if (ip == ERROR) {
94  }
95  // from sin_addr, which has one struct
96  // member s_addr, which is unsigned int
97  *static_cast<unsigned long*>(out) = static_cast<unsigned long>(ip);
98 #else
99  // inet_pton(3) returns 1 on success, 0 if the input is not a valid IPv4 presentation
100  // string, and -1 (with errno=EAFNOSUPPORT) if the family argument is bogus. Only a
101  // strict equality check is safe — a `not` test treats -1 as success and would silently
102  // mask an EAFNOSUPPORT failure. (Power-of-Ten Rule 7: check every return value.)
103  const int ptonStatus = ::inet_pton(AF_INET, ipv4_address, out);
104  if (ptonStatus != 1) {
106  }
107 #endif
108  return SOCK_SUCCESS;
109 }
110 
111 void IpSocket::close(const SocketDescriptor& socketDescriptor) {
112  if (socketDescriptor.fd >= 0) {
113  (void)::close(socketDescriptor.fd);
114  }
115 }
116 
117 void IpSocket::shutdown(const SocketDescriptor& socketDescriptor) {
118  errno = 0;
119  int status = ::shutdown(socketDescriptor.fd, SHUT_RDWR);
120  // If shutdown fails, go straight to the hard-shutdown
121  if (status != 0) {
122  this->close(socketDescriptor);
123  }
124 }
125 
127  SocketIpStatus status = SOCK_SUCCESS;
128  errno = 0;
129  // Open a TCP socket for incoming commands, and outgoing data if not using UDP
130  status = this->openProtocol(socketDescriptor);
131  if (status != SOCK_SUCCESS) {
132  socketDescriptor.fd = -1;
133  return status;
134  }
135  return status;
136 }
137 
138 SocketIpStatus IpSocket::send(const SocketDescriptor& socketDescriptor, const U8* const data, const FwSizeType size) {
139  FW_ASSERT((size == 0) || (data != nullptr));
140  // Zero-size sends are a no-op
141  if (size == 0) {
142  return SOCK_SUCCESS;
143  }
144 
145  FwSizeType total = 0;
146  FwSignedSizeType sent = 0;
147  // Attempt to send out data and retry as necessary
148  for (FwSizeType i = 0; (i < SOCKET_MAX_ITERATIONS) && (total < size); i++) {
149  errno = 0;
150  // Send using my specific protocol
151  sent = this->sendProtocol(socketDescriptor, data + total, size - total);
152  // Error is EINTR just try again
153  if (((sent == -1) && (errno == EINTR)) || (sent == 0)) {
154  continue;
155  }
156  // A bad file descriptor, a reset, or a broken pipe (the peer closed the connection) is a disconnect
157  else if ((sent == -1) && ((errno == EBADF) || (errno == ECONNRESET) || (errno == EPIPE))) {
158  return SOCK_DISCONNECTED;
159  }
160  // Error is a send timeout (SO_SNDTIMEO) or would-block, recoverable by a caller retry
161  else if ((sent == -1) && ((errno == EAGAIN) || (errno == EWOULDBLOCK))) {
163  }
164  // Error returned, and it wasn't an interrupt, a timeout, nor a disconnect
165  else if (sent == -1) {
166  return SOCK_SEND_ERROR;
167  }
168  FW_ASSERT(sent > 0, static_cast<FwAssertArgType>(sent));
169  total += static_cast<FwSizeType>(sent);
170  }
171  // Failed to retry enough to send all data
172  if (total < size) {
174  }
175  // Ensure we sent everything
176  FW_ASSERT(total == size, static_cast<FwAssertArgType>(total), static_cast<FwAssertArgType>(size));
177  return SOCK_SUCCESS;
178 }
179 
180 SocketIpStatus IpSocket::recv(const SocketDescriptor& socketDescriptor, U8* data, FwSizeType& req_read) {
181  // TODO: Uncomment FW_ASSERT for socketDescriptor.fd once we fix TcpClientTester to not pass in uninitialized
182  // socketDescriptor
183  // FW_ASSERT(socketDescriptor.fd != -1, static_cast<FwAssertArgType>(socketDescriptor.fd));
184  FW_ASSERT(data != nullptr);
185 
186  FwSignedSizeType bytes_received_or_status; // Stores the return value from recvProtocol
187 
188  // Loop primarily for EINTR. Other conditions should lead to an earlier exit.
189  for (FwSizeType i = 0; i < SOCKET_MAX_ITERATIONS; i++) {
190  errno = 0;
191  // Pass the current value of req_read (max buffer size) to recvProtocol.
192  // recvProtocol returns bytes read or -1 on error.
193  bytes_received_or_status = this->recvProtocol(socketDescriptor, data, req_read);
194 
195  if (bytes_received_or_status > 0) {
196  // Successfully read data
197  req_read = static_cast<FwSizeType>(bytes_received_or_status);
198  return SOCK_SUCCESS;
199  } else if (bytes_received_or_status == 0) {
200  // Handle zero return based on protocol-specific behavior
201  req_read = 0;
202  return this->handleZeroReturn();
203  } else { // bytes_received_or_status == -1, an error occurred
204  if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) {
205  // Non-blocking socket would block, or SO_RCVTIMEO timeout occurred.
206  req_read = 0;
207  return SOCK_NO_DATA_AVAILABLE;
208  } else if ((errno == ECONNRESET) || (errno == EBADF)) {
209  // Connection reset or bad file descriptor.
210  req_read = 0;
211  return SOCK_DISCONNECTED; // Or a more specific error like SOCK_READ_ERROR
212  } else if (errno == EINTR) {
213  continue;
214  } else {
215  // Other socket read error.
216  req_read = 0;
217  return SOCK_READ_ERROR;
218  }
219  }
220  }
221  // If the loop completes, it means SOCKET_MAX_ITERATIONS of EINTR occurred.
222  req_read = 0;
224 }
225 
227  // For TCP (which IpSocket primarily serves as a base for, or when not overridden),
228  // a return of 0 from ::recv means the peer has performed an orderly shutdown.
229  return SOCK_DISCONNECTED;
230 }
231 
233  // Iterate over the socket options and set them
234  for (const auto& options : IP_SOCKET_OPTIONS) {
235  int status = 0;
236  if (options.type == SOCK_OPT_INT) {
237  status = setsockopt(socketFd, options.level, options.option, &options.value.intVal,
238  sizeof(options.value.intVal));
239  } else {
240  status = setsockopt(socketFd, options.level, options.option, &options.value.sizeVal,
241  sizeof(options.value.sizeVal));
242  }
243  if (status) {
245  }
246  }
247  return SOCK_SUCCESS;
248 }
249 
250 } // namespace Drv
Failed to send after configured retries.
Definition: IpSocket.hpp:42
Socket disconnected during read or send.
Definition: IpSocket.hpp:38
Interrupted status for retries.
Definition: IpSocket.hpp:36
Failed to configure socket.
Definition: IpSocket.hpp:35
PlatformSizeType FwSizeType
SocketIpStatus recv(const SocketDescriptor &fd, U8 *const data, FwSizeType &size)
receive data from the IP socket from the given buffer
Definition: IpSocket.cpp:180
Operation failed.
Definition: Os.hpp:28
SocketIpStatus setupTimeouts(int socketFd)
setup the socket timeout properties of the opened outgoing socket
Definition: IpSocket.cpp:54
virtual SocketIpStatus configure(const char *const ipv4_address, const U16 port, const U32 send_timeout_seconds, const U32 send_timeout_microseconds)
configure the ip socket with an IPv4 address and transmission timeouts
Definition: IpSocket.cpp:30
static SocketIpStatus addressToIp4(const char *const ipv4_address, void *const out)
converts a given IPv4 address in dotted-quad form "x.x.x.x" to a network-order in_addr structure...
Definition: IpSocket.cpp:83
int fd
Used for all sockets to track the communication file descriptor.
Definition: IpSocket.hpp:22
PlatformSignedSizeType FwSignedSizeType
SocketIpStatus setupNoSigPipe(int socketFd)
prevent sends on a stream socket from raising SIGPIPE on platforms without MSG_NOSIGNAL ...
Definition: IpSocket.cpp:71
virtual SocketIpStatus send(const SocketDescriptor &socketDescriptor, const U8 *const data, const FwSizeType size)
send data out the IP socket from the given buffer
Definition: IpSocket.cpp:138
Bad IP address supplied.
Definition: IpSocket.hpp:33
virtual SocketIpStatus openProtocol(SocketDescriptor &fd)=0
Protocol specific open implementation, called from open.
void shutdown(const SocketDescriptor &socketDescriptor)
shutdown the socket
Definition: IpSocket.cpp:117
virtual FwSignedSizeType sendProtocol(const SocketDescriptor &socketDescriptor, const U8 *const data, const FwSizeType size)=0
Protocol specific implementation of send. Called directly with retry from send.
U16 m_port
IP address port used.
Definition: IpSocket.hpp:273
Socket operation successful.
Definition: IpSocket.hpp:30
char * string_copy(char *destination, const char *source, FwSizeType num)
copy string with null-termination guaranteed
Definition: StringUtils.cpp:7
Failed to read socket.
Definition: IpSocket.hpp:37
SocketIpStatus setupSocketOptions(int socketFd)
setup the socket options of the input socket as defined in IpCfg.hpp
Definition: IpSocket.cpp:232
virtual bool isValidPort(U16 port) const
Check if the given port is valid for the socket.
Definition: IpSocket.cpp:50
uint8_t U8
8-bit unsigned integer
Definition: BasicTypes.h:54
static const IpSocketOptions IP_SOCKET_OPTIONS[]
Definition: IpCfg.hpp:105
virtual SocketIpStatus handleZeroReturn()
Handle zero return from recvProtocol.
Definition: IpSocket.cpp:226
char m_ipv4_address[SOCKET_MAX_IPV4_ADDRESS_SIZE]
IPv4 address (dotted-quad "x.x.x.x")
Definition: IpSocket.hpp:274
void close(const SocketDescriptor &socketDescriptor)
closes the socket
Definition: IpSocket.cpp:111
virtual FwSignedSizeType recvProtocol(const SocketDescriptor &socketDescriptor, U8 *const data, const FwSizeType size)=0
Protocol specific implementation of recv. Called directly with error handling from recv...
SocketIpStatus open(SocketDescriptor &socketDescriptor)
open the IP socket for communications
Definition: IpSocket.cpp:126
SocketIpStatus
Status enumeration for socket return values.
Definition: IpSocket.hpp:29
U32 m_timeoutMicroseconds
Definition: IpSocket.hpp:272
No data available or read operation would block.
Definition: IpSocket.hpp:45
#define FW_ASSERT(...)
Definition: Assert.hpp:14
U32 m_timeoutSeconds
Definition: IpSocket.hpp:271
FwSizeType string_length(const CHAR *source, FwSizeType buffer_size)
get the length of the source string
Definition: StringUtils.cpp:32