SolidSyslog coverage report
Current view: top level - Platform/Posix/Source - SolidSyslogPosixTcpStream.c (source / functions) Coverage Total Hit
Test: SolidSyslog Lines: 100.0 % 185 185
Test Date: 2026-11-12 23:14:35 Functions: 100.0 % 31 31
Branches: 99.1 % 106 105

             Branch data     Line data    Source code
       1                 :             : /* SPDX-FileCopyrightText: Copyright 2026 Cozens Software Solutions Limited
       2                 :             :  * SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 OR LicenseRef-PolyForm-Internal-Use-1.0.0 OR LicenseRef-COSOSO-Commercial
       3                 :             :  */
       4                 :             : 
       5                 :             : #include "SolidSyslogPosixTcpStream.h"
       6                 :             : 
       7                 :             : #include <errno.h>
       8                 :             : #include <fcntl.h>
       9                 :             : #include <netinet/in.h>
      10                 :             : #include <netinet/tcp.h>
      11                 :             : #include <stdbool.h>
      12                 :             : #include <stddef.h>
      13                 :             : #include <stdint.h>
      14                 :             : #include <sys/select.h>
      15                 :             : #include <sys/socket.h>
      16                 :             : #include <sys/time.h>
      17                 :             : #include <sys/types.h>
      18                 :             : #include <unistd.h>
      19                 :             : 
      20                 :             : #include "SolidSyslogError.h"
      21                 :             : #include "SolidSyslogErrorCategory.h"
      22                 :             : #include "SolidSyslogNullStream.h"
      23                 :             : #include "SolidSyslogPosixAddressPrivate.h"
      24                 :             : #include "SolidSyslogPosixTcpStreamErrors.h"
      25                 :             : #include "SolidSyslogPosixTcpStreamPrivate.h"
      26                 :             : #include "SolidSyslogStream.h"
      27                 :             : #include "SolidSyslogStreamCategories.h"
      28                 :             : #include "SolidSyslogTunables.h"
      29                 :             : 
      30                 :             : /* Linux rejects a keepalive option outside these ranges with EINVAL, and the
      31                 :             :  * setsockopt results are not checked, so an out-of-range tunable would leave the
      32                 :             :  * kernel default in place while TCP_USER_TIMEOUT is derived from the tunable. */
      33                 :             : #if SOLIDSYSLOG_TCP_KEEPALIVE_IDLE_SECONDS > 32767U
      34                 :             : #error "SOLIDSYSLOG_TCP_KEEPALIVE_IDLE_SECONDS must be <= 32767 on Linux"
      35                 :             : #endif
      36                 :             : 
      37                 :             : #if SOLIDSYSLOG_TCP_KEEPALIVE_INTERVAL_SECONDS > 32767U
      38                 :             : #error "SOLIDSYSLOG_TCP_KEEPALIVE_INTERVAL_SECONDS must be <= 32767 on Linux"
      39                 :             : #endif
      40                 :             : 
      41                 :             : #if SOLIDSYSLOG_TCP_KEEPALIVE_PROBE_COUNT > 127U
      42                 :             : #error "SOLIDSYSLOG_TCP_KEEPALIVE_PROBE_COUNT must be <= 127 on Linux"
      43                 :             : #endif
      44                 :             : 
      45                 :             : const struct SolidSyslogErrorSource SolidSyslogPosixTcpStreamErrorSource = {
      46                 :             :     "PosixTcpStream",
      47                 :             :     SolidSyslogTcpStreamErrors_Name
      48                 :             : };
      49                 :             : 
      50                 :             : struct SolidSyslogAddress;
      51                 :             : 
      52                 :             : enum
      53                 :             : {
      54                 :             :     INVALID_FD = -1,
      55                 :             :     MILLISECONDS_PER_SECOND = 1000
      56                 :             : };
      57                 :             : 
      58                 :             : static uint32_t PosixTcpStream_NullConnectTimeoutGetter(void* context);
      59                 :             : 
      60                 :             : static bool PosixTcpStream_Open(struct SolidSyslogStream* base, const struct SolidSyslogAddress* addr);
      61                 :             : static bool PosixTcpStream_TakeSocketAndConnect(struct SolidSyslogPosixTcpStream* self, const struct sockaddr_in* sin);
      62                 :             : static bool PosixTcpStream_Send(struct SolidSyslogStream* base, const void* buffer, size_t size);
      63                 :             : static SolidSyslogSsize PosixTcpStream_Read(struct SolidSyslogStream* base, void* buffer, size_t size);
      64                 :             : static void PosixTcpStream_Close(struct SolidSyslogStream* base);
      65                 :             : static uint32_t PosixTcpStream_Version(struct SolidSyslogStream* base);
      66                 :             : 
      67                 :             : static inline struct SolidSyslogPosixTcpStream* PosixTcpStream_SelfFromBase(struct SolidSyslogStream* base);
      68                 :             : static inline bool PosixTcpStream_ConfigProvidesGetter(const struct SolidSyslogPosixTcpStreamConfig* config);
      69                 :             : 
      70                 :             : static void PosixTcpStream_OpenAndConfigureSocket(struct SolidSyslogPosixTcpStream* self);
      71                 :             : static bool PosixTcpStream_ConfigureSocket(struct SolidSyslogPosixTcpStream* self);
      72                 :             : static void PosixTcpStream_EnableTcpNoDelay(int fd);
      73                 :             : static void PosixTcpStream_EnableKeepalive(int fd);
      74                 :             : static bool PosixTcpStream_SetNonBlocking(struct SolidSyslogPosixTcpStream* self);
      75                 :             : static inline bool PosixTcpStream_IsFileDescriptorValid(int fd);
      76                 :             : static bool PosixTcpStream_ConnectOrCloseOnFailure(
      77                 :             :     struct SolidSyslogPosixTcpStream* self,
      78                 :             :     const struct sockaddr_in* sin
      79                 :             : );
      80                 :             : static bool PosixTcpStream_Connect(
      81                 :             :     struct SolidSyslogPosixTcpStream* self,
      82                 :             :     const struct sockaddr_in* sin,
      83                 :             :     long timeoutMicros
      84                 :             : );
      85                 :             : static bool PosixTcpStream_WaitForConnectCompletion(struct SolidSyslogPosixTcpStream* self, long timeoutMicros);
      86                 :             : static bool PosixTcpStream_ReadDeferredConnectError(struct SolidSyslogPosixTcpStream* self);
      87                 :             : static bool PosixTcpStream_ReadSocketError(int fd, int* code);
      88                 :             : static void PosixTcpStream_ReportConnectFailure(
      89                 :             :     struct SolidSyslogPosixTcpStream* self,
      90                 :             :     enum SolidSyslogSeverity severity,
      91                 :             :     enum SolidSyslogTcpStreamErrors detail
      92                 :             : );
      93                 :             : static void PosixTcpStream_ReportConnectFailureWithErrno(
      94                 :             :     struct SolidSyslogPosixTcpStream* self,
      95                 :             :     enum SolidSyslogSeverity severity,
      96                 :             :     enum SolidSyslogTcpStreamErrors detail,
      97                 :             :     int nativeErrno
      98                 :             : );
      99                 :             : static void PosixTcpStream_ReportUnfinishedWait(
     100                 :             :     struct SolidSyslogPosixTcpStream* self,
     101                 :             :     int selectResult,
     102                 :             :     int selectErrno
     103                 :             : );
     104                 :             : static inline bool PosixTcpStream_IsRemoteConnectError(int connectErrno);
     105                 :             : static inline bool PosixTcpStream_WaitTimedOut(int selectResult);
     106                 :             : static long PosixTcpStream_ResolveConnectTimeoutMicros(struct SolidSyslogPosixTcpStream* self);
     107                 :             : static bool PosixTcpStream_PeerIsStillThere(struct SolidSyslogPosixTcpStream* self);
     108                 :             : static bool PosixTcpStream_WroteAllBytes(ssize_t sent, size_t expected);
     109                 :             : static inline bool PosixTcpStream_WouldBlock(int err);
     110                 :             : 
     111                 :         167 : void SolidSyslogPosixTcpStream_Initialise(
     112                 :             :     struct SolidSyslogStream* base,
     113                 :             :     const struct SolidSyslogPosixTcpStreamConfig* config
     114                 :             : )
     115                 :             : {
     116                 :             :     static const struct SolidSyslogPosixTcpStream DefaultPosixTcpStream = {
     117                 :             :         .Base =
     118                 :             :             {.Open = PosixTcpStream_Open,
     119                 :             :              .Send = PosixTcpStream_Send,
     120                 :             :              .Read = PosixTcpStream_Read,
     121                 :             :              .Close = PosixTcpStream_Close,
     122                 :             :              .Version = PosixTcpStream_Version},
     123                 :             :         .Config = {.GetConnectTimeoutMs = PosixTcpStream_NullConnectTimeoutGetter, .ConnectTimeoutContext = NULL},
     124                 :             :         .Fd = INVALID_FD,
     125                 :             :     };
     126                 :             : 
     127                 :         167 :     struct SolidSyslogPosixTcpStream* self = PosixTcpStream_SelfFromBase(base);
     128                 :         167 :     *self = DefaultPosixTcpStream;
     129         [ +  + ]:         167 :     if (PosixTcpStream_ConfigProvidesGetter(config) == true)
     130                 :             :     {
     131                 :           4 :         self->Config = *config;
     132                 :             :     }
     133                 :         167 : }
     134                 :             : 
     135                 :         167 : static inline bool PosixTcpStream_ConfigProvidesGetter(const struct SolidSyslogPosixTcpStreamConfig* config)
     136                 :             : {
     137   [ +  +  +  + ]:         167 :     return (config != NULL) && (config->GetConnectTimeoutMs != NULL);
     138                 :             : }
     139                 :             : 
     140                 :             : /* Null Object substituted when the integrator does not install a getter -
     141                 :             :  * returns the compile-time tunable so the bounded-wait path has a single
     142                 :             :  * code path regardless of whether the integrator wired runtime tuning. */
     143                 :         134 : static uint32_t PosixTcpStream_NullConnectTimeoutGetter(void* context)
     144                 :             : {
     145                 :             :     (void) context;
     146                 :         134 :     return (uint32_t) SOLIDSYSLOG_TCP_CONNECT_TIMEOUT_MS;
     147                 :             : }
     148                 :             : 
     149                 :         699 : static inline struct SolidSyslogPosixTcpStream* PosixTcpStream_SelfFromBase(struct SolidSyslogStream* base)
     150                 :             : {
     151                 :         699 :     return (struct SolidSyslogPosixTcpStream*) base;
     152                 :             : }
     153                 :             : 
     154                 :         167 : void SolidSyslogPosixTcpStream_Cleanup(struct SolidSyslogStream* base)
     155                 :             : {
     156                 :         167 :     struct SolidSyslogPosixTcpStream* self = PosixTcpStream_SelfFromBase(base);
     157         [ +  + ]:         167 :     if (PosixTcpStream_IsFileDescriptorValid(self->Fd))
     158                 :             :     {
     159                 :          43 :         close(self->Fd);
     160                 :          43 :         self->Fd = INVALID_FD;
     161                 :             :     }
     162                 :             :     /* Overwrite the abstract base with the shared NullStream vtable so
     163                 :             :      * use-after-destroy is a safe no-op rather than a NULL-fn-pointer crash. */
     164                 :         167 :     *base = *SolidSyslogNullStream_Get();
     165                 :         167 : }
     166                 :             : 
     167                 :         679 : static inline bool PosixTcpStream_IsFileDescriptorValid(int fd)
     168                 :             : {
     169                 :         679 :     return (fd >= 0);
     170                 :             : }
     171                 :             : 
     172                 :         146 : static bool PosixTcpStream_Open(struct SolidSyslogStream* base, const struct SolidSyslogAddress* addr)
     173                 :             : {
     174                 :         146 :     struct SolidSyslogPosixTcpStream* self = PosixTcpStream_SelfFromBase(base);
     175                 :         146 :     bool connected = false;
     176         [ +  + ]:         146 :     if (PosixTcpStream_IsFileDescriptorValid(self->Fd))
     177                 :             :     {
     178                 :             :         /* Refused by contract, not reconnected: what is held stays as it is. */
     179                 :           2 :         PosixTcpStream_Report(
     180                 :             :             SOLIDSYSLOG_BAD_ARGUMENT_SEVERITY,
     181                 :             :             SOLIDSYSLOG_CAT_BAD_ARGUMENT,
     182                 :             :             SOLIDSYSLOG_TCP_STREAM_ERROR_ALREADY_OPEN
     183                 :             :         );
     184                 :             :     }
     185                 :             :     else
     186                 :             :     {
     187                 :         144 :         connected = PosixTcpStream_TakeSocketAndConnect(self, SolidSyslogPosixAddress_AsConstSockaddrIn(addr));
     188                 :             :     }
     189                 :         146 :     return connected;
     190                 :             : }
     191                 :             : 
     192                 :         144 : static bool PosixTcpStream_TakeSocketAndConnect(struct SolidSyslogPosixTcpStream* self, const struct sockaddr_in* sin)
     193                 :             : {
     194                 :         144 :     bool connected = false;
     195                 :         144 :     PosixTcpStream_OpenAndConfigureSocket(self);
     196         [ +  + ]:         144 :     if (PosixTcpStream_IsFileDescriptorValid(self->Fd))
     197                 :             :     {
     198                 :         138 :         connected = PosixTcpStream_ConnectOrCloseOnFailure(self, sin);
     199                 :             :     }
     200         [ +  + ]:         144 :     if (connected)
     201                 :             :     {
     202                 :         109 :         SolidSyslogStreamOpenHealth_Opened(&self->OpenHealth);
     203                 :             :     }
     204                 :         144 :     return connected;
     205                 :             : }
     206                 :             : 
     207                 :             : /* Every connect failure is one category with the detail naming which step
     208                 :             :  * failed, so a portable handler reacts to "no connection" without knowing
     209                 :             :  * POSIX. Each failing step reports its own, because each is the only place
     210                 :             :  * that knows which one it was, and the only place the errno it left can be
     211                 :             :  * read. Reported once per run of the same detail, as the Open contract
     212                 :             :  * requires: the sender retries every service pass. */
     213                 :          10 : static void PosixTcpStream_ReportConnectFailure(
     214                 :             :     struct SolidSyslogPosixTcpStream* self,
     215                 :             :     enum SolidSyslogSeverity severity,
     216                 :             :     enum SolidSyslogTcpStreamErrors detail
     217                 :             : )
     218                 :             : {
     219                 :          10 :     SolidSyslogStreamOpenHealth_ReportFailure(
     220                 :             :         &self->OpenHealth,
     221                 :             :         &SolidSyslogPosixTcpStreamErrorSource,
     222                 :             :         severity,
     223                 :             :         SOLIDSYSLOG_CAT_STREAM_CONNECT_FAILED,
     224                 :             :         (int32_t) detail
     225                 :             :     );
     226                 :          10 : }
     227                 :             : 
     228                 :             : /* The fault, with the errno behind it when the call left one. */
     229                 :          31 : static void PosixTcpStream_ReportConnectFailureWithErrno(
     230                 :             :     struct SolidSyslogPosixTcpStream* self,
     231                 :             :     enum SolidSyslogSeverity severity,
     232                 :             :     enum SolidSyslogTcpStreamErrors detail,
     233                 :             :     int nativeErrno
     234                 :             : )
     235                 :             : {
     236         [ +  + ]:          31 :     if (nativeErrno != 0)
     237                 :             :     {
     238                 :          25 :         SolidSyslogStreamOpenHealth_ReportFailureWithNativeCode(
     239                 :             :             &self->OpenHealth,
     240                 :             :             &SolidSyslogPosixTcpStreamErrorSource,
     241                 :             :             severity,
     242                 :             :             SOLIDSYSLOG_CAT_STREAM_CONNECT_FAILED,
     243                 :             :             (int32_t) detail,
     244                 :             :             (int32_t) nativeErrno
     245                 :             :         );
     246                 :             :     }
     247                 :             :     else
     248                 :             :     {
     249                 :           6 :         PosixTcpStream_ReportConnectFailure(self, severity, detail);
     250                 :             :     }
     251                 :          31 : }
     252                 :             : 
     253                 :             : /* Non-blocking from the start: connect() reports EINPROGRESS, the wait is
     254                 :             :  * bounded by select(), and PosixTcpStream_Send/PosixTcpStream_Read never block the service thread on a
     255                 :             :  * wedged peer or a full kernel send buffer. */
     256                 :         144 : static void PosixTcpStream_OpenAndConfigureSocket(struct SolidSyslogPosixTcpStream* self)
     257                 :             : {
     258                 :         144 :     self->Fd = socket(AF_INET, SOCK_STREAM, 0);
     259                 :             :     /* Capture errno immediately after socket (MISRA 22.10). */
     260         [ +  + ]:         144 :     int socketErrno = (self->Fd < 0) ? errno : 0;
     261         [ +  + ]:         144 :     if (!PosixTcpStream_IsFileDescriptorValid(self->Fd))
     262                 :             :     {
     263                 :           3 :         PosixTcpStream_ReportConnectFailureWithErrno(
     264                 :             :             self,
     265                 :             :             SOLIDSYSLOG_STREAM_CONNECT_LOCAL_SEVERITY,
     266                 :             :             SOLIDSYSLOG_TCP_STREAM_ERROR_ENDPOINT_UNAVAILABLE,
     267                 :             :             socketErrno
     268                 :             :         );
     269                 :             :     }
     270         [ +  + ]:         141 :     else if (!PosixTcpStream_ConfigureSocket(self))
     271                 :             :     {
     272                 :           3 :         close(self->Fd);
     273                 :           3 :         self->Fd = INVALID_FD;
     274                 :             :     }
     275                 :             :     else
     276                 :             :     {
     277                 :             :         /* configured - ready to connect */
     278                 :             :     }
     279                 :         144 : }
     280                 :             : 
     281                 :         141 : static bool PosixTcpStream_ConfigureSocket(struct SolidSyslogPosixTcpStream* self)
     282                 :             : {
     283                 :         141 :     PosixTcpStream_EnableTcpNoDelay(self->Fd);
     284                 :         141 :     PosixTcpStream_EnableKeepalive(self->Fd);
     285                 :         141 :     return PosixTcpStream_SetNonBlocking(self);
     286                 :             : }
     287                 :             : 
     288                 :         141 : static void PosixTcpStream_EnableTcpNoDelay(int fd)
     289                 :             : {
     290                 :         141 :     int enable = 1;
     291                 :         141 :     setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &enable, sizeof(enable));
     292                 :         141 : }
     293                 :             : 
     294                 :             : /* Enable kernel TCP keepalive so a dead peer is surfaced as ETIMEDOUT during
     295                 :             :  * idle periods, not on the next PosixTcpStream_Send. TCP_USER_TIMEOUT bounds a
     296                 :             :  * write the peer never acknowledges, where keepalive does not probe. On Linux a
     297                 :             :  * user timeout also ends keepalive, overriding the probe count: the connection
     298                 :             :  * drops at the first unanswered probe once the user timeout has elapsed since
     299                 :             :  * anything was received. Setting it to the keepalive window, the idle period
     300                 :             :  * plus the interval across every probe, keeps the probe count meaningful and
     301                 :             :  * bounds an unacknowledged write by the same window. Linux is the POSIX
     302                 :             :  * target - TCP_KEEP* and TCP_USER_TIMEOUT are all available there; other POSIX
     303                 :             :  * targets are out of scope until we actually port to one. */
     304                 :         141 : static void PosixTcpStream_EnableKeepalive(int fd)
     305                 :             : {
     306                 :         141 :     int enable = 1;
     307                 :         141 :     int idle = (int) SOLIDSYSLOG_TCP_KEEPALIVE_IDLE_SECONDS;
     308                 :         141 :     int interval = (int) SOLIDSYSLOG_TCP_KEEPALIVE_INTERVAL_SECONDS;
     309                 :         141 :     int count = (int) SOLIDSYSLOG_TCP_KEEPALIVE_PROBE_COUNT;
     310                 :         141 :     int userTimeout = (idle + (interval * count)) * MILLISECONDS_PER_SECOND;
     311                 :             : 
     312                 :         141 :     setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &enable, sizeof(enable));
     313                 :         141 :     setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof(idle));
     314                 :         141 :     setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &interval, sizeof(interval));
     315                 :         141 :     setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &count, sizeof(count));
     316                 :         141 :     setsockopt(fd, IPPROTO_TCP, TCP_USER_TIMEOUT, &userTimeout, sizeof(userTimeout));
     317                 :         141 : }
     318                 :             : 
     319                 :             : /* A socket the kernel will not make non-blocking is of no use: the bounded
     320                 :             :  * connect, and Send and Read never blocking the service thread, all rest on
     321                 :             :  * it. The attempt is given up here, and this is the step that reports it. */
     322                 :         141 : static bool PosixTcpStream_SetNonBlocking(struct SolidSyslogPosixTcpStream* self)
     323                 :             : {
     324                 :         141 :     bool nonBlocking = false;
     325                 :         141 :     int fd = self->Fd;
     326                 :         141 :     int flags = fcntl(fd, F_GETFL, 0);
     327                 :             :     /* Capture errno immediately after each fcntl (MISRA 22.10). */
     328         [ +  + ]:         141 :     int fcntlErrno = (flags < 0) ? errno : 0;
     329         [ +  + ]:         141 :     if (flags >= 0)
     330                 :             :     {
     331                 :         140 :         int rc = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
     332         [ +  + ]:         140 :         fcntlErrno = (rc == -1) ? errno : 0;
     333                 :         140 :         nonBlocking = (rc != -1);
     334                 :             :     }
     335         [ +  + ]:         141 :     if (!nonBlocking)
     336                 :             :     {
     337                 :           3 :         PosixTcpStream_ReportConnectFailureWithErrno(
     338                 :             :             self,
     339                 :             :             SOLIDSYSLOG_STREAM_CONNECT_LOCAL_SEVERITY,
     340                 :             :             SOLIDSYSLOG_TCP_STREAM_ERROR_ENDPOINT_UNAVAILABLE,
     341                 :             :             fcntlErrno
     342                 :             :         );
     343                 :             :     }
     344                 :         141 :     return nonBlocking;
     345                 :             : }
     346                 :             : 
     347                 :         138 : static bool PosixTcpStream_ConnectOrCloseOnFailure(
     348                 :             :     struct SolidSyslogPosixTcpStream* self,
     349                 :             :     const struct sockaddr_in* sin
     350                 :             : )
     351                 :             : {
     352                 :         138 :     long timeoutMicros = PosixTcpStream_ResolveConnectTimeoutMicros(self);
     353                 :         138 :     bool connected = PosixTcpStream_Connect(self, sin, timeoutMicros);
     354         [ +  + ]:         138 :     if (!connected)
     355                 :             :     {
     356                 :          29 :         close(self->Fd);
     357                 :          29 :         self->Fd = INVALID_FD;
     358                 :             :     }
     359                 :         138 :     return connected;
     360                 :             : }
     361                 :             : 
     362                 :             : /* Bridges the integrator-installed getter (or the Null Object substituted in
     363                 :             :  * Initialise) to the bounded select() deadline. Invoked on every connect
     364                 :             :  * attempt so a runtime-tunable value takes effect on the next reconnect. */
     365                 :         138 : static long PosixTcpStream_ResolveConnectTimeoutMicros(struct SolidSyslogPosixTcpStream* self)
     366                 :             : {
     367                 :         138 :     uint32_t ms = self->Config.GetConnectTimeoutMs(self->Config.ConnectTimeoutContext);
     368                 :         138 :     uint32_t boundedMs = (ms > SOLIDSYSLOG_TCP_CONNECT_TIMEOUT_MS_MAX) ? SOLIDSYSLOG_TCP_CONNECT_TIMEOUT_MS_MAX : ms;
     369                 :         138 :     return (long) boundedMs * 1000L;
     370                 :             : }
     371                 :             : 
     372                 :             : /* Non-blocking connect with bounded wait. connect() returns immediately:
     373                 :             :  *   0           - connected (loopback success path).
     374                 :             :  *   -1 EINPROGRESS - connect started; wait via select() up to
     375                 :             :  *                    CONNECT_TIMEOUT_MICROSECONDS, then read SO_ERROR to
     376                 :             :  *                    distinguish completed-success from deferred-failure.
     377                 :             :  *   -1 other    - immediate fail-fast (refused, unreachable, etc.). */
     378                 :         138 : static bool PosixTcpStream_Connect(
     379                 :             :     struct SolidSyslogPosixTcpStream* self,
     380                 :             :     const struct sockaddr_in* sin,
     381                 :             :     long timeoutMicros
     382                 :             : )
     383                 :             : {
     384                 :         138 :     bool connected = false;
     385                 :         138 :     int rc = connect(self->Fd, (const struct sockaddr*) sin, sizeof(*sin));
     386                 :             :     /* Capture errno immediately after connect so the EINPROGRESS test
     387                 :             :      * below satisfies MISRA 22.10 - no intervening C-library calls
     388                 :             :      * between the errno-setting function and the read. */
     389         [ +  + ]:         138 :     int connectErrno = (rc < 0) ? errno : 0;
     390                 :             : 
     391         [ +  + ]:         138 :     if (rc == 0)
     392                 :             :     {
     393                 :         100 :         connected = true;
     394                 :             :     }
     395         [ +  + ]:          38 :     else if (connectErrno == EINPROGRESS)
     396                 :             :     {
     397   [ +  +  +  + ]:          34 :         connected = PosixTcpStream_WaitForConnectCompletion(self, timeoutMicros) &&
     398                 :          13 :                     PosixTcpStream_ReadDeferredConnectError(self);
     399                 :             :     }
     400         [ +  + ]:          17 :     else if (PosixTcpStream_IsRemoteConnectError(connectErrno))
     401                 :             :     {
     402                 :           8 :         PosixTcpStream_ReportConnectFailureWithErrno(
     403                 :             :             self,
     404                 :             :             SOLIDSYSLOG_STREAM_CONNECT_REMOTE_SEVERITY,
     405                 :             :             SOLIDSYSLOG_TCP_STREAM_ERROR_CONNECT_REFUSED,
     406                 :             :             connectErrno
     407                 :             :         );
     408                 :             :     }
     409                 :             :     else
     410                 :             :     {
     411                 :           9 :         PosixTcpStream_ReportConnectFailureWithErrno(
     412                 :             :             self,
     413                 :             :             SOLIDSYSLOG_STREAM_CONNECT_LOCAL_SEVERITY,
     414                 :             :             SOLIDSYSLOG_TCP_STREAM_ERROR_CONNECT_NOT_STARTED,
     415                 :             :             connectErrno
     416                 :             :         );
     417                 :             :     }
     418                 :         138 :     return connected;
     419                 :             : }
     420                 :             : 
     421                 :             : /* Remote means something was transmitted and the destination or the network
     422                 :             :  * answered, or failed to: a reset came back, or a sent SYN drew nothing. Every
     423                 :             :  * other immediate failure is local - routing rejected the call, or the stack
     424                 :             :  * would not accept the socket - and nothing left this device, which is what
     425                 :             :  * CONNECT_NOT_STARTED says. An unreachable report is local here because the
     426                 :             :  * routing lookup failed before anything was sent; one that arrives after the
     427                 :             :  * SYN is out reaches us through SO_ERROR instead, on the remote path. */
     428                 :          17 : static inline bool PosixTcpStream_IsRemoteConnectError(int connectErrno)
     429                 :             : {
     430   [ +  +  +  + ]:          17 :     return (connectErrno == ECONNREFUSED) || (connectErrno == ETIMEDOUT);
     431                 :             : }
     432                 :             : 
     433                 :          21 : static bool PosixTcpStream_WaitForConnectCompletion(struct SolidSyslogPosixTcpStream* self, long timeoutMicros)
     434                 :             : {
     435                 :          21 :     int fd = self->Fd;
     436                 :             :     fd_set writeSet;
     437         [ +  + ]:         357 :     FD_ZERO(&writeSet);
     438                 :          21 :     FD_SET(fd, &writeSet);
     439                 :             : 
     440                 :             :     fd_set errorSet;
     441         [ +  + ]:         357 :     FD_ZERO(&errorSet);
     442                 :          21 :     FD_SET(fd, &errorSet);
     443                 :             : 
     444                 :          21 :     struct timeval timeout = {.tv_sec = timeoutMicros / 1000000L, .tv_usec = timeoutMicros % 1000000L};
     445                 :             : 
     446                 :          21 :     int rc = select(fd + 1, NULL, &writeSet, &errorSet, &timeout);
     447                 :             :     /* Capture errno immediately after select (MISRA 22.10). */
     448         [ +  + ]:          21 :     int selectErrno = (rc < 0) ? errno : 0;
     449   [ +  +  +  +  :          21 :     bool ready = (rc > 0) && FD_ISSET(fd, &writeSet) && !FD_ISSET(fd, &errorSet);
                   +  + ]
     450         [ +  + ]:          21 :     if (!ready)
     451                 :             :     {
     452                 :           8 :         PosixTcpStream_ReportUnfinishedWait(self, rc, selectErrno);
     453                 :             :     }
     454                 :          21 :     return ready;
     455                 :             : }
     456                 :             : 
     457                 :             : /* The budget expiring is nothing to report a code for. A select that failed
     458                 :             :  * left its errno. A socket select answered for, flagged in the exception set,
     459                 :             :  * holds the failure in SO_ERROR. */
     460                 :             : // NOLINTBEGIN(bugprone-easily-swappable-parameters) -- a select result and the errno it left; distinct semantics
     461                 :           8 : static void PosixTcpStream_ReportUnfinishedWait(
     462                 :             :     struct SolidSyslogPosixTcpStream* self,
     463                 :             :     int selectResult,
     464                 :             :     int selectErrno
     465                 :             : )
     466                 :             : {
     467         [ +  + ]:           8 :     if (PosixTcpStream_WaitTimedOut(selectResult))
     468                 :             :     {
     469                 :           4 :         PosixTcpStream_ReportConnectFailure(
     470                 :             :             self,
     471                 :             :             SOLIDSYSLOG_STREAM_CONNECT_REMOTE_SEVERITY,
     472                 :             :             SOLIDSYSLOG_TCP_STREAM_ERROR_CONNECT_TIMED_OUT
     473                 :             :         );
     474                 :             :     }
     475                 :             :     else
     476                 :             :     {
     477                 :           4 :         int nativeErrno = selectErrno;
     478         [ +  + ]:           4 :         if (selectResult > 0)
     479                 :             :         {
     480                 :           3 :             (void) PosixTcpStream_ReadSocketError(self->Fd, &nativeErrno);
     481                 :             :         }
     482                 :           4 :         PosixTcpStream_ReportConnectFailureWithErrno(
     483                 :             :             self,
     484                 :             :             SOLIDSYSLOG_STREAM_CONNECT_REMOTE_SEVERITY,
     485                 :             :             SOLIDSYSLOG_TCP_STREAM_ERROR_CONNECT_REFUSED,
     486                 :             :             nativeErrno
     487                 :             :         );
     488                 :             :     }
     489                 :           8 : }
     490                 :             : 
     491                 :             : // NOLINTEND(bugprone-easily-swappable-parameters)
     492                 :             : 
     493                 :             : /* select() returning zero is the budget expiring with nothing to report. Any
     494                 :             :  * other unready outcome means the destination answered, just not with a
     495                 :             :  * connection. */
     496                 :           8 : static inline bool PosixTcpStream_WaitTimedOut(int selectResult)
     497                 :             : {
     498                 :           8 :     return selectResult == 0;
     499                 :             : }
     500                 :             : 
     501                 :          13 : static bool PosixTcpStream_ReadDeferredConnectError(struct SolidSyslogPosixTcpStream* self)
     502                 :             : {
     503                 :          13 :     int code = 0;
     504                 :          13 :     bool asked = PosixTcpStream_ReadSocketError(self->Fd, &code);
     505   [ +  +  +  + ]:          13 :     bool connected = asked && (code == 0);
     506         [ +  + ]:          13 :     if (!connected)
     507                 :             :     {
     508                 :           4 :         PosixTcpStream_ReportConnectFailureWithErrno(
     509                 :             :             self,
     510                 :             :             SOLIDSYSLOG_STREAM_CONNECT_REMOTE_SEVERITY,
     511                 :             :             SOLIDSYSLOG_TCP_STREAM_ERROR_CONNECT_REFUSED,
     512                 :             :             code
     513                 :             :         );
     514                 :             :     }
     515                 :          13 :     return connected;
     516                 :             : }
     517                 :             : 
     518                 :             : /* The error the socket holds, or, when it cannot be asked, the lookup's own:
     519                 :             :  * true when the socket answered. */
     520                 :          16 : static bool PosixTcpStream_ReadSocketError(int fd, int* code)
     521                 :             : {
     522                 :          16 :     int err = 0;
     523                 :          16 :     socklen_t errlen = (socklen_t) sizeof(err);
     524                 :          16 :     int rc = getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen);
     525                 :             :     /* Capture errno immediately after getsockopt (MISRA 22.10). */
     526         [ +  + ]:          16 :     int lookupErrno = (rc != 0) ? errno : 0;
     527         [ +  + ]:          16 :     *code = (rc == 0) ? err : lookupErrno;
     528                 :          16 :     return rc == 0;
     529                 :             : }
     530                 :             : 
     531                 :         131 : static bool PosixTcpStream_Send(struct SolidSyslogStream* base, const void* buffer, size_t size)
     532                 :             : {
     533                 :         131 :     struct SolidSyslogPosixTcpStream* self = PosixTcpStream_SelfFromBase(base);
     534                 :         131 :     bool ok = PosixTcpStream_PeerIsStillThere(self);
     535                 :             : 
     536         [ +  + ]:         131 :     if (ok)
     537                 :             :     {
     538                 :         129 :         ssize_t sent = send(self->Fd, buffer, size, MSG_NOSIGNAL);
     539                 :         129 :         ok = PosixTcpStream_WroteAllBytes(sent, size);
     540                 :             :     }
     541         [ +  + ]:         131 :     if (!ok)
     542                 :             :     {
     543                 :          19 :         PosixTcpStream_Close(base);
     544                 :             :     }
     545                 :         131 :     return ok;
     546                 :             : }
     547                 :             : 
     548                 :             : /* A peer that has closed its end leaves the socket writable, so send takes the
     549                 :             :  * record, and only the peer's reset - a round trip later - says it went
     550                 :             :  * nowhere. By then Send has returned true and the record has left the caller's
     551                 :             :  * hands. A FIN that has arrived reads as end-of-stream, so ask first: a
     552                 :             :  * half-closed connection fails the send and store-and-forward replays the
     553                 :             :  * record instead of losing it. Bytes the peer sent that nothing has read stand
     554                 :             :  * in front of its FIN, and the peek sees those instead. They are left for Read
     555                 :             :  * rather than discarded: a stream layered over this one may be mid-handshake,
     556                 :             :  * with the peer's reply queued here. A syslog collector sends nothing back, so
     557                 :             :  * the queue is empty when the check runs. */
     558                 :         131 : static bool PosixTcpStream_PeerIsStillThere(struct SolidSyslogPosixTcpStream* self)
     559                 :             : {
     560                 :         131 :     char discard = 0;
     561                 :         131 :     ssize_t peeked = recv(self->Fd, &discard, sizeof(discard), MSG_PEEK);
     562                 :             :     /* Captured immediately after recv so the test below satisfies MISRA 22.10 -
     563                 :             :      * no intervening library call between the errno-setting function and the
     564                 :             :      * read. */
     565         [ +  + ]:         131 :     int peekErrno = (peeked < 0) ? errno : 0;
     566   [ +  +  +  +  :         131 :     return (peeked > 0) || ((peeked < 0) && PosixTcpStream_WouldBlock(peekErrno));
                   +  + ]
     567                 :             : }
     568                 :             : 
     569                 :             : /* Non-blocking single-call contract: short write or any error means the
     570                 :             :  * connection is gone; the caller closes and reconnects on the next attempt. */
     571                 :         129 : static bool PosixTcpStream_WroteAllBytes(ssize_t sent, size_t expected)
     572                 :             : {
     573   [ +  +  +  + ]:         129 :     return (sent >= 0) && ((size_t) sent == expected);
     574                 :             : }
     575                 :             : 
     576                 :          10 : static SolidSyslogSsize PosixTcpStream_Read(struct SolidSyslogStream* base, void* buffer, size_t size)
     577                 :             : {
     578                 :          10 :     struct SolidSyslogPosixTcpStream* self = PosixTcpStream_SelfFromBase(base);
     579                 :          10 :     ssize_t n = recv(self->Fd, buffer, size, 0);
     580                 :             :     /* Capture errno immediately after recv so the WouldBlock test below
     581                 :             :      * satisfies MISRA 22.10 - passing the captured value into the helper
     582                 :             :      * keeps the predicate pure and decouples it from errno's lifetime. */
     583         [ +  + ]:          10 :     int recvErrno = (n < 0) ? errno : 0;
     584                 :          10 :     SolidSyslogSsize result = -1;
     585                 :             : 
     586         [ +  + ]:          10 :     if (n > 0)
     587                 :             :     {
     588                 :           1 :         result = (SolidSyslogSsize) n;
     589                 :             :     }
     590   [ +  +  +  + ]:           9 :     else if ((n < 0) && PosixTcpStream_WouldBlock(recvErrno))
     591                 :             :     {
     592                 :           7 :         result = 0;
     593                 :             :     }
     594                 :             :     else
     595                 :             :     {
     596                 :           2 :         PosixTcpStream_Close(base);
     597                 :             :     }
     598                 :          10 :     return result;
     599                 :             : }
     600                 :             : 
     601                 :         137 : static inline bool PosixTcpStream_WouldBlock(int err)
     602                 :             : {
     603   [ +  +  -  + ]:         137 :     return (err == EAGAIN) || (err == EWOULDBLOCK);
     604                 :             : }
     605                 :             : 
     606                 :          78 : static void PosixTcpStream_Close(struct SolidSyslogStream* base)
     607                 :             : {
     608                 :          78 :     struct SolidSyslogPosixTcpStream* self = PosixTcpStream_SelfFromBase(base);
     609         [ +  + ]:          78 :     if (PosixTcpStream_IsFileDescriptorValid(self->Fd))
     610                 :             :     {
     611                 :          66 :         close(self->Fd);
     612                 :          66 :         self->Fd = INVALID_FD;
     613                 :             :     }
     614                 :          78 : }
     615                 :             : 
     616                 :          68 : static uint32_t PosixTcpStream_Version(struct SolidSyslogStream* base)
     617                 :             : {
     618                 :             :     (void) base;
     619                 :          68 :     return 0U;
     620                 :             : }
        

Generated by: LCOV version 2.0-1