LCOV - code coverage report
Current view: top level - include/internal - csock.h (source / functions) Coverage Total Hit
Test: c_collections 2.0.0 Lines: 100.0 % 8 8
Test Date: 2026-11-15 18:57:05 Functions: 100.0 % 2 2
Legend: Lines: hit not hit

            Line data    Source code
       1              : /*
       2              : MIT License
       3              : 
       4              : Copyright (c) 2026 - A bunch of nerds
       5              : 
       6              : Permission is hereby granted, free of charge, to any person obtaining a copy
       7              : of this software and associated documentation files (the "Software"), to deal
       8              : in the Software without restriction, including without limitation the rights
       9              : to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      10              : copies of the Software, and to permit persons to whom the Software is
      11              : furnished to do so, subject to the following conditions:
      12              : 
      13              : The above copyright notice and this permission notice shall be included in all
      14              : copies or substantial portions of the Software.
      15              : 
      16              : THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      17              : IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      18              : FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      19              : AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      20              : LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      21              : OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      22              : SOFTWARE.
      23              : */
      24              : 
      25              : // Every socket the library creates is non-blocking, closed on exec and never
      26              : // raises SIGPIPE. Linux and the BSDs take SOCK_NONBLOCK and SOCK_CLOEXEC at
      27              : // creation, have accept4() and MSG_NOSIGNAL. macOS has none of them, so there
      28              : // we set the flags with fcntl() right after the socket exists and put
      29              : // SO_NOSIGPIPE on it, which makes CCOL_MSG_NOSIGNAL 0.
      30              : // CCOL__EMULATE_DARWIN_SOCK picks the macOS form on other systems too, which is
      31              : // how the Linux and FreeBSD suites test it (Linux has no SO_NOSIGPIPE, so it
      32              : // keeps MSG_NOSIGNAL). When the flags need a second call, both calls run inside
      33              : // the close-on-exec gate of common.h, so a fork() from another thread can't
      34              : // hand a child the socket before it's closed on exec. Every new socket of the
      35              : // library should come from here: A socket() call with the Linux flags doesn't
      36              : // build on macOS, and one without them loses these properties everywhere.
      37              : 
      38              : #ifndef CCOL_INTERNAL_CSOCK_H
      39              : #define CCOL_INTERNAL_CSOCK_H
      40              : 
      41              : #include <common.h>
      42              : #include <errno.h>
      43              : #include <fcntl.h>
      44              : #include <poll.h>
      45              : #include <stddef.h>
      46              : // C23 has bool, true and false as keywords.
      47              : #if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 202311L
      48              : #include <stdbool.h>
      49              : #endif
      50              : #include <sys/socket.h>
      51              : #include <sys/types.h>
      52              : #include <unistd.h>
      53              : 
      54              : // macOS lacks the Linux socket flags, so it always takes the emulated path.
      55              : #if defined(__APPLE__) && !defined(CCOL__EMULATE_DARWIN_SOCK)
      56              : #define CCOL__EMULATE_DARWIN_SOCK 1
      57              : #endif
      58              : 
      59              : // CCOL_MSG_NOSIGNAL is the flag every send of the library passes so a gone
      60              : // peer raises no SIGPIPE. It's 0 where SO_NOSIGPIPE on the socket does the job,
      61              : // and CCOL__SOCK_NOSIGPIPE says so.
      62              : #if defined(CCOL__EMULATE_DARWIN_SOCK) && defined(SO_NOSIGPIPE)
      63              : #define CCOL_MSG_NOSIGNAL 0
      64              : #define CCOL__SOCK_NOSIGPIPE 1
      65              : #else
      66              : #define CCOL_MSG_NOSIGNAL MSG_NOSIGNAL
      67              : #endif
      68              : 
      69              : #if defined(CCOL__EMULATE_DARWIN_SOCK)
      70              : // Makes a new socket closed on exec, free of SIGPIPE and, when nonblock is
      71              : // true, non-blocking, with fcntl() and setsockopt(); the emulated helpers below
      72              : // call it on each socket they create. If any step fails it closes fd and gives
      73              : // -1, else it gives fd.
      74              : static inline int ccol__sock_setup(int fd, bool nonblock) {
      75              :   if (fd < 0) return -1;
      76              :   int fl = fcntl(fd, F_GETFD);
      77              :   int st = nonblock ? fcntl(fd, F_GETFL) : 0;
      78              :   bool ok = fl >= 0 && fcntl(fd, F_SETFD, fl | FD_CLOEXEC) == 0 && st >= 0 &&
      79              :             (!nonblock || fcntl(fd, F_SETFL, st | O_NONBLOCK) == 0);
      80              : #if defined(CCOL__SOCK_NOSIGPIPE)
      81              :   int one = 1;
      82              :   ok = ok && setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof(one)) == 0;
      83              : #endif
      84              :   if (!ok) {
      85              :     close(fd);
      86              :     return -1;
      87              :   }
      88              :   return fd;
      89              : }
      90              : #endif
      91              : 
      92              : // Makes a socket we didn't create free of SIGPIPE where that's a property of
      93              : // the socket (SO_NOSIGPIPE). Gives 0, or -1 when the option can't be set. Where
      94              : // CCOL_MSG_NOSIGNAL does the job it does nothing.
      95              : static inline int ccol_sock_nosigpipe(int fd) {
      96              : #if defined(CCOL__SOCK_NOSIGPIPE)
      97              :   int one = 1;
      98              :   return setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof(one)) == 0 ? 0
      99              :                                                                           : -1;
     100              : #else
     101              :   (void)fd;
     102              :   return 0;
     103              : #endif
     104              : }
     105              : 
     106              : #if defined(CCOL__EMULATE_DARWIN_SOCK)
     107              : // Leaves the close-on-exec gate and gives fd back, keeping the errno that the
     108              : // steps inside the gate left; every emulated helper ends with it.
     109              : static inline int ccol__sock_gate_leave(int fd) {
     110              :   int saved = errno;
     111              :   ccol__cloexec_gate_leave();
     112              :   errno = saved;
     113              :   return fd;
     114              : }
     115              : #endif
     116              : 
     117              : // socket(2) for a non-blocking socket that is closed on exec; every socket the
     118              : // library creates comes from here. Gives the fd or -1 with errno set.
     119         1728 : static inline int ccol_socket_nb(int domain, int type, int protocol) {
     120              : #if defined(CCOL__EMULATE_DARWIN_SOCK)
     121              :   ccol__cloexec_gate_enter();
     122              :   return ccol__sock_gate_leave(
     123              :       ccol__sock_setup(socket(domain, type, protocol), true));
     124              : #else
     125         1728 :   return socket(domain, type | SOCK_NONBLOCK | SOCK_CLOEXEC, protocol);
     126              : #endif
     127              : }
     128              : 
     129              : #if defined(CCOL__EMULATE_DARWIN_SOCK)
     130              : // accept(2) for a non-blocking socket that is closed on exec, for the servers
     131              : // of the library. ccol_accept_nb is a macro that evaluates to the new fd or -1,
     132              : // so that a file which never accepts doesn't need a declaration of accept4(),
     133              : // which glibc gives only under _GNU_SOURCE.
     134              : static inline int ccol__accept_nb_gated(int fd, struct sockaddr *addr,
     135              :                                         socklen_t *addrlen) {
     136              :   ccol__cloexec_gate_enter();
     137              :   return ccol__sock_gate_leave(
     138              :       ccol__sock_setup(accept(fd, addr, addrlen), true));
     139              : }
     140              : #define ccol_accept_nb(fd, addr, addrlen) \
     141              :   ccol__accept_nb_gated((fd), (addr), (addrlen))
     142              : #else
     143              : #define ccol_accept_nb(fd, addr, addrlen) \
     144              :   accept4((fd), (addr), (addrlen), SOCK_NONBLOCK | SOCK_CLOEXEC)
     145              : #endif
     146              : 
     147              : // socketpair(2) for two non-blocking sockets that are closed on exec, filling
     148              : // sv. Gives 0, or -1 with errno set and no socket left open.
     149            8 : static inline int ccol_socketpair_nb(int domain, int type, int protocol,
     150              :                                      int sv[2]) {
     151              : #if defined(CCOL__EMULATE_DARWIN_SOCK)
     152              :   ccol__cloexec_gate_enter();
     153              :   if (socketpair(domain, type, protocol, sv) != 0)
     154              :     return ccol__sock_gate_leave(-1);
     155              :   if (ccol__sock_setup(sv[0], true) < 0) {
     156              :     close(sv[1]);
     157              :     return ccol__sock_gate_leave(-1);
     158              :   }
     159              :   if (ccol__sock_setup(sv[1], true) < 0) {
     160              :     close(sv[0]);
     161              :     return ccol__sock_gate_leave(-1);
     162              :   }
     163              :   return ccol__sock_gate_leave(0);
     164              : #else
     165            8 :   return socketpair(domain, type | SOCK_NONBLOCK | SOCK_CLOEXEC, protocol, sv);
     166              : #endif
     167              : }
     168              : 
     169              : #if defined(CCOL__EMULATE_DARWIN_SOCK)
     170              : // The flag for a send that must not block. Linux and FreeBSD honour
     171              : // MSG_DONTWAIT on send(2); macOS honours it only on recv(2), so its send to a
     172              : // blocking socket with too little room waits for the rest. There the flag is 0
     173              : // and ccol_send_room() limits the send instead.
     174              : #define CCOL_MSG_DONTWAIT 0
     175              : #else
     176              : #define CCOL_MSG_DONTWAIT MSG_DONTWAIT
     177              : #endif
     178              : 
     179              : #if defined(CCOL__EMULATE_DARWIN_SOCK)
     180              : // How many of len bytes one send(2) can hand to a blocking fd without waiting.
     181              : // After POLLOUT a stream socket has room for at least SO_SNDLOWAT bytes, so we
     182              : // give that many, or 0 when there's no room (the caller reports EAGAIN). Any
     183              : // other socket type gets len: A macOS datagram socket never queues in its send
     184              : // buffer, so a datagram goes out whole or fails with ENOBUFS. An error or a
     185              : // hang-up also gives len, so the send itself reports it. Linux has no real
     186              : // SO_SNDLOWAT and its POLLOUT means a quarter of the buffer is free, so the
     187              : // emulation uses 2048 there, the macOS default.
     188              : static inline size_t ccol__send_room_blocking(int fd, size_t len) {
     189              :   int type = 0;
     190              :   socklen_t tl = sizeof(type);
     191              :   if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &type, &tl) != 0 ||
     192              :       type != SOCK_STREAM)
     193              :     return len;
     194              :   struct pollfd pfd = {.fd = fd, .events = POLLOUT, .revents = 0};
     195              :   int pr;
     196              :   do {
     197              :     pr = poll(&pfd, 1, 0);
     198              :   } while (pr < 0 && errno == EINTR);
     199              :   if (pr < 0) return len;
     200              :   if (pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) return len;
     201              :   if (!(pfd.revents & POLLOUT)) return 0;
     202              : #if defined(__linux__)
     203              :   int lowat = 2048;
     204              : #else
     205              :   int lowat = 0;
     206              :   socklen_t ll = sizeof(lowat);
     207              :   if (getsockopt(fd, SOL_SOCKET, SO_SNDLOWAT, &lowat, &ll) != 0 || lowat < 1)
     208              :     lowat = 1;
     209              : #endif
     210              :   return len < (size_t)lowat ? len : (size_t)lowat;
     211              : }
     212              : 
     213              : // Gives how many of the len bytes a send with CCOL_MSG_DONTWAIT can hand to fd
     214              : // without waiting, for ccol_send_nb() and the callers that use sendmsg(): len
     215              : // where the flag does the job or fd is non-blocking, otherwise what
     216              : // ccol__send_room_blocking() finds.
     217              : static inline size_t ccol_send_room(int fd, size_t len) {
     218              :   int st = fcntl(fd, F_GETFL);
     219              :   if (st < 0 || (st & O_NONBLOCK)) return len;
     220              :   return ccol__send_room_blocking(fd, len);
     221              : }
     222              : #else
     223              : // Without the emulation MSG_DONTWAIT does the job, so a send may hand over all
     224              : // len bytes.
     225              : static inline size_t ccol_send_room(int fd, size_t len) {
     226              :   (void)fd;
     227              :   return len;
     228              : }
     229              : #endif
     230              : 
     231              : // send(2) of at most len bytes that never blocks, for the HTTP stream writes
     232              : // and the logger's bounded writes. With no room right now it gives -1 and errno
     233              : // EAGAIN, otherwise what send(2) gives. A short count can happen on every
     234              : // system, as with any send on a stream socket.
     235           32 : static inline ssize_t ccol_send_nb(int fd, const void *buf, size_t len,
     236              :                                    int flags) {
     237           32 :   size_t room = ccol_send_room(fd, len);
     238           32 :   if (room == 0 && len > 0) {
     239              :     errno = EAGAIN;
     240              :     return -1;
     241              :   }
     242           32 :   return send(fd, buf, room, flags | CCOL_MSG_DONTWAIT);
     243              : }
     244              : 
     245              : #endif
        

Generated by: LCOV version 2.0-1