LCOV - code coverage report
Current view: top level - src/backend/libpq - pqcomm.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 61.3 % 551 338
Test Date: 2026-08-15 10:15:37 Functions: 91.5 % 47 43
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 39.6 % 412 163

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * pqcomm.c
       4                 :             :  *    Communication functions between the Frontend and the Backend
       5                 :             :  *
       6                 :             :  * These routines handle the low-level details of communication between
       7                 :             :  * frontend and backend.  They just shove data across the communication
       8                 :             :  * channel, and are ignorant of the semantics of the data.
       9                 :             :  *
      10                 :             :  * To emit an outgoing message, use the routines in pqformat.c to construct
      11                 :             :  * the message in a buffer and then emit it in one call to pq_putmessage.
      12                 :             :  * There are no functions to send raw bytes or partial messages; this
      13                 :             :  * ensures that the channel will not be clogged by an incomplete message if
      14                 :             :  * execution is aborted by ereport(ERROR) partway through the message.
      15                 :             :  *
      16                 :             :  * At one time, libpq was shared between frontend and backend, but now
      17                 :             :  * the backend's "backend/libpq" is quite separate from "interfaces/libpq".
      18                 :             :  * All that remains is similarities of names to trap the unwary...
      19                 :             :  *
      20                 :             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
      21                 :             :  * Portions Copyright (c) 1994, Regents of the University of California
      22                 :             :  *
      23                 :             :  *  src/backend/libpq/pqcomm.c
      24                 :             :  *
      25                 :             :  *-------------------------------------------------------------------------
      26                 :             :  */
      27                 :             : 
      28                 :             : /*------------------------
      29                 :             :  * INTERFACE ROUTINES
      30                 :             :  *
      31                 :             :  * setup/teardown:
      32                 :             :  *      ListenServerPort    - Open postmaster's server port
      33                 :             :  *      AcceptConnection    - Accept new connection with client
      34                 :             :  *      TouchSocketFiles    - Protect socket files against /tmp cleaners
      35                 :             :  *      pq_init             - initialize libpq at backend startup
      36                 :             :  *      socket_comm_reset   - reset libpq during error recovery
      37                 :             :  *      socket_close        - shutdown libpq at backend exit
      38                 :             :  *
      39                 :             :  * low-level I/O:
      40                 :             :  *      pq_getbytes     - get a known number of bytes from connection
      41                 :             :  *      pq_getmessage   - get a message with length word from connection
      42                 :             :  *      pq_getbyte      - get next byte from connection
      43                 :             :  *      pq_peekbyte     - peek at next byte from connection
      44                 :             :  *      pq_flush        - flush pending output
      45                 :             :  *      pq_flush_if_writable - flush pending output if writable without blocking
      46                 :             :  *      pq_getbyte_if_available - get a byte if available without blocking
      47                 :             :  *
      48                 :             :  * message-level I/O
      49                 :             :  *      pq_putmessage   - send a normal message (suppressed in COPY OUT mode)
      50                 :             :  *      pq_putmessage_noblock - buffer a normal message (suppressed in COPY OUT)
      51                 :             :  *
      52                 :             :  *------------------------
      53                 :             :  */
      54                 :             : #include "postgres.h"
      55                 :             : 
      56                 :             : #include <signal.h>
      57                 :             : #include <fcntl.h>
      58                 :             : #include <grp.h>
      59                 :             : #include <unistd.h>
      60                 :             : #include <sys/file.h>
      61                 :             : #include <sys/socket.h>
      62                 :             : #include <sys/stat.h>
      63                 :             : #include <sys/time.h>
      64                 :             : #include <netdb.h>
      65                 :             : #include <netinet/in.h>
      66                 :             : #include <netinet/tcp.h>
      67                 :             : #include <utime.h>
      68                 :             : #ifdef WIN32
      69                 :             : #include <mstcpip.h>
      70                 :             : #endif
      71                 :             : 
      72                 :             : #include "common/ip.h"
      73                 :             : #include "libpq/libpq.h"
      74                 :             : #include "miscadmin.h"
      75                 :             : #include "port/pg_bswap.h"
      76                 :             : #include "postmaster/postmaster.h"
      77                 :             : #include "storage/ipc.h"
      78                 :             : #include "storage/latch.h"
      79                 :             : #include "utils/guc_hooks.h"
      80                 :             : #include "utils/memutils.h"
      81                 :             : 
      82                 :             : /*
      83                 :             :  * Cope with the various platform-specific ways to spell TCP keepalive socket
      84                 :             :  * options.  This doesn't cover Windows, which as usual does its own thing.
      85                 :             :  */
      86                 :             : #if defined(TCP_KEEPIDLE)
      87                 :             : /* TCP_KEEPIDLE is the name of this option on Linux and *BSD */
      88                 :             : #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPIDLE
      89                 :             : #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPIDLE"
      90                 :             : #elif defined(TCP_KEEPALIVE_THRESHOLD)
      91                 :             : /* TCP_KEEPALIVE_THRESHOLD is the name of this option on Solaris >= 11 */
      92                 :             : #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE_THRESHOLD
      93                 :             : #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE_THRESHOLD"
      94                 :             : #elif defined(TCP_KEEPALIVE) && defined(__darwin__)
      95                 :             : /* TCP_KEEPALIVE is the name of this option on macOS */
      96                 :             : /* Caution: Solaris has this symbol but it means something different */
      97                 :             : #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE
      98                 :             : #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE"
      99                 :             : #endif
     100                 :             : 
     101                 :             : /*
     102                 :             :  * Configuration options
     103                 :             :  */
     104                 :             : int         Unix_socket_permissions;
     105                 :             : char       *Unix_socket_group;
     106                 :             : 
     107                 :             : /* Where the Unix socket files are (list of palloc'd strings) */
     108                 :             : static List *sock_paths = NIL;
     109                 :             : 
     110                 :             : /*
     111                 :             :  * Buffers for low-level I/O.
     112                 :             :  *
     113                 :             :  * The receive buffer is fixed size. Send buffer is usually 8k, but can be
     114                 :             :  * enlarged by pq_putmessage_noblock() if the message doesn't fit otherwise.
     115                 :             :  */
     116                 :             : 
     117                 :             : #define PQ_SEND_BUFFER_SIZE 8192
     118                 :             : #define PQ_RECV_BUFFER_SIZE 8192
     119                 :             : 
     120                 :             : static char *PqSendBuffer;
     121                 :             : static int  PqSendBufferSize;   /* Size send buffer */
     122                 :             : static size_t PqSendPointer;    /* Next index to store a byte in PqSendBuffer */
     123                 :             : static size_t PqSendStart;      /* Next index to send a byte in PqSendBuffer */
     124                 :             : 
     125                 :             : static char PqRecvBuffer[PQ_RECV_BUFFER_SIZE];
     126                 :             : static int  PqRecvPointer;      /* Next index to read a byte from PqRecvBuffer */
     127                 :             : static int  PqRecvLength;       /* End of data available in PqRecvBuffer */
     128                 :             : 
     129                 :             : /*
     130                 :             :  * Message status
     131                 :             :  */
     132                 :             : static bool PqCommBusy;         /* busy sending data to the client */
     133                 :             : static bool PqCommReadingMsg;   /* in the middle of reading a message */
     134                 :             : 
     135                 :             : 
     136                 :             : /* Internal functions */
     137                 :             : static void socket_comm_reset(void);
     138                 :             : static void socket_close(int code, Datum arg);
     139                 :             : static void socket_set_nonblocking(bool nonblocking);
     140                 :             : static int  socket_flush(void);
     141                 :             : static int  socket_flush_if_writable(void);
     142                 :             : static bool socket_is_send_pending(void);
     143                 :             : static int  socket_putmessage(char msgtype, const char *s, size_t len);
     144                 :             : static void socket_putmessage_noblock(char msgtype, const char *s, size_t len);
     145                 :             : static inline int internal_putbytes(const void *b, size_t len);
     146                 :             : static inline int internal_flush(void);
     147                 :             : static pg_noinline int internal_flush_buffer(const char *buf, size_t *start,
     148                 :             :                                              size_t *end);
     149                 :             : 
     150                 :             : static int  Lock_AF_UNIX(const char *unixSocketDir, const char *unixSocketPath);
     151                 :             : static int  Setup_AF_UNIX(const char *sock_path);
     152                 :             : 
     153                 :             : static const PQcommMethods PqCommSocketMethods = {
     154                 :             :     .comm_reset = socket_comm_reset,
     155                 :             :     .flush = socket_flush,
     156                 :             :     .flush_if_writable = socket_flush_if_writable,
     157                 :             :     .is_send_pending = socket_is_send_pending,
     158                 :             :     .putmessage = socket_putmessage,
     159                 :             :     .putmessage_noblock = socket_putmessage_noblock
     160                 :             : };
     161                 :             : 
     162                 :             : const PQcommMethods *PqCommMethods = &PqCommSocketMethods;
     163                 :             : 
     164                 :             : WaitEventSet *FeBeWaitSet;
     165                 :             : 
     166                 :             : 
     167                 :             : /* --------------------------------
     168                 :             :  *      pq_init - initialize libpq at backend startup
     169                 :             :  * --------------------------------
     170                 :             :  */
     171                 :             : Port *
     172                 :       15451 : pq_init(ClientSocket *client_sock)
     173                 :             : {
     174                 :             :     Port       *port;
     175                 :             :     int         socket_pos PG_USED_FOR_ASSERTS_ONLY;
     176                 :             :     int         latch_pos PG_USED_FOR_ASSERTS_ONLY;
     177                 :             : 
     178                 :             :     /* allocate the Port struct and copy the ClientSocket contents to it */
     179                 :       15451 :     port = palloc0_object(Port);
     180                 :       15451 :     port->sock = client_sock->sock;
     181                 :       15451 :     memcpy(&port->raddr.addr, &client_sock->raddr.addr, client_sock->raddr.salen);
     182                 :       15451 :     port->raddr.salen = client_sock->raddr.salen;
     183                 :             : 
     184                 :             :     /* fill in the server (local) address */
     185                 :       15451 :     port->laddr.salen = sizeof(port->laddr.addr);
     186         [ -  + ]:       15451 :     if (getsockname(port->sock,
     187                 :       15451 :                     (struct sockaddr *) &port->laddr.addr,
     188                 :             :                     &port->laddr.salen) < 0)
     189                 :             :     {
     190         [ #  # ]:           0 :         ereport(FATAL,
     191                 :             :                 (errmsg("%s() failed: %m", "getsockname")));
     192                 :             :     }
     193                 :             : 
     194                 :             :     /* select NODELAY and KEEPALIVE options if it's a TCP connection */
     195         [ +  + ]:       15451 :     if (port->laddr.addr.ss_family != AF_UNIX)
     196                 :             :     {
     197                 :             :         int         on;
     198                 :             : #ifdef WIN32
     199                 :             :         int         oldopt;
     200                 :             :         int         optlen;
     201                 :             :         int         newopt;
     202                 :             : #endif
     203                 :             : 
     204                 :             : #ifdef  TCP_NODELAY
     205                 :         334 :         on = 1;
     206         [ -  + ]:         334 :         if (setsockopt(port->sock, IPPROTO_TCP, TCP_NODELAY,
     207                 :             :                        (char *) &on, sizeof(on)) < 0)
     208                 :             :         {
     209         [ #  # ]:           0 :             ereport(FATAL,
     210                 :             :                     (errmsg("%s(%s) failed: %m", "setsockopt", "TCP_NODELAY")));
     211                 :             :         }
     212                 :             : #endif
     213                 :         334 :         on = 1;
     214         [ -  + ]:         334 :         if (setsockopt(port->sock, SOL_SOCKET, SO_KEEPALIVE,
     215                 :             :                        (char *) &on, sizeof(on)) < 0)
     216                 :             :         {
     217         [ #  # ]:           0 :             ereport(FATAL,
     218                 :             :                     (errmsg("%s(%s) failed: %m", "setsockopt", "SO_KEEPALIVE")));
     219                 :             :         }
     220                 :             : 
     221                 :             : #ifdef WIN32
     222                 :             : 
     223                 :             :         /*
     224                 :             :          * This is a Win32 socket optimization.  The OS send buffer should be
     225                 :             :          * large enough to send the whole Postgres send buffer in one go, or
     226                 :             :          * performance suffers.  The Postgres send buffer can be enlarged if a
     227                 :             :          * very large message needs to be sent, but we won't attempt to
     228                 :             :          * enlarge the OS buffer if that happens, so somewhat arbitrarily
     229                 :             :          * ensure that the OS buffer is at least PQ_SEND_BUFFER_SIZE * 4.
     230                 :             :          * (That's 32kB with the current default).
     231                 :             :          *
     232                 :             :          * The default OS buffer size used to be 8kB in earlier Windows
     233                 :             :          * versions, but was raised to 64kB in Windows 2012.  So it shouldn't
     234                 :             :          * be necessary to change it in later versions anymore.  Changing it
     235                 :             :          * unnecessarily can even reduce performance, because setting
     236                 :             :          * SO_SNDBUF in the application disables the "dynamic send buffering"
     237                 :             :          * feature that was introduced in Windows 7.  So before fiddling with
     238                 :             :          * SO_SNDBUF, check if the current buffer size is already large enough
     239                 :             :          * and only increase it if necessary.
     240                 :             :          *
     241                 :             :          * See https://support.microsoft.com/kb/823764/EN-US/ and
     242                 :             :          * https://msdn.microsoft.com/en-us/library/bb736549%28v=vs.85%29.aspx
     243                 :             :          */
     244                 :             :         optlen = sizeof(oldopt);
     245                 :             :         if (getsockopt(port->sock, SOL_SOCKET, SO_SNDBUF, (char *) &oldopt,
     246                 :             :                        &optlen) < 0)
     247                 :             :         {
     248                 :             :             ereport(FATAL,
     249                 :             :                     (errmsg("%s(%s) failed: %m", "getsockopt", "SO_SNDBUF")));
     250                 :             :         }
     251                 :             :         newopt = PQ_SEND_BUFFER_SIZE * 4;
     252                 :             :         if (oldopt < newopt)
     253                 :             :         {
     254                 :             :             if (setsockopt(port->sock, SOL_SOCKET, SO_SNDBUF, (char *) &newopt,
     255                 :             :                            sizeof(newopt)) < 0)
     256                 :             :             {
     257                 :             :                 ereport(FATAL,
     258                 :             :                         (errmsg("%s(%s) failed: %m", "setsockopt", "SO_SNDBUF")));
     259                 :             :             }
     260                 :             :         }
     261                 :             : #endif
     262                 :             : 
     263                 :             :         /*
     264                 :             :          * Also apply the current keepalive parameters.  If we fail to set a
     265                 :             :          * parameter, don't error out, because these aren't universally
     266                 :             :          * supported.  (Note: you might think we need to reset the GUC
     267                 :             :          * variables to 0 in such a case, but it's not necessary because the
     268                 :             :          * show hooks for these variables report the truth anyway.)
     269                 :             :          */
     270                 :         334 :         (void) pq_setkeepalivesidle(tcp_keepalives_idle, port);
     271                 :         334 :         (void) pq_setkeepalivesinterval(tcp_keepalives_interval, port);
     272                 :         334 :         (void) pq_setkeepalivescount(tcp_keepalives_count, port);
     273                 :         334 :         (void) pq_settcpusertimeout(tcp_user_timeout, port);
     274                 :             :     }
     275                 :             : 
     276                 :             :     /* initialize state variables */
     277                 :       15451 :     PqSendBufferSize = PQ_SEND_BUFFER_SIZE;
     278                 :       15451 :     PqSendBuffer = MemoryContextAlloc(TopMemoryContext, PqSendBufferSize);
     279                 :       15451 :     PqSendPointer = PqSendStart = PqRecvPointer = PqRecvLength = 0;
     280                 :       15451 :     PqCommBusy = false;
     281                 :       15451 :     PqCommReadingMsg = false;
     282                 :             : 
     283                 :             :     /* set up process-exit hook to close the socket */
     284                 :       15451 :     on_proc_exit(socket_close, 0);
     285                 :             : 
     286                 :             :     /*
     287                 :             :      * In backends (as soon as forked) we operate the underlying socket in
     288                 :             :      * nonblocking mode and use latches to implement blocking semantics if
     289                 :             :      * needed. That allows us to provide safely interruptible reads and
     290                 :             :      * writes.
     291                 :             :      */
     292                 :             : #ifndef WIN32
     293         [ -  + ]:       15451 :     if (!pg_set_noblock(port->sock))
     294         [ #  # ]:           0 :         ereport(FATAL,
     295                 :             :                 (errmsg("could not set socket to nonblocking mode: %m")));
     296                 :             : #endif
     297                 :             : 
     298                 :             : #ifndef WIN32
     299                 :             : 
     300                 :             :     /* Don't give the socket to any subprograms we execute. */
     301         [ -  + ]:       15451 :     if (fcntl(port->sock, F_SETFD, FD_CLOEXEC) < 0)
     302         [ #  # ]:           0 :         elog(FATAL, "fcntl(F_SETFD) failed on socket: %m");
     303                 :             : #endif
     304                 :             : 
     305                 :       15451 :     FeBeWaitSet = CreateWaitEventSet(NULL, FeBeWaitSetNEvents);
     306                 :       15451 :     socket_pos = AddWaitEventToSet(FeBeWaitSet, WL_SOCKET_WRITEABLE,
     307                 :             :                                    port->sock, NULL, NULL);
     308                 :       15451 :     latch_pos = AddWaitEventToSet(FeBeWaitSet, WL_LATCH_SET, PGINVALID_SOCKET,
     309                 :             :                                   MyLatch, NULL);
     310                 :       15451 :     AddWaitEventToSet(FeBeWaitSet, WL_POSTMASTER_DEATH, PGINVALID_SOCKET,
     311                 :             :                       NULL, NULL);
     312                 :             : 
     313                 :             :     /*
     314                 :             :      * The event positions match the order we added them, but let's sanity
     315                 :             :      * check them to be sure.
     316                 :             :      */
     317                 :             :     Assert(socket_pos == FeBeWaitSetSocketPos);
     318                 :             :     Assert(latch_pos == FeBeWaitSetLatchPos);
     319                 :             : 
     320                 :       15451 :     return port;
     321                 :             : }
     322                 :             : 
     323                 :             : /* --------------------------------
     324                 :             :  *      socket_comm_reset - reset libpq during error recovery
     325                 :             :  *
     326                 :             :  * This is called from error recovery at the outer idle loop.  It's
     327                 :             :  * just to get us out of trouble if we somehow manage to elog() from
     328                 :             :  * inside a pqcomm.c routine (which ideally will never happen, but...)
     329                 :             :  * --------------------------------
     330                 :             :  */
     331                 :             : static void
     332                 :       31857 : socket_comm_reset(void)
     333                 :             : {
     334                 :             :     /* Do not throw away pending data, but do reset the busy flag */
     335                 :       31857 :     PqCommBusy = false;
     336                 :       31857 : }
     337                 :             : 
     338                 :             : /* --------------------------------
     339                 :             :  *      socket_close - shutdown libpq at backend exit
     340                 :             :  *
     341                 :             :  * This is the one pg_on_exit_callback in place during BackendInitialize().
     342                 :             :  * That function's unusual signal handling constrains that this callback be
     343                 :             :  * safe to run at any instant.
     344                 :             :  * --------------------------------
     345                 :             :  */
     346                 :             : static void
     347                 :       15451 : socket_close(int code, Datum arg)
     348                 :             : {
     349                 :             :     /* Nothing to do in a standalone backend, where MyProcPort is NULL. */
     350         [ +  - ]:       15451 :     if (MyProcPort != NULL)
     351                 :             :     {
     352                 :             : #ifdef ENABLE_GSS
     353                 :             :         /*
     354                 :             :          * Shutdown GSSAPI layer.  This section does nothing when interrupting
     355                 :             :          * BackendInitialize(), because pg_GSS_recvauth() makes first use of
     356                 :             :          * "ctx" and "cred".
     357                 :             :          *
     358                 :             :          * Note that we don't bother to free MyProcPort->gss, since we're
     359                 :             :          * about to exit anyway.
     360                 :             :          */
     361                 :             :         if (MyProcPort->gss)
     362                 :             :         {
     363                 :             :             OM_uint32   min_s;
     364                 :             : 
     365                 :             :             if (MyProcPort->gss->ctx != GSS_C_NO_CONTEXT)
     366                 :             :                 gss_delete_sec_context(&min_s, &MyProcPort->gss->ctx, NULL);
     367                 :             : 
     368                 :             :             if (MyProcPort->gss->cred != GSS_C_NO_CREDENTIAL)
     369                 :             :                 gss_release_cred(&min_s, &MyProcPort->gss->cred);
     370                 :             :         }
     371                 :             : #endif                          /* ENABLE_GSS */
     372                 :             : 
     373                 :             :         /*
     374                 :             :          * Cleanly shut down SSL layer.  Nowhere else does a postmaster child
     375                 :             :          * call this, so this is safe when interrupting BackendInitialize().
     376                 :             :          */
     377                 :       15451 :         secure_close(MyProcPort);
     378                 :             : 
     379                 :             :         /*
     380                 :             :          * Formerly we did an explicit close() here, but it seems better to
     381                 :             :          * leave the socket open until the process dies.  This allows clients
     382                 :             :          * to perform a "synchronous close" if they care --- wait till the
     383                 :             :          * transport layer reports connection closure, and you can be sure the
     384                 :             :          * backend has exited.
     385                 :             :          *
     386                 :             :          * We do set sock to PGINVALID_SOCKET to prevent any further I/O,
     387                 :             :          * though.
     388                 :             :          */
     389                 :       15451 :         MyProcPort->sock = PGINVALID_SOCKET;
     390                 :             :     }
     391                 :       15451 : }
     392                 :             : 
     393                 :             : 
     394                 :             : 
     395                 :             : /* --------------------------------
     396                 :             :  * Postmaster functions to handle sockets.
     397                 :             :  * --------------------------------
     398                 :             :  */
     399                 :             : 
     400                 :             : /*
     401                 :             :  * ListenServerPort -- open a "listening" port to accept connections.
     402                 :             :  *
     403                 :             :  * family should be AF_UNIX or AF_UNSPEC; portNumber is the port number.
     404                 :             :  * For AF_UNIX ports, hostName should be NULL and unixSocketDir must be
     405                 :             :  * specified.  For TCP ports, hostName is either NULL for all interfaces or
     406                 :             :  * the interface to listen on, and unixSocketDir is ignored (can be NULL).
     407                 :             :  *
     408                 :             :  * Successfully opened sockets are appended to the ListenSockets[] array.  On
     409                 :             :  * entry, *NumListenSockets holds the number of elements currently in the
     410                 :             :  * array, and it is updated to reflect the opened sockets.  MaxListen is the
     411                 :             :  * allocated size of the array.
     412                 :             :  *
     413                 :             :  * RETURNS: STATUS_OK or STATUS_ERROR
     414                 :             :  */
     415                 :             : int
     416                 :        1056 : ListenServerPort(int family, const char *hostName, unsigned short portNumber,
     417                 :             :                  const char *unixSocketDir,
     418                 :             :                  pgsocket ListenSockets[], int *NumListenSockets, int MaxListen)
     419                 :             : {
     420                 :             :     pgsocket    fd;
     421                 :             :     int         err;
     422                 :             :     int         maxconn;
     423                 :             :     int         ret;
     424                 :             :     char        portNumberStr[32];
     425                 :             :     const char *familyDesc;
     426                 :             :     char        familyDescBuf[64];
     427                 :             :     const char *addrDesc;
     428                 :             :     char        addrBuf[NI_MAXHOST];
     429                 :             :     char       *service;
     430                 :        1056 :     struct addrinfo *addrs = NULL,
     431                 :             :                *addr;
     432                 :             :     struct addrinfo hint;
     433                 :        1056 :     int         added = 0;
     434                 :             :     char        unixSocketPath[MAXPGPATH];
     435                 :             : #if !defined(WIN32) || defined(IPV6_V6ONLY)
     436                 :        1056 :     int         one = 1;
     437                 :             : #endif
     438                 :             : 
     439                 :             :     /* Initialize hint structure */
     440   [ +  -  +  -  :        7392 :     MemSet(&hint, 0, sizeof(hint));
          +  -  +  -  +  
                      + ]
     441                 :        1056 :     hint.ai_family = family;
     442                 :        1056 :     hint.ai_flags = AI_PASSIVE;
     443                 :        1056 :     hint.ai_socktype = SOCK_STREAM;
     444                 :             : 
     445         [ +  + ]:        1056 :     if (family == AF_UNIX)
     446                 :             :     {
     447                 :             :         /*
     448                 :             :          * Create unixSocketPath from portNumber and unixSocketDir and lock
     449                 :             :          * that file path
     450                 :             :          */
     451                 :        1015 :         UNIXSOCK_PATH(unixSocketPath, portNumber, unixSocketDir);
     452         [ -  + ]:        1015 :         if (strlen(unixSocketPath) >= UNIXSOCK_PATH_BUFLEN)
     453                 :             :         {
     454         [ #  # ]:           0 :             ereport(LOG,
     455                 :             :                     (errmsg("Unix-domain socket path \"%s\" is too long (maximum %zu bytes)",
     456                 :             :                             unixSocketPath,
     457                 :             :                             (UNIXSOCK_PATH_BUFLEN - 1))));
     458                 :           0 :             return STATUS_ERROR;
     459                 :             :         }
     460         [ -  + ]:        1015 :         if (Lock_AF_UNIX(unixSocketDir, unixSocketPath) != STATUS_OK)
     461                 :           0 :             return STATUS_ERROR;
     462                 :        1015 :         service = unixSocketPath;
     463                 :             :     }
     464                 :             :     else
     465                 :             :     {
     466                 :          41 :         snprintf(portNumberStr, sizeof(portNumberStr), "%d", portNumber);
     467                 :          41 :         service = portNumberStr;
     468                 :             :     }
     469                 :             : 
     470                 :        1056 :     ret = pg_getaddrinfo_all(hostName, service, &hint, &addrs);
     471   [ +  -  -  + ]:        1056 :     if (ret || !addrs)
     472                 :             :     {
     473         [ #  # ]:           0 :         if (hostName)
     474         [ #  # ]:           0 :             ereport(LOG,
     475                 :             :                     (errmsg("could not translate host name \"%s\", service \"%s\" to address: %s",
     476                 :             :                             hostName, service, gai_strerror(ret))));
     477                 :             :         else
     478         [ #  # ]:           0 :             ereport(LOG,
     479                 :             :                     (errmsg("could not translate service \"%s\" to address: %s",
     480                 :             :                             service, gai_strerror(ret))));
     481         [ #  # ]:           0 :         if (addrs)
     482                 :           0 :             pg_freeaddrinfo_all(hint.ai_family, addrs);
     483                 :           0 :         return STATUS_ERROR;
     484                 :             :     }
     485                 :             : 
     486         [ +  + ]:        2113 :     for (addr = addrs; addr; addr = addr->ai_next)
     487                 :             :     {
     488   [ +  +  -  + ]:        1057 :         if (family != AF_UNIX && addr->ai_family == AF_UNIX)
     489                 :             :         {
     490                 :             :             /*
     491                 :             :              * Only set up a unix domain socket when they really asked for it.
     492                 :             :              * The service/port is different in that case.
     493                 :             :              */
     494                 :           0 :             continue;
     495                 :             :         }
     496                 :             : 
     497                 :             :         /* See if there is still room to add 1 more socket. */
     498         [ -  + ]:        1057 :         if (*NumListenSockets == MaxListen)
     499                 :             :         {
     500         [ #  # ]:           0 :             ereport(LOG,
     501                 :             :                     (errmsg("could not bind to all requested addresses: MAXLISTEN (%d) exceeded",
     502                 :             :                             MaxListen)));
     503                 :           0 :             break;
     504                 :             :         }
     505                 :             : 
     506                 :             :         /* set up address family name for log messages */
     507   [ +  +  +  - ]:        1057 :         switch (addr->ai_family)
     508                 :             :         {
     509                 :          41 :             case AF_INET:
     510                 :          41 :                 familyDesc = _("IPv4");
     511                 :          41 :                 break;
     512                 :           1 :             case AF_INET6:
     513                 :           1 :                 familyDesc = _("IPv6");
     514                 :           1 :                 break;
     515                 :        1015 :             case AF_UNIX:
     516                 :        1015 :                 familyDesc = _("Unix");
     517                 :        1015 :                 break;
     518                 :           0 :             default:
     519                 :           0 :                 snprintf(familyDescBuf, sizeof(familyDescBuf),
     520                 :           0 :                          _("unrecognized address family %d"),
     521                 :             :                          addr->ai_family);
     522                 :           0 :                 familyDesc = familyDescBuf;
     523                 :           0 :                 break;
     524                 :             :         }
     525                 :             : 
     526                 :             :         /* set up text form of address for log messages */
     527         [ +  + ]:        1057 :         if (addr->ai_family == AF_UNIX)
     528                 :        1015 :             addrDesc = unixSocketPath;
     529                 :             :         else
     530                 :             :         {
     531                 :          42 :             pg_getnameinfo_all((const struct sockaddr_storage *) addr->ai_addr,
     532                 :          42 :                                addr->ai_addrlen,
     533                 :             :                                addrBuf, sizeof(addrBuf),
     534                 :             :                                NULL, 0,
     535                 :             :                                NI_NUMERICHOST);
     536                 :          42 :             addrDesc = addrBuf;
     537                 :             :         }
     538                 :             : 
     539         [ -  + ]:        1057 :         if ((fd = socket(addr->ai_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
     540                 :             :         {
     541         [ #  # ]:           0 :             ereport(LOG,
     542                 :             :                     (errcode_for_socket_access(),
     543                 :             :             /* translator: first %s is IPv4, IPv6, or Unix */
     544                 :             :                      errmsg("could not create %s socket for address \"%s\": %m",
     545                 :             :                             familyDesc, addrDesc)));
     546                 :           0 :             continue;
     547                 :             :         }
     548                 :             : 
     549                 :             : #ifndef WIN32
     550                 :             :         /* Don't give the listen socket to any subprograms we execute. */
     551         [ -  + ]:        1057 :         if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0)
     552         [ #  # ]:           0 :             elog(FATAL, "fcntl(F_SETFD) failed on socket: %m");
     553                 :             : 
     554                 :             :         /*
     555                 :             :          * Without the SO_REUSEADDR flag, a new postmaster can't be started
     556                 :             :          * right away after a stop or crash, giving "address already in use"
     557                 :             :          * error on TCP ports.
     558                 :             :          *
     559                 :             :          * On win32, however, this behavior only happens if the
     560                 :             :          * SO_EXCLUSIVEADDRUSE is set. With SO_REUSEADDR, win32 allows
     561                 :             :          * multiple servers to listen on the same address, resulting in
     562                 :             :          * unpredictable behavior. With no flags at all, win32 behaves as Unix
     563                 :             :          * with SO_REUSEADDR.
     564                 :             :          */
     565         [ +  + ]:        1057 :         if (addr->ai_family != AF_UNIX)
     566                 :             :         {
     567         [ -  + ]:          42 :             if ((setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
     568                 :             :                             (char *) &one, sizeof(one))) == -1)
     569                 :             :             {
     570         [ #  # ]:           0 :                 ereport(LOG,
     571                 :             :                         (errcode_for_socket_access(),
     572                 :             :                 /* translator: third %s is IPv4 or IPv6 */
     573                 :             :                          errmsg("%s(%s) failed for %s address \"%s\": %m",
     574                 :             :                                 "setsockopt", "SO_REUSEADDR",
     575                 :             :                                 familyDesc, addrDesc)));
     576                 :           0 :                 closesocket(fd);
     577                 :           0 :                 continue;
     578                 :             :             }
     579                 :             :         }
     580                 :             : #endif
     581                 :             : 
     582                 :             : #ifdef IPV6_V6ONLY
     583         [ +  + ]:        1057 :         if (addr->ai_family == AF_INET6)
     584                 :             :         {
     585         [ -  + ]:           1 :             if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY,
     586                 :             :                            (char *) &one, sizeof(one)) == -1)
     587                 :             :             {
     588         [ #  # ]:           0 :                 ereport(LOG,
     589                 :             :                         (errcode_for_socket_access(),
     590                 :             :                 /* translator: third %s is IPv6 */
     591                 :             :                          errmsg("%s(%s) failed for %s address \"%s\": %m",
     592                 :             :                                 "setsockopt", "IPV6_V6ONLY",
     593                 :             :                                 familyDesc, addrDesc)));
     594                 :           0 :                 closesocket(fd);
     595                 :           0 :                 continue;
     596                 :             :             }
     597                 :             :         }
     598                 :             : #endif
     599                 :             : 
     600                 :             :         /*
     601                 :             :          * Note: This might fail on some OS's, like Linux older than
     602                 :             :          * 2.4.21-pre3, that don't have the IPV6_V6ONLY socket option, and map
     603                 :             :          * ipv4 addresses to ipv6.  It will show ::ffff:ipv4 for all ipv4
     604                 :             :          * connections.
     605                 :             :          */
     606                 :        1057 :         err = bind(fd, addr->ai_addr, addr->ai_addrlen);
     607         [ -  + ]:        1057 :         if (err < 0)
     608                 :           0 :         {
     609                 :           0 :             int         saved_errno = errno;
     610                 :             : 
     611   [ #  #  #  #  :           0 :             ereport(LOG,
                   #  # ]
     612                 :             :                     (errcode_for_socket_access(),
     613                 :             :             /* translator: first %s is IPv4, IPv6, or Unix */
     614                 :             :                      errmsg("could not bind %s address \"%s\": %m",
     615                 :             :                             familyDesc, addrDesc),
     616                 :             :                      saved_errno == EADDRINUSE ?
     617                 :             :                      (addr->ai_family == AF_UNIX ?
     618                 :             :                       errhint("Is another postmaster already running on port %d?",
     619                 :             :                               portNumber) :
     620                 :             :                       errhint("Is another postmaster already running on port %d?"
     621                 :             :                               " If not, wait a few seconds and retry.",
     622                 :             :                               portNumber)) : 0));
     623                 :           0 :             closesocket(fd);
     624                 :           0 :             continue;
     625                 :             :         }
     626                 :             : 
     627         [ +  + ]:        1057 :         if (addr->ai_family == AF_UNIX)
     628                 :             :         {
     629         [ -  + ]:        1015 :             if (Setup_AF_UNIX(service) != STATUS_OK)
     630                 :             :             {
     631                 :           0 :                 closesocket(fd);
     632                 :           0 :                 break;
     633                 :             :             }
     634                 :             :         }
     635                 :             : 
     636                 :             :         /*
     637                 :             :          * Select appropriate accept-queue length limit.  It seems reasonable
     638                 :             :          * to use a value similar to the maximum number of child processes
     639                 :             :          * that the postmaster will permit.
     640                 :             :          */
     641                 :        1057 :         maxconn = MaxConnections * 2;
     642                 :             : 
     643                 :        1057 :         err = listen(fd, maxconn);
     644         [ -  + ]:        1057 :         if (err < 0)
     645                 :             :         {
     646         [ #  # ]:           0 :             ereport(LOG,
     647                 :             :                     (errcode_for_socket_access(),
     648                 :             :             /* translator: first %s is IPv4, IPv6, or Unix */
     649                 :             :                      errmsg("could not listen on %s address \"%s\": %m",
     650                 :             :                             familyDesc, addrDesc)));
     651                 :           0 :             closesocket(fd);
     652                 :           0 :             continue;
     653                 :             :         }
     654                 :             : 
     655         [ +  + ]:        1057 :         if (addr->ai_family == AF_UNIX)
     656         [ +  - ]:        1015 :             ereport(LOG,
     657                 :             :                     (errmsg("listening on Unix socket \"%s\"",
     658                 :             :                             addrDesc)));
     659                 :             :         else
     660         [ +  - ]:          42 :             ereport(LOG,
     661                 :             :             /* translator: first %s is IPv4 or IPv6 */
     662                 :             :                     (errmsg("listening on %s address \"%s\", port %d",
     663                 :             :                             familyDesc, addrDesc, portNumber)));
     664                 :             : 
     665                 :        1057 :         ListenSockets[*NumListenSockets] = fd;
     666                 :        1057 :         (*NumListenSockets)++;
     667                 :        1057 :         added++;
     668                 :             :     }
     669                 :             : 
     670                 :        1056 :     pg_freeaddrinfo_all(hint.ai_family, addrs);
     671                 :             : 
     672         [ -  + ]:        1056 :     if (!added)
     673                 :           0 :         return STATUS_ERROR;
     674                 :             : 
     675                 :        1056 :     return STATUS_OK;
     676                 :             : }
     677                 :             : 
     678                 :             : 
     679                 :             : /*
     680                 :             :  * Lock_AF_UNIX -- configure unix socket file path
     681                 :             :  */
     682                 :             : static int
     683                 :        1015 : Lock_AF_UNIX(const char *unixSocketDir, const char *unixSocketPath)
     684                 :             : {
     685                 :             :     /* no lock file for abstract sockets */
     686         [ -  + ]:        1015 :     if (unixSocketPath[0] == '@')
     687                 :           0 :         return STATUS_OK;
     688                 :             : 
     689                 :             :     /*
     690                 :             :      * Grab an interlock file associated with the socket file.
     691                 :             :      *
     692                 :             :      * Note: there are two reasons for using a socket lock file, rather than
     693                 :             :      * trying to interlock directly on the socket itself.  First, it's a lot
     694                 :             :      * more portable, and second, it lets us remove any pre-existing socket
     695                 :             :      * file without race conditions.
     696                 :             :      */
     697                 :        1015 :     CreateSocketLockFile(unixSocketPath, true, unixSocketDir);
     698                 :             : 
     699                 :             :     /*
     700                 :             :      * Once we have the interlock, we can safely delete any pre-existing
     701                 :             :      * socket file to avoid failure at bind() time.
     702                 :             :      */
     703                 :        1015 :     (void) unlink(unixSocketPath);
     704                 :             : 
     705                 :             :     /*
     706                 :             :      * Remember socket file pathnames for later maintenance.
     707                 :             :      */
     708                 :        1015 :     sock_paths = lappend(sock_paths, pstrdup(unixSocketPath));
     709                 :             : 
     710                 :        1015 :     return STATUS_OK;
     711                 :             : }
     712                 :             : 
     713                 :             : 
     714                 :             : /*
     715                 :             :  * Setup_AF_UNIX -- configure unix socket permissions
     716                 :             :  */
     717                 :             : static int
     718                 :        1015 : Setup_AF_UNIX(const char *sock_path)
     719                 :             : {
     720                 :             :     /* no file system permissions for abstract sockets */
     721         [ -  + ]:        1015 :     if (sock_path[0] == '@')
     722                 :           0 :         return STATUS_OK;
     723                 :             : 
     724                 :             :     /*
     725                 :             :      * Fix socket ownership/permission if requested.  Note we must do this
     726                 :             :      * before we listen() to avoid a window where unwanted connections could
     727                 :             :      * get accepted.
     728                 :             :      */
     729                 :             :     Assert(Unix_socket_group);
     730         [ -  + ]:        1015 :     if (Unix_socket_group[0] != '\0')
     731                 :             :     {
     732                 :             : #ifdef WIN32
     733                 :             :         elog(WARNING, "configuration item \"unix_socket_group\" is not supported on this platform");
     734                 :             : #else
     735                 :             :         char       *endptr;
     736                 :             :         unsigned long val;
     737                 :             :         gid_t       gid;
     738                 :             : 
     739                 :           0 :         val = strtoul(Unix_socket_group, &endptr, 10);
     740         [ #  # ]:           0 :         if (*endptr == '\0')
     741                 :             :         {                       /* numeric group id */
     742                 :           0 :             gid = val;
     743                 :             :         }
     744                 :             :         else
     745                 :             :         {                       /* convert group name to id */
     746                 :             :             struct group *gr;
     747                 :             : 
     748                 :           0 :             gr = getgrnam(Unix_socket_group);
     749         [ #  # ]:           0 :             if (!gr)
     750                 :             :             {
     751         [ #  # ]:           0 :                 ereport(LOG,
     752                 :             :                         (errmsg("group \"%s\" does not exist",
     753                 :             :                                 Unix_socket_group)));
     754                 :           0 :                 return STATUS_ERROR;
     755                 :             :             }
     756                 :           0 :             gid = gr->gr_gid;
     757                 :             :         }
     758         [ #  # ]:           0 :         if (chown(sock_path, -1, gid) == -1)
     759                 :             :         {
     760         [ #  # ]:           0 :             ereport(LOG,
     761                 :             :                     (errcode_for_file_access(),
     762                 :             :                      errmsg("could not set group of file \"%s\": %m",
     763                 :             :                             sock_path)));
     764                 :           0 :             return STATUS_ERROR;
     765                 :             :         }
     766                 :             : #endif
     767                 :             :     }
     768                 :             : 
     769         [ -  + ]:        1015 :     if (chmod(sock_path, Unix_socket_permissions) == -1)
     770                 :             :     {
     771         [ #  # ]:           0 :         ereport(LOG,
     772                 :             :                 (errcode_for_file_access(),
     773                 :             :                  errmsg("could not set permissions of file \"%s\": %m",
     774                 :             :                         sock_path)));
     775                 :           0 :         return STATUS_ERROR;
     776                 :             :     }
     777                 :        1015 :     return STATUS_OK;
     778                 :             : }
     779                 :             : 
     780                 :             : 
     781                 :             : /*
     782                 :             :  * AcceptConnection -- accept a new connection with client using
     783                 :             :  *      server port.  Fills *client_sock with the FD and endpoint info
     784                 :             :  *      of the new connection.
     785                 :             :  *
     786                 :             :  * ASSUME: that this doesn't need to be non-blocking because
     787                 :             :  *      the Postmaster waits for the socket to be ready to accept().
     788                 :             :  *
     789                 :             :  * RETURNS: STATUS_OK or STATUS_ERROR
     790                 :             :  */
     791                 :             : int
     792                 :       15695 : AcceptConnection(pgsocket server_fd, ClientSocket *client_sock)
     793                 :             : {
     794                 :             :     /* accept connection and fill in the client (remote) address */
     795                 :       15695 :     client_sock->raddr.salen = sizeof(client_sock->raddr.addr);
     796         [ -  + ]:       15695 :     if ((client_sock->sock = accept(server_fd,
     797                 :       15695 :                                     (struct sockaddr *) &client_sock->raddr.addr,
     798                 :             :                                     &client_sock->raddr.salen)) == PGINVALID_SOCKET)
     799                 :             :     {
     800         [ #  # ]:           0 :         ereport(LOG,
     801                 :             :                 (errcode_for_socket_access(),
     802                 :             :                  errmsg("could not accept new connection: %m")));
     803                 :             : 
     804                 :             :         /*
     805                 :             :          * If accept() fails then postmaster.c will still see the server
     806                 :             :          * socket as read-ready, and will immediately try again.  To avoid
     807                 :             :          * uselessly sucking lots of CPU, delay a bit before trying again.
     808                 :             :          * (The most likely reason for failure is being out of kernel file
     809                 :             :          * table slots; we can do little except hope some will get freed up.)
     810                 :             :          */
     811                 :           0 :         pg_usleep(100000L);     /* wait 0.1 sec */
     812                 :           0 :         return STATUS_ERROR;
     813                 :             :     }
     814                 :             : 
     815                 :       15695 :     return STATUS_OK;
     816                 :             : }
     817                 :             : 
     818                 :             : /*
     819                 :             :  * TouchSocketFiles -- mark socket files as recently accessed
     820                 :             :  *
     821                 :             :  * This routine should be called every so often to ensure that the socket
     822                 :             :  * files have a recent mod date (ordinary operations on sockets usually won't
     823                 :             :  * change the mod date).  That saves them from being removed by
     824                 :             :  * overenthusiastic /tmp-directory-cleaner daemons.  (Another reason we should
     825                 :             :  * never have put the socket file in /tmp...)
     826                 :             :  */
     827                 :             : void
     828                 :           0 : TouchSocketFiles(void)
     829                 :             : {
     830                 :             :     ListCell   *l;
     831                 :             : 
     832                 :             :     /* Loop through all created sockets... */
     833   [ #  #  #  #  :           0 :     foreach(l, sock_paths)
                   #  # ]
     834                 :             :     {
     835                 :           0 :         char       *sock_path = (char *) lfirst(l);
     836                 :             : 
     837                 :             :         /* Ignore errors; there's no point in complaining */
     838                 :           0 :         (void) utime(sock_path, NULL);
     839                 :             :     }
     840                 :           0 : }
     841                 :             : 
     842                 :             : /*
     843                 :             :  * RemoveSocketFiles -- unlink socket files at postmaster shutdown
     844                 :             :  */
     845                 :             : void
     846                 :        1016 : RemoveSocketFiles(void)
     847                 :             : {
     848                 :             :     ListCell   *l;
     849                 :             : 
     850                 :             :     /* Loop through all created sockets... */
     851   [ +  +  +  +  :        2031 :     foreach(l, sock_paths)
                   +  + ]
     852                 :             :     {
     853                 :        1015 :         char       *sock_path = (char *) lfirst(l);
     854                 :             : 
     855                 :             :         /* Ignore any error. */
     856                 :        1015 :         (void) unlink(sock_path);
     857                 :             :     }
     858                 :             :     /* Since we're about to exit, no need to reclaim storage */
     859                 :        1016 : }
     860                 :             : 
     861                 :             : 
     862                 :             : /* --------------------------------
     863                 :             :  * Low-level I/O routines begin here.
     864                 :             :  *
     865                 :             :  * These routines communicate with a frontend client across a connection
     866                 :             :  * already established by the preceding routines.
     867                 :             :  * --------------------------------
     868                 :             :  */
     869                 :             : 
     870                 :             : /* --------------------------------
     871                 :             :  *            socket_set_nonblocking - set socket blocking/non-blocking
     872                 :             :  *
     873                 :             :  * Sets the socket non-blocking if nonblocking is true, or sets it
     874                 :             :  * blocking otherwise.
     875                 :             :  * --------------------------------
     876                 :             :  */
     877                 :             : static void
     878                 :     2858447 : socket_set_nonblocking(bool nonblocking)
     879                 :             : {
     880         [ -  + ]:     2858447 :     if (MyProcPort == NULL)
     881         [ #  # ]:           0 :         ereport(ERROR,
     882                 :             :                 (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
     883                 :             :                  errmsg("there is no client connection")));
     884                 :             : 
     885                 :     2858447 :     MyProcPort->noblock = nonblocking;
     886                 :     2858447 : }
     887                 :             : 
     888                 :             : /* --------------------------------
     889                 :             :  *      pq_recvbuf - load some bytes into the input buffer
     890                 :             :  *
     891                 :             :  *      returns 0 if OK, EOF if trouble
     892                 :             :  * --------------------------------
     893                 :             :  */
     894                 :             : static int
     895                 :      510608 : pq_recvbuf(void)
     896                 :             : {
     897         [ +  + ]:      510608 :     if (PqRecvPointer > 0)
     898                 :             :     {
     899         [ -  + ]:      495157 :         if (PqRecvLength > PqRecvPointer)
     900                 :             :         {
     901                 :             :             /* still some unread data, left-justify it in the buffer */
     902                 :           0 :             memmove(PqRecvBuffer, PqRecvBuffer + PqRecvPointer,
     903                 :           0 :                     PqRecvLength - PqRecvPointer);
     904                 :           0 :             PqRecvLength -= PqRecvPointer;
     905                 :           0 :             PqRecvPointer = 0;
     906                 :             :         }
     907                 :             :         else
     908                 :      495157 :             PqRecvLength = PqRecvPointer = 0;
     909                 :             :     }
     910                 :             : 
     911                 :             :     /* Ensure that we're in blocking mode */
     912                 :      510608 :     socket_set_nonblocking(false);
     913                 :             : 
     914                 :             :     /* Can fill buffer from PqRecvLength and upwards */
     915                 :             :     for (;;)
     916                 :           0 :     {
     917                 :             :         ssize_t     r;
     918                 :             : 
     919                 :      510608 :         errno = 0;
     920                 :             : 
     921                 :      510608 :         r = secure_read(MyProcPort, PqRecvBuffer + PqRecvLength,
     922                 :      510608 :                         PQ_RECV_BUFFER_SIZE - PqRecvLength);
     923                 :             : 
     924         [ -  + ]:      510582 :         if (r < 0)
     925                 :             :         {
     926         [ #  # ]:           0 :             if (errno == EINTR)
     927                 :           0 :                 continue;       /* Ok if interrupted */
     928                 :             : 
     929                 :             :             /*
     930                 :             :              * Careful: an ereport() that tries to write to the client would
     931                 :             :              * cause recursion to here, leading to stack overflow and core
     932                 :             :              * dump!  This message must go *only* to the postmaster log.
     933                 :             :              *
     934                 :             :              * If errno is zero, assume it's EOF and let the caller complain.
     935                 :             :              */
     936         [ #  # ]:           0 :             if (errno != 0)
     937         [ #  # ]:           0 :                 ereport(COMMERROR,
     938                 :             :                         (errcode_for_socket_access(),
     939                 :             :                          errmsg("could not receive data from client: %m")));
     940                 :           0 :             return EOF;
     941                 :             :         }
     942         [ +  + ]:      510582 :         if (r == 0)
     943                 :             :         {
     944                 :             :             /*
     945                 :             :              * EOF detected.  We used to write a log message here, but it's
     946                 :             :              * better to expect the ultimate caller to do that.
     947                 :             :              */
     948                 :          76 :             return EOF;
     949                 :             :         }
     950                 :             :         /* r contains number of bytes read, so just incr length */
     951                 :      510506 :         PqRecvLength += r;
     952                 :      510506 :         return 0;
     953                 :             :     }
     954                 :             : }
     955                 :             : 
     956                 :             : /* --------------------------------
     957                 :             :  *      pq_getbyte  - get a single byte from connection, or return EOF
     958                 :             :  * --------------------------------
     959                 :             :  */
     960                 :             : int
     961                 :      669901 : pq_getbyte(void)
     962                 :             : {
     963                 :             :     Assert(PqCommReadingMsg);
     964                 :             : 
     965         [ +  + ]:     1098114 :     while (PqRecvPointer >= PqRecvLength)
     966                 :             :     {
     967         [ +  + ]:      428298 :         if (pq_recvbuf())       /* If nothing in buffer, then recv some */
     968                 :          59 :             return EOF;         /* Failed to recv data */
     969                 :             :     }
     970                 :      669816 :     return (unsigned char) PqRecvBuffer[PqRecvPointer++];
     971                 :             : }
     972                 :             : 
     973                 :             : /* --------------------------------
     974                 :             :  *      pq_peekbyte     - peek at next byte from connection
     975                 :             :  *
     976                 :             :  *   Same as pq_getbyte() except we don't advance the pointer.
     977                 :             :  * --------------------------------
     978                 :             :  */
     979                 :             : int
     980                 :       15451 : pq_peekbyte(void)
     981                 :             : {
     982                 :             :     Assert(PqCommReadingMsg);
     983                 :             : 
     984         [ +  + ]:       30900 :     while (PqRecvPointer >= PqRecvLength)
     985                 :             :     {
     986         [ +  + ]:       15451 :         if (pq_recvbuf())       /* If nothing in buffer, then recv some */
     987                 :           2 :             return EOF;         /* Failed to recv data */
     988                 :             :     }
     989                 :       15449 :     return (unsigned char) PqRecvBuffer[PqRecvPointer];
     990                 :             : }
     991                 :             : 
     992                 :             : /* --------------------------------
     993                 :             :  *      pq_getbyte_if_available - get a single byte from connection,
     994                 :             :  *          if available
     995                 :             :  *
     996                 :             :  * The received byte is stored in *c. Returns 1 if a byte was read,
     997                 :             :  * 0 if no data was available, or EOF if trouble.
     998                 :             :  * --------------------------------
     999                 :             :  */
    1000                 :             : int
    1001                 :     1015812 : pq_getbyte_if_available(unsigned char *c)
    1002                 :             : {
    1003                 :             :     ssize_t     r;
    1004                 :             : 
    1005                 :             :     Assert(PqCommReadingMsg);
    1006                 :             : 
    1007         [ +  + ]:     1015812 :     if (PqRecvPointer < PqRecvLength)
    1008                 :             :     {
    1009                 :       50822 :         *c = PqRecvBuffer[PqRecvPointer++];
    1010                 :       50822 :         return 1;
    1011                 :             :     }
    1012                 :             : 
    1013                 :             :     /* Put the socket into non-blocking mode */
    1014                 :      964990 :     socket_set_nonblocking(true);
    1015                 :             : 
    1016                 :      964990 :     errno = 0;
    1017                 :             : 
    1018                 :      964990 :     r = secure_read(MyProcPort, c, 1);
    1019         [ +  + ]:      964990 :     if (r < 0)
    1020                 :             :     {
    1021                 :             :         /*
    1022                 :             :          * Ok if no data available without blocking or interrupted (though
    1023                 :             :          * EINTR really shouldn't happen with a non-blocking socket). Report
    1024                 :             :          * other errors.
    1025                 :             :          */
    1026   [ +  +  +  -  :      899897 :         if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
                   -  + ]
    1027                 :      899894 :             r = 0;
    1028                 :             :         else
    1029                 :             :         {
    1030                 :             :             /*
    1031                 :             :              * Careful: an ereport() that tries to write to the client would
    1032                 :             :              * cause recursion to here, leading to stack overflow and core
    1033                 :             :              * dump!  This message must go *only* to the postmaster log.
    1034                 :             :              *
    1035                 :             :              * If errno is zero, assume it's EOF and let the caller complain.
    1036                 :             :              */
    1037         [ +  - ]:           3 :             if (errno != 0)
    1038         [ +  - ]:           3 :                 ereport(COMMERROR,
    1039                 :             :                         (errcode_for_socket_access(),
    1040                 :             :                          errmsg("could not receive data from client: %m")));
    1041                 :           3 :             r = EOF;
    1042                 :             :         }
    1043                 :             :     }
    1044         [ +  + ]:       65093 :     else if (r == 0)
    1045                 :             :     {
    1046                 :             :         /* EOF detected */
    1047                 :          12 :         r = EOF;
    1048                 :             :     }
    1049                 :             : 
    1050                 :      964990 :     return r;
    1051                 :             : }
    1052                 :             : 
    1053                 :             : /* --------------------------------
    1054                 :             :  *      pq_getbytes     - get a known number of bytes from connection
    1055                 :             :  *
    1056                 :             :  *      returns 0 if OK, EOF if trouble
    1057                 :             :  * --------------------------------
    1058                 :             :  */
    1059                 :             : int
    1060                 :     1590671 : pq_getbytes(void *b, size_t len)
    1061                 :             : {
    1062                 :     1590671 :     char       *s = b;
    1063                 :             :     size_t      amount;
    1064                 :             : 
    1065                 :             :     Assert(PqCommReadingMsg);
    1066                 :             : 
    1067         [ +  + ]:     3182810 :     while (len > 0)
    1068                 :             :     {
    1069         [ +  + ]:     1658998 :         while (PqRecvPointer >= PqRecvLength)
    1070                 :             :         {
    1071         [ +  + ]:       66859 :             if (pq_recvbuf())   /* If nothing in buffer, then recv some */
    1072                 :          15 :                 return EOF;     /* Failed to recv data */
    1073                 :             :         }
    1074                 :     1592139 :         amount = PqRecvLength - PqRecvPointer;
    1075         [ +  + ]:     1592139 :         if (amount > len)
    1076                 :     1081643 :             amount = len;
    1077                 :     1592139 :         memcpy(s, PqRecvBuffer + PqRecvPointer, amount);
    1078                 :     1592139 :         PqRecvPointer += amount;
    1079                 :     1592139 :         s += amount;
    1080                 :     1592139 :         len -= amount;
    1081                 :             :     }
    1082                 :     1590656 :     return 0;
    1083                 :             : }
    1084                 :             : 
    1085                 :             : /* --------------------------------
    1086                 :             :  *      pq_discardbytes     - throw away a known number of bytes
    1087                 :             :  *
    1088                 :             :  *      same as pq_getbytes except we do not copy the data to anyplace.
    1089                 :             :  *      this is used for resynchronizing after read errors.
    1090                 :             :  *
    1091                 :             :  *      returns 0 if OK, EOF if trouble
    1092                 :             :  * --------------------------------
    1093                 :             :  */
    1094                 :             : static int
    1095                 :           0 : pq_discardbytes(size_t len)
    1096                 :             : {
    1097                 :             :     size_t      amount;
    1098                 :             : 
    1099                 :             :     Assert(PqCommReadingMsg);
    1100                 :             : 
    1101         [ #  # ]:           0 :     while (len > 0)
    1102                 :             :     {
    1103         [ #  # ]:           0 :         while (PqRecvPointer >= PqRecvLength)
    1104                 :             :         {
    1105         [ #  # ]:           0 :             if (pq_recvbuf())   /* If nothing in buffer, then recv some */
    1106                 :           0 :                 return EOF;     /* Failed to recv data */
    1107                 :             :         }
    1108                 :           0 :         amount = PqRecvLength - PqRecvPointer;
    1109         [ #  # ]:           0 :         if (amount > len)
    1110                 :           0 :             amount = len;
    1111                 :           0 :         PqRecvPointer += amount;
    1112                 :           0 :         len -= amount;
    1113                 :             :     }
    1114                 :           0 :     return 0;
    1115                 :             : }
    1116                 :             : 
    1117                 :             : /* --------------------------------
    1118                 :             :  *      pq_buffer_remaining_data    - return number of bytes in receive buffer
    1119                 :             :  *
    1120                 :             :  * This will *not* attempt to read more data. And reading up to that number of
    1121                 :             :  * bytes should not cause reading any more data either.
    1122                 :             :  * --------------------------------
    1123                 :             :  */
    1124                 :             : ssize_t
    1125                 :         454 : pq_buffer_remaining_data(void)
    1126                 :             : {
    1127                 :             :     Assert(PqRecvLength >= PqRecvPointer);
    1128                 :         454 :     return (PqRecvLength - PqRecvPointer);
    1129                 :             : }
    1130                 :             : 
    1131                 :             : 
    1132                 :             : /* --------------------------------
    1133                 :             :  *      pq_startmsgread - begin reading a message from the client.
    1134                 :             :  *
    1135                 :             :  *      This must be called before any of the pq_get* functions.
    1136                 :             :  * --------------------------------
    1137                 :             :  */
    1138                 :             : void
    1139                 :     1716899 : pq_startmsgread(void)
    1140                 :             : {
    1141                 :             :     /*
    1142                 :             :      * There shouldn't be a read active already, but let's check just to be
    1143                 :             :      * sure.
    1144                 :             :      */
    1145         [ -  + ]:     1716899 :     if (PqCommReadingMsg)
    1146         [ #  # ]:           0 :         ereport(FATAL,
    1147                 :             :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
    1148                 :             :                  errmsg("terminating connection because protocol synchronization was lost")));
    1149                 :             : 
    1150                 :     1716899 :     PqCommReadingMsg = true;
    1151                 :     1716899 : }
    1152                 :             : 
    1153                 :             : 
    1154                 :             : /* --------------------------------
    1155                 :             :  *      pq_endmsgread   - finish reading message.
    1156                 :             :  *
    1157                 :             :  *      This must be called after reading a message with pq_getbytes()
    1158                 :             :  *      and friends, to indicate that we have read the whole message.
    1159                 :             :  *      pq_getmessage() does this implicitly.
    1160                 :             :  * --------------------------------
    1161                 :             :  */
    1162                 :             : void
    1163                 :      931065 : pq_endmsgread(void)
    1164                 :             : {
    1165                 :             :     Assert(PqCommReadingMsg);
    1166                 :             : 
    1167                 :      931065 :     PqCommReadingMsg = false;
    1168                 :      931065 : }
    1169                 :             : 
    1170                 :             : /* --------------------------------
    1171                 :             :  *      pq_is_reading_msg - are we currently reading a message?
    1172                 :             :  *
    1173                 :             :  * This is used in error recovery at the outer idle loop to detect if we have
    1174                 :             :  * lost protocol sync, and need to terminate the connection. pq_startmsgread()
    1175                 :             :  * will check for that too, but it's nicer to detect it earlier.
    1176                 :             :  * --------------------------------
    1177                 :             :  */
    1178                 :             : bool
    1179                 :       31856 : pq_is_reading_msg(void)
    1180                 :             : {
    1181                 :       31856 :     return PqCommReadingMsg;
    1182                 :             : }
    1183                 :             : 
    1184                 :             : /* --------------------------------
    1185                 :             :  *      pq_getmessage   - get a message with length word from connection
    1186                 :             :  *
    1187                 :             :  *      The return value is placed in an expansible StringInfo, which has
    1188                 :             :  *      already been initialized by the caller.
    1189                 :             :  *      Only the message body is placed in the StringInfo; the length word
    1190                 :             :  *      is removed.  Also, s->cursor is initialized to zero for convenience
    1191                 :             :  *      in scanning the message contents.
    1192                 :             :  *
    1193                 :             :  *      maxlen is the upper limit on the length of the
    1194                 :             :  *      message we are willing to accept.  We abort the connection (by
    1195                 :             :  *      returning EOF) if client tries to send more than that.
    1196                 :             :  *
    1197                 :             :  *      returns 0 if OK, EOF if trouble
    1198                 :             :  * --------------------------------
    1199                 :             :  */
    1200                 :             : int
    1201                 :      785717 : pq_getmessage(StringInfo s, int maxlen)
    1202                 :             : {
    1203                 :             :     int32       len;
    1204                 :             : 
    1205                 :             :     Assert(PqCommReadingMsg);
    1206                 :             : 
    1207                 :      785717 :     resetStringInfo(s);
    1208                 :             : 
    1209                 :             :     /* Read message length word */
    1210         [ -  + ]:      785717 :     if (pq_getbytes(&len, 4) == EOF)
    1211                 :             :     {
    1212         [ #  # ]:           0 :         ereport(COMMERROR,
    1213                 :             :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
    1214                 :             :                  errmsg("unexpected EOF within message length word")));
    1215                 :           0 :         return EOF;
    1216                 :             :     }
    1217                 :             : 
    1218                 :      785717 :     len = pg_ntoh32(len);
    1219                 :             : 
    1220   [ +  -  -  + ]:      785717 :     if (len < 4 || len > maxlen)
    1221                 :             :     {
    1222         [ #  # ]:           0 :         ereport(COMMERROR,
    1223                 :             :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
    1224                 :             :                  errmsg("invalid message length")));
    1225                 :           0 :         return EOF;
    1226                 :             :     }
    1227                 :             : 
    1228                 :      785717 :     len -= 4;                   /* discount length itself */
    1229                 :             : 
    1230         [ +  + ]:      785717 :     if (len > 0)
    1231                 :             :     {
    1232                 :             :         /*
    1233                 :             :          * Allocate space for message.  If we run out of room (ridiculously
    1234                 :             :          * large message), we will elog(ERROR), but we want to discard the
    1235                 :             :          * message body so as not to lose communication sync.
    1236                 :             :          */
    1237         [ +  - ]:      757785 :         PG_TRY();
    1238                 :             :         {
    1239                 :      757785 :             enlargeStringInfo(s, len);
    1240                 :             :         }
    1241                 :           0 :         PG_CATCH();
    1242                 :             :         {
    1243         [ #  # ]:           0 :             if (pq_discardbytes(len) == EOF)
    1244         [ #  # ]:           0 :                 ereport(COMMERROR,
    1245                 :             :                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
    1246                 :             :                          errmsg("incomplete message from client")));
    1247                 :             : 
    1248                 :             :             /* we discarded the rest of the message so we're back in sync. */
    1249                 :           0 :             PqCommReadingMsg = false;
    1250                 :           0 :             PG_RE_THROW();
    1251                 :             :         }
    1252         [ -  + ]:      757785 :         PG_END_TRY();
    1253                 :             : 
    1254                 :             :         /* And grab the message */
    1255         [ -  + ]:      757785 :         if (pq_getbytes(s->data, len) == EOF)
    1256                 :             :         {
    1257         [ #  # ]:           0 :             ereport(COMMERROR,
    1258                 :             :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
    1259                 :             :                      errmsg("incomplete message from client")));
    1260                 :           0 :             return EOF;
    1261                 :             :         }
    1262                 :      757785 :         s->len = len;
    1263                 :             :         /* Place a trailing null per StringInfo convention */
    1264                 :      757785 :         s->data[len] = '\0';
    1265                 :             :     }
    1266                 :             : 
    1267                 :             :     /* finished reading the message. */
    1268                 :      785717 :     PqCommReadingMsg = false;
    1269                 :             : 
    1270                 :      785717 :     return 0;
    1271                 :             : }
    1272                 :             : 
    1273                 :             : 
    1274                 :             : static inline int
    1275                 :    23710512 : internal_putbytes(const void *b, size_t len)
    1276                 :             : {
    1277                 :    23710512 :     const char *s = b;
    1278                 :             : 
    1279         [ +  + ]:    47626859 :     while (len > 0)
    1280                 :             :     {
    1281                 :             :         /* If buffer is full, then flush it out */
    1282         [ +  + ]:    23916351 :         if (PqSendPointer >= PqSendBufferSize)
    1283                 :             :         {
    1284                 :      237834 :             socket_set_nonblocking(false);
    1285         [ +  + ]:      237834 :             if (internal_flush())
    1286                 :           2 :                 return EOF;
    1287                 :             :         }
    1288                 :             : 
    1289                 :             :         /*
    1290                 :             :          * If the buffer is empty and data length is larger than the buffer
    1291                 :             :          * size, send it without buffering.  Otherwise, copy as much data as
    1292                 :             :          * possible into the buffer.
    1293                 :             :          */
    1294   [ +  +  +  + ]:    23916349 :         if (len >= PqSendBufferSize && PqSendStart == PqSendPointer)
    1295                 :      128905 :         {
    1296                 :      128907 :             size_t      start = 0;
    1297                 :             : 
    1298                 :      128907 :             socket_set_nonblocking(false);
    1299         [ +  + ]:      128907 :             if (internal_flush_buffer(s, &start, &len))
    1300                 :           2 :                 return EOF;
    1301                 :             :         }
    1302                 :             :         else
    1303                 :             :         {
    1304                 :    23787442 :             size_t      amount = PqSendBufferSize - PqSendPointer;
    1305                 :             : 
    1306         [ +  + ]:    23787442 :             if (amount > len)
    1307                 :    23467571 :                 amount = len;
    1308                 :    23787442 :             memcpy(PqSendBuffer + PqSendPointer, s, amount);
    1309                 :    23787442 :             PqSendPointer += amount;
    1310                 :    23787442 :             s += amount;
    1311                 :    23787442 :             len -= amount;
    1312                 :             :         }
    1313                 :             :     }
    1314                 :             : 
    1315                 :    23710508 :     return 0;
    1316                 :             : }
    1317                 :             : 
    1318                 :             : /* --------------------------------
    1319                 :             :  *      socket_flush        - flush pending output
    1320                 :             :  *
    1321                 :             :  *      returns 0 if OK, EOF if trouble
    1322                 :             :  * --------------------------------
    1323                 :             :  */
    1324                 :             : static int
    1325                 :      648117 : socket_flush(void)
    1326                 :             : {
    1327                 :             :     int         res;
    1328                 :             : 
    1329                 :             :     /* No-op if reentrant call */
    1330         [ -  + ]:      648117 :     if (PqCommBusy)
    1331                 :           0 :         return 0;
    1332                 :      648117 :     PqCommBusy = true;
    1333                 :      648117 :     socket_set_nonblocking(false);
    1334                 :      648117 :     res = internal_flush();
    1335                 :      648117 :     PqCommBusy = false;
    1336                 :      648117 :     return res;
    1337                 :             : }
    1338                 :             : 
    1339                 :             : /* --------------------------------
    1340                 :             :  *      internal_flush - flush pending output
    1341                 :             :  *
    1342                 :             :  * Returns 0 if OK (meaning everything was sent, or operation would block
    1343                 :             :  * and the socket is in non-blocking mode), or EOF if trouble.
    1344                 :             :  * --------------------------------
    1345                 :             :  */
    1346                 :             : static inline int
    1347                 :     1253942 : internal_flush(void)
    1348                 :             : {
    1349                 :     1253942 :     return internal_flush_buffer(PqSendBuffer, &PqSendStart, &PqSendPointer);
    1350                 :             : }
    1351                 :             : 
    1352                 :             : /* --------------------------------
    1353                 :             :  *      internal_flush_buffer - flush the given buffer content
    1354                 :             :  *
    1355                 :             :  * Returns 0 if OK (meaning everything was sent, or operation would block
    1356                 :             :  * and the socket is in non-blocking mode), or EOF if trouble.
    1357                 :             :  * --------------------------------
    1358                 :             :  */
    1359                 :             : static pg_noinline int
    1360                 :     1382849 : internal_flush_buffer(const char *buf, size_t *start, size_t *end)
    1361                 :             : {
    1362                 :             :     static int  last_reported_send_errno = 0;
    1363                 :             : 
    1364                 :     1382849 :     const char *bufptr = buf + *start;
    1365                 :     1382849 :     const char *bufend = buf + *end;
    1366                 :             : 
    1367         [ +  + ]:     2754197 :     while (bufptr < bufend)
    1368                 :             :     {
    1369                 :             :         ssize_t     r;
    1370                 :             : 
    1371                 :     1414144 :         r = secure_write(MyProcPort, bufptr, bufend - bufptr);
    1372                 :             : 
    1373         [ +  + ]:     1414144 :         if (r <= 0)
    1374                 :             :         {
    1375         [ -  + ]:       42796 :             if (errno == EINTR)
    1376                 :           0 :                 continue;       /* Ok if we were interrupted */
    1377                 :             : 
    1378                 :             :             /*
    1379                 :             :              * Ok if no data writable without blocking, and the socket is in
    1380                 :             :              * non-blocking mode.
    1381                 :             :              */
    1382         [ +  + ]:       42796 :             if (errno == EAGAIN ||
    1383         [ -  + ]:          18 :                 errno == EWOULDBLOCK)
    1384                 :             :             {
    1385                 :       42778 :                 return 0;
    1386                 :             :             }
    1387                 :             : 
    1388                 :             :             /*
    1389                 :             :              * Careful: an ereport() that tries to write to the client would
    1390                 :             :              * cause recursion to here, leading to stack overflow and core
    1391                 :             :              * dump!  This message must go *only* to the postmaster log.
    1392                 :             :              *
    1393                 :             :              * If a client disconnects while we're in the midst of output, we
    1394                 :             :              * might write quite a bit of data before we get to a safe query
    1395                 :             :              * abort point.  So, suppress duplicate log messages.
    1396                 :             :              */
    1397         [ +  - ]:          18 :             if (errno != last_reported_send_errno)
    1398                 :             :             {
    1399                 :          18 :                 last_reported_send_errno = errno;
    1400         [ +  - ]:          18 :                 ereport(COMMERROR,
    1401                 :             :                         (errcode_for_socket_access(),
    1402                 :             :                          errmsg("could not send data to client: %m")));
    1403                 :             :             }
    1404                 :             : 
    1405                 :             :             /*
    1406                 :             :              * We drop the buffered data anyway so that processing can
    1407                 :             :              * continue, even though we'll probably quit soon. We also set a
    1408                 :             :              * flag that'll cause the next CHECK_FOR_INTERRUPTS to terminate
    1409                 :             :              * the connection.
    1410                 :             :              */
    1411                 :          18 :             *start = *end = 0;
    1412                 :          18 :             ClientConnectionLost = 1;
    1413                 :          18 :             InterruptPending = 1;
    1414                 :          18 :             return EOF;
    1415                 :             :         }
    1416                 :             : 
    1417                 :     1371348 :         last_reported_send_errno = 0;   /* reset after any successful send */
    1418                 :     1371348 :         bufptr += r;
    1419                 :     1371348 :         *start += r;
    1420                 :             :     }
    1421                 :             : 
    1422                 :     1340053 :     *start = *end = 0;
    1423                 :     1340053 :     return 0;
    1424                 :             : }
    1425                 :             : 
    1426                 :             : /* --------------------------------
    1427                 :             :  *      pq_flush_if_writable - flush pending output if writable without blocking
    1428                 :             :  *
    1429                 :             :  * Returns 0 if OK, or EOF if trouble.
    1430                 :             :  * --------------------------------
    1431                 :             :  */
    1432                 :             : static int
    1433                 :     1100717 : socket_flush_if_writable(void)
    1434                 :             : {
    1435                 :             :     int         res;
    1436                 :             : 
    1437                 :             :     /* Quick exit if nothing to do */
    1438         [ +  + ]:     1100717 :     if (PqSendPointer == PqSendStart)
    1439                 :      732726 :         return 0;
    1440                 :             : 
    1441                 :             :     /* No-op if reentrant call */
    1442         [ -  + ]:      367991 :     if (PqCommBusy)
    1443                 :           0 :         return 0;
    1444                 :             : 
    1445                 :             :     /* Temporarily put the socket into non-blocking mode */
    1446                 :      367991 :     socket_set_nonblocking(true);
    1447                 :             : 
    1448                 :      367991 :     PqCommBusy = true;
    1449                 :      367991 :     res = internal_flush();
    1450                 :      367991 :     PqCommBusy = false;
    1451                 :      367991 :     return res;
    1452                 :             : }
    1453                 :             : 
    1454                 :             : /* --------------------------------
    1455                 :             :  *  socket_is_send_pending  - is there any pending data in the output buffer?
    1456                 :             :  * --------------------------------
    1457                 :             :  */
    1458                 :             : static bool
    1459                 :     2120279 : socket_is_send_pending(void)
    1460                 :             : {
    1461                 :     2120279 :     return (PqSendStart < PqSendPointer);
    1462                 :             : }
    1463                 :             : 
    1464                 :             : /* --------------------------------
    1465                 :             :  * Message-level I/O routines begin here.
    1466                 :             :  * --------------------------------
    1467                 :             :  */
    1468                 :             : 
    1469                 :             : 
    1470                 :             : /* --------------------------------
    1471                 :             :  *      socket_putmessage - send a normal message (suppressed in COPY OUT mode)
    1472                 :             :  *
    1473                 :             :  *      msgtype is a message type code to place before the message body.
    1474                 :             :  *
    1475                 :             :  *      len is the length of the message body data at *s.  A message length
    1476                 :             :  *      word (equal to len+4 because it counts itself too) is inserted by this
    1477                 :             :  *      routine.
    1478                 :             :  *
    1479                 :             :  *      We suppress messages generated while pqcomm.c is busy.  This
    1480                 :             :  *      avoids any possibility of messages being inserted within other
    1481                 :             :  *      messages.  The only known trouble case arises if SIGQUIT occurs
    1482                 :             :  *      during a pqcomm.c routine --- quickdie() will try to send a warning
    1483                 :             :  *      message, and the most reasonable approach seems to be to drop it.
    1484                 :             :  *
    1485                 :             :  *      returns 0 if OK, EOF if trouble
    1486                 :             :  * --------------------------------
    1487                 :             :  */
    1488                 :             : static int
    1489                 :     7903504 : socket_putmessage(char msgtype, const char *s, size_t len)
    1490                 :             : {
    1491                 :             :     uint32      n32;
    1492                 :             : 
    1493                 :             :     Assert(msgtype != 0);
    1494                 :             : 
    1495         [ -  + ]:     7903504 :     if (PqCommBusy)
    1496                 :           0 :         return 0;
    1497                 :     7903504 :     PqCommBusy = true;
    1498         [ -  + ]:     7903504 :     if (internal_putbytes(&msgtype, 1))
    1499                 :           0 :         goto fail;
    1500                 :             : 
    1501                 :     7903504 :     n32 = pg_hton32((uint32) (len + 4));
    1502         [ -  + ]:     7903504 :     if (internal_putbytes(&n32, 4))
    1503                 :           0 :         goto fail;
    1504                 :             : 
    1505         [ +  + ]:     7903504 :     if (internal_putbytes(s, len))
    1506                 :           4 :         goto fail;
    1507                 :     7903500 :     PqCommBusy = false;
    1508                 :     7903500 :     return 0;
    1509                 :             : 
    1510                 :           4 : fail:
    1511                 :           4 :     PqCommBusy = false;
    1512                 :           4 :     return EOF;
    1513                 :             : }
    1514                 :             : 
    1515                 :             : /* --------------------------------
    1516                 :             :  *      pq_putmessage_noblock   - like pq_putmessage, but never blocks
    1517                 :             :  *
    1518                 :             :  *      If the output buffer is too small to hold the message, the buffer
    1519                 :             :  *      is enlarged.
    1520                 :             :  */
    1521                 :             : static void
    1522                 :      325149 : socket_putmessage_noblock(char msgtype, const char *s, size_t len)
    1523                 :             : {
    1524                 :             :     int         res PG_USED_FOR_ASSERTS_ONLY;
    1525                 :             :     int         required;
    1526                 :             : 
    1527                 :             :     /*
    1528                 :             :      * Ensure we have enough space in the output buffer for the message header
    1529                 :             :      * as well as the message itself.
    1530                 :             :      */
    1531                 :      325149 :     required = PqSendPointer + 1 + 4 + len;
    1532         [ +  + ]:      325149 :     if (required > PqSendBufferSize)
    1533                 :             :     {
    1534                 :         592 :         PqSendBuffer = repalloc(PqSendBuffer, required);
    1535                 :         592 :         PqSendBufferSize = required;
    1536                 :             :     }
    1537                 :      325149 :     res = socket_putmessage(msgtype, s, len);
    1538                 :             :     Assert(res == 0);           /* should not fail when the message fits in
    1539                 :             :                                  * buffer */
    1540                 :      325149 : }
    1541                 :             : 
    1542                 :             : /* --------------------------------
    1543                 :             :  *      pq_putmessage_v2 - send a message in protocol version 2
    1544                 :             :  *
    1545                 :             :  *      msgtype is a message type code to place before the message body.
    1546                 :             :  *
    1547                 :             :  *      We no longer support protocol version 2, but we have kept this
    1548                 :             :  *      function so that if a client tries to connect with protocol version 2,
    1549                 :             :  *      as a courtesy we can still send the "unsupported protocol version"
    1550                 :             :  *      error to the client in the old format.
    1551                 :             :  *
    1552                 :             :  *      Like in pq_putmessage(), we suppress messages generated while
    1553                 :             :  *      pqcomm.c is busy.
    1554                 :             :  *
    1555                 :             :  *      returns 0 if OK, EOF if trouble
    1556                 :             :  * --------------------------------
    1557                 :             :  */
    1558                 :             : int
    1559                 :           0 : pq_putmessage_v2(char msgtype, const char *s, size_t len)
    1560                 :             : {
    1561                 :             :     Assert(msgtype != 0);
    1562                 :             : 
    1563         [ #  # ]:           0 :     if (PqCommBusy)
    1564                 :           0 :         return 0;
    1565                 :           0 :     PqCommBusy = true;
    1566         [ #  # ]:           0 :     if (internal_putbytes(&msgtype, 1))
    1567                 :           0 :         goto fail;
    1568                 :             : 
    1569         [ #  # ]:           0 :     if (internal_putbytes(s, len))
    1570                 :           0 :         goto fail;
    1571                 :           0 :     PqCommBusy = false;
    1572                 :           0 :     return 0;
    1573                 :             : 
    1574                 :           0 : fail:
    1575                 :           0 :     PqCommBusy = false;
    1576                 :           0 :     return EOF;
    1577                 :             : }
    1578                 :             : 
    1579                 :             : /*
    1580                 :             :  * Support for TCP Keepalive parameters
    1581                 :             :  */
    1582                 :             : 
    1583                 :             : /*
    1584                 :             :  * On Windows, we need to set both idle and interval at the same time.
    1585                 :             :  * We also cannot reset them to the default (setting to zero will
    1586                 :             :  * actually set them to zero, not default), therefore we fallback to
    1587                 :             :  * the out-of-the-box default instead.
    1588                 :             :  */
    1589                 :             : #if defined(WIN32) && defined(SIO_KEEPALIVE_VALS)
    1590                 :             : static int
    1591                 :             : pq_setkeepaliveswin32(Port *port, int idle, int interval)
    1592                 :             : {
    1593                 :             :     struct tcp_keepalive ka;
    1594                 :             :     DWORD       retsize;
    1595                 :             : 
    1596                 :             :     if (idle <= 0)
    1597                 :             :         idle = 2 * 60 * 60;     /* default = 2 hours */
    1598                 :             :     if (interval <= 0)
    1599                 :             :         interval = 1;           /* default = 1 second */
    1600                 :             : 
    1601                 :             :     ka.onoff = 1;
    1602                 :             :     ka.keepalivetime = idle * 1000;
    1603                 :             :     ka.keepaliveinterval = interval * 1000;
    1604                 :             : 
    1605                 :             :     if (WSAIoctl(port->sock,
    1606                 :             :                  SIO_KEEPALIVE_VALS,
    1607                 :             :                  (LPVOID) &ka,
    1608                 :             :                  sizeof(ka),
    1609                 :             :                  NULL,
    1610                 :             :                  0,
    1611                 :             :                  &retsize,
    1612                 :             :                  NULL,
    1613                 :             :                  NULL)
    1614                 :             :         != 0)
    1615                 :             :     {
    1616                 :             :         ereport(LOG,
    1617                 :             :                 (errmsg("%s(%s) failed: error code %d",
    1618                 :             :                         "WSAIoctl", "SIO_KEEPALIVE_VALS", WSAGetLastError())));
    1619                 :             :         return STATUS_ERROR;
    1620                 :             :     }
    1621                 :             :     if (port->keepalives_idle != idle)
    1622                 :             :         port->keepalives_idle = idle;
    1623                 :             :     if (port->keepalives_interval != interval)
    1624                 :             :         port->keepalives_interval = interval;
    1625                 :             :     return STATUS_OK;
    1626                 :             : }
    1627                 :             : #endif
    1628                 :             : 
    1629                 :             : int
    1630                 :        1926 : pq_getkeepalivesidle(Port *port)
    1631                 :             : {
    1632                 :             : #if defined(PG_TCP_KEEPALIVE_IDLE) || defined(SIO_KEEPALIVE_VALS)
    1633   [ +  -  +  - ]:        1926 :     if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
    1634                 :        1926 :         return 0;
    1635                 :             : 
    1636         [ #  # ]:           0 :     if (port->keepalives_idle != 0)
    1637                 :           0 :         return port->keepalives_idle;
    1638                 :             : 
    1639         [ #  # ]:           0 :     if (port->default_keepalives_idle == 0)
    1640                 :             :     {
    1641                 :             : #ifndef WIN32
    1642                 :           0 :         socklen_t   size = sizeof(port->default_keepalives_idle);
    1643                 :             : 
    1644         [ #  # ]:           0 :         if (getsockopt(port->sock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
    1645                 :           0 :                        (char *) &port->default_keepalives_idle,
    1646                 :             :                        &size) < 0)
    1647                 :             :         {
    1648         [ #  # ]:           0 :             ereport(LOG,
    1649                 :             :                     (errmsg("%s(%s) failed: %m", "getsockopt", PG_TCP_KEEPALIVE_IDLE_STR)));
    1650                 :           0 :             port->default_keepalives_idle = -1; /* don't know */
    1651                 :             :         }
    1652                 :             : #else                           /* WIN32 */
    1653                 :             :         /* We can't get the defaults on Windows, so return "don't know" */
    1654                 :             :         port->default_keepalives_idle = -1;
    1655                 :             : #endif                          /* WIN32 */
    1656                 :             :     }
    1657                 :             : 
    1658                 :           0 :     return port->default_keepalives_idle;
    1659                 :             : #else
    1660                 :             :     return 0;
    1661                 :             : #endif
    1662                 :             : }
    1663                 :             : 
    1664                 :             : int
    1665                 :        1645 : pq_setkeepalivesidle(int idle, Port *port)
    1666                 :             : {
    1667   [ +  +  -  + ]:        1645 :     if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
    1668                 :        1311 :         return STATUS_OK;
    1669                 :             : 
    1670                 :             : /* check SIO_KEEPALIVE_VALS here, not just WIN32, as some toolchains lack it */
    1671                 :             : #if defined(PG_TCP_KEEPALIVE_IDLE) || defined(SIO_KEEPALIVE_VALS)
    1672         [ +  - ]:         334 :     if (idle == port->keepalives_idle)
    1673                 :         334 :         return STATUS_OK;
    1674                 :             : 
    1675                 :             : #ifndef WIN32
    1676         [ #  # ]:           0 :     if (port->default_keepalives_idle <= 0)
    1677                 :             :     {
    1678         [ #  # ]:           0 :         if (pq_getkeepalivesidle(port) < 0)
    1679                 :             :         {
    1680         [ #  # ]:           0 :             if (idle == 0)
    1681                 :           0 :                 return STATUS_OK;   /* default is set but unknown */
    1682                 :             :             else
    1683                 :           0 :                 return STATUS_ERROR;
    1684                 :             :         }
    1685                 :             :     }
    1686                 :             : 
    1687         [ #  # ]:           0 :     if (idle == 0)
    1688                 :           0 :         idle = port->default_keepalives_idle;
    1689                 :             : 
    1690         [ #  # ]:           0 :     if (setsockopt(port->sock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
    1691                 :             :                    (char *) &idle, sizeof(idle)) < 0)
    1692                 :             :     {
    1693         [ #  # ]:           0 :         ereport(LOG,
    1694                 :             :                 (errmsg("%s(%s) failed: %m", "setsockopt", PG_TCP_KEEPALIVE_IDLE_STR)));
    1695                 :           0 :         return STATUS_ERROR;
    1696                 :             :     }
    1697                 :             : 
    1698                 :           0 :     port->keepalives_idle = idle;
    1699                 :             : #else                           /* WIN32 */
    1700                 :             :     return pq_setkeepaliveswin32(port, idle, port->keepalives_interval);
    1701                 :             : #endif
    1702                 :             : #else
    1703                 :             :     if (idle != 0)
    1704                 :             :     {
    1705                 :             :         ereport(LOG,
    1706                 :             :                 (errmsg("setting the keepalive idle time is not supported")));
    1707                 :             :         return STATUS_ERROR;
    1708                 :             :     }
    1709                 :             : #endif
    1710                 :             : 
    1711                 :           0 :     return STATUS_OK;
    1712                 :             : }
    1713                 :             : 
    1714                 :             : int
    1715                 :        1926 : pq_getkeepalivesinterval(Port *port)
    1716                 :             : {
    1717                 :             : #if defined(TCP_KEEPINTVL) || defined(SIO_KEEPALIVE_VALS)
    1718   [ +  -  +  - ]:        1926 :     if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
    1719                 :        1926 :         return 0;
    1720                 :             : 
    1721         [ #  # ]:           0 :     if (port->keepalives_interval != 0)
    1722                 :           0 :         return port->keepalives_interval;
    1723                 :             : 
    1724         [ #  # ]:           0 :     if (port->default_keepalives_interval == 0)
    1725                 :             :     {
    1726                 :             : #ifndef WIN32
    1727                 :           0 :         socklen_t   size = sizeof(port->default_keepalives_interval);
    1728                 :             : 
    1729         [ #  # ]:           0 :         if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPINTVL,
    1730                 :           0 :                        (char *) &port->default_keepalives_interval,
    1731                 :             :                        &size) < 0)
    1732                 :             :         {
    1733         [ #  # ]:           0 :             ereport(LOG,
    1734                 :             :                     (errmsg("%s(%s) failed: %m", "getsockopt", "TCP_KEEPINTVL")));
    1735                 :           0 :             port->default_keepalives_interval = -1; /* don't know */
    1736                 :             :         }
    1737                 :             : #else
    1738                 :             :         /* We can't get the defaults on Windows, so return "don't know" */
    1739                 :             :         port->default_keepalives_interval = -1;
    1740                 :             : #endif                          /* WIN32 */
    1741                 :             :     }
    1742                 :             : 
    1743                 :           0 :     return port->default_keepalives_interval;
    1744                 :             : #else
    1745                 :             :     return 0;
    1746                 :             : #endif
    1747                 :             : }
    1748                 :             : 
    1749                 :             : int
    1750                 :        1645 : pq_setkeepalivesinterval(int interval, Port *port)
    1751                 :             : {
    1752   [ +  +  -  + ]:        1645 :     if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
    1753                 :        1311 :         return STATUS_OK;
    1754                 :             : 
    1755                 :             : #if defined(TCP_KEEPINTVL) || defined(SIO_KEEPALIVE_VALS)
    1756         [ +  - ]:         334 :     if (interval == port->keepalives_interval)
    1757                 :         334 :         return STATUS_OK;
    1758                 :             : 
    1759                 :             : #ifndef WIN32
    1760         [ #  # ]:           0 :     if (port->default_keepalives_interval <= 0)
    1761                 :             :     {
    1762         [ #  # ]:           0 :         if (pq_getkeepalivesinterval(port) < 0)
    1763                 :             :         {
    1764         [ #  # ]:           0 :             if (interval == 0)
    1765                 :           0 :                 return STATUS_OK;   /* default is set but unknown */
    1766                 :             :             else
    1767                 :           0 :                 return STATUS_ERROR;
    1768                 :             :         }
    1769                 :             :     }
    1770                 :             : 
    1771         [ #  # ]:           0 :     if (interval == 0)
    1772                 :           0 :         interval = port->default_keepalives_interval;
    1773                 :             : 
    1774         [ #  # ]:           0 :     if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPINTVL,
    1775                 :             :                    (char *) &interval, sizeof(interval)) < 0)
    1776                 :             :     {
    1777         [ #  # ]:           0 :         ereport(LOG,
    1778                 :             :                 (errmsg("%s(%s) failed: %m", "setsockopt", "TCP_KEEPINTVL")));
    1779                 :           0 :         return STATUS_ERROR;
    1780                 :             :     }
    1781                 :             : 
    1782                 :           0 :     port->keepalives_interval = interval;
    1783                 :             : #else                           /* WIN32 */
    1784                 :             :     return pq_setkeepaliveswin32(port, port->keepalives_idle, interval);
    1785                 :             : #endif
    1786                 :             : #else
    1787                 :             :     if (interval != 0)
    1788                 :             :     {
    1789                 :             :         ereport(LOG,
    1790                 :             :                 (errmsg("%s(%s) not supported", "setsockopt", "TCP_KEEPINTVL")));
    1791                 :             :         return STATUS_ERROR;
    1792                 :             :     }
    1793                 :             : #endif
    1794                 :             : 
    1795                 :           0 :     return STATUS_OK;
    1796                 :             : }
    1797                 :             : 
    1798                 :             : int
    1799                 :        1926 : pq_getkeepalivescount(Port *port)
    1800                 :             : {
    1801                 :             : #ifdef TCP_KEEPCNT
    1802   [ +  -  +  - ]:        1926 :     if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
    1803                 :        1926 :         return 0;
    1804                 :             : 
    1805         [ #  # ]:           0 :     if (port->keepalives_count != 0)
    1806                 :           0 :         return port->keepalives_count;
    1807                 :             : 
    1808         [ #  # ]:           0 :     if (port->default_keepalives_count == 0)
    1809                 :             :     {
    1810                 :           0 :         socklen_t   size = sizeof(port->default_keepalives_count);
    1811                 :             : 
    1812         [ #  # ]:           0 :         if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPCNT,
    1813                 :           0 :                        (char *) &port->default_keepalives_count,
    1814                 :             :                        &size) < 0)
    1815                 :             :         {
    1816         [ #  # ]:           0 :             ereport(LOG,
    1817                 :             :                     (errmsg("%s(%s) failed: %m", "getsockopt", "TCP_KEEPCNT")));
    1818                 :           0 :             port->default_keepalives_count = -1; /* don't know */
    1819                 :             :         }
    1820                 :             :     }
    1821                 :             : 
    1822                 :           0 :     return port->default_keepalives_count;
    1823                 :             : #else
    1824                 :             :     return 0;
    1825                 :             : #endif
    1826                 :             : }
    1827                 :             : 
    1828                 :             : int
    1829                 :        1645 : pq_setkeepalivescount(int count, Port *port)
    1830                 :             : {
    1831   [ +  +  -  + ]:        1645 :     if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
    1832                 :        1311 :         return STATUS_OK;
    1833                 :             : 
    1834                 :             : #ifdef TCP_KEEPCNT
    1835         [ +  - ]:         334 :     if (count == port->keepalives_count)
    1836                 :         334 :         return STATUS_OK;
    1837                 :             : 
    1838         [ #  # ]:           0 :     if (port->default_keepalives_count <= 0)
    1839                 :             :     {
    1840         [ #  # ]:           0 :         if (pq_getkeepalivescount(port) < 0)
    1841                 :             :         {
    1842         [ #  # ]:           0 :             if (count == 0)
    1843                 :           0 :                 return STATUS_OK;   /* default is set but unknown */
    1844                 :             :             else
    1845                 :           0 :                 return STATUS_ERROR;
    1846                 :             :         }
    1847                 :             :     }
    1848                 :             : 
    1849         [ #  # ]:           0 :     if (count == 0)
    1850                 :           0 :         count = port->default_keepalives_count;
    1851                 :             : 
    1852         [ #  # ]:           0 :     if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPCNT,
    1853                 :             :                    (char *) &count, sizeof(count)) < 0)
    1854                 :             :     {
    1855         [ #  # ]:           0 :         ereport(LOG,
    1856                 :             :                 (errmsg("%s(%s) failed: %m", "setsockopt", "TCP_KEEPCNT")));
    1857                 :           0 :         return STATUS_ERROR;
    1858                 :             :     }
    1859                 :             : 
    1860                 :           0 :     port->keepalives_count = count;
    1861                 :             : #else
    1862                 :             :     if (count != 0)
    1863                 :             :     {
    1864                 :             :         ereport(LOG,
    1865                 :             :                 (errmsg("%s(%s) not supported", "setsockopt", "TCP_KEEPCNT")));
    1866                 :             :         return STATUS_ERROR;
    1867                 :             :     }
    1868                 :             : #endif
    1869                 :             : 
    1870                 :           0 :     return STATUS_OK;
    1871                 :             : }
    1872                 :             : 
    1873                 :             : int
    1874                 :        1926 : pq_gettcpusertimeout(Port *port)
    1875                 :             : {
    1876                 :             : #ifdef TCP_USER_TIMEOUT
    1877   [ +  -  +  - ]:        1926 :     if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
    1878                 :        1926 :         return 0;
    1879                 :             : 
    1880         [ #  # ]:           0 :     if (port->tcp_user_timeout != 0)
    1881                 :           0 :         return port->tcp_user_timeout;
    1882                 :             : 
    1883         [ #  # ]:           0 :     if (port->default_tcp_user_timeout == 0)
    1884                 :             :     {
    1885                 :           0 :         socklen_t   size = sizeof(port->default_tcp_user_timeout);
    1886                 :             : 
    1887         [ #  # ]:           0 :         if (getsockopt(port->sock, IPPROTO_TCP, TCP_USER_TIMEOUT,
    1888                 :           0 :                        (char *) &port->default_tcp_user_timeout,
    1889                 :             :                        &size) < 0)
    1890                 :             :         {
    1891         [ #  # ]:           0 :             ereport(LOG,
    1892                 :             :                     (errmsg("%s(%s) failed: %m", "getsockopt", "TCP_USER_TIMEOUT")));
    1893                 :           0 :             port->default_tcp_user_timeout = -1; /* don't know */
    1894                 :             :         }
    1895                 :             :     }
    1896                 :             : 
    1897                 :           0 :     return port->default_tcp_user_timeout;
    1898                 :             : #else
    1899                 :             :     return 0;
    1900                 :             : #endif
    1901                 :             : }
    1902                 :             : 
    1903                 :             : int
    1904                 :        1645 : pq_settcpusertimeout(int timeout, Port *port)
    1905                 :             : {
    1906   [ +  +  -  + ]:        1645 :     if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
    1907                 :        1311 :         return STATUS_OK;
    1908                 :             : 
    1909                 :             : #ifdef TCP_USER_TIMEOUT
    1910         [ +  - ]:         334 :     if (timeout == port->tcp_user_timeout)
    1911                 :         334 :         return STATUS_OK;
    1912                 :             : 
    1913         [ #  # ]:           0 :     if (port->default_tcp_user_timeout <= 0)
    1914                 :             :     {
    1915         [ #  # ]:           0 :         if (pq_gettcpusertimeout(port) < 0)
    1916                 :             :         {
    1917         [ #  # ]:           0 :             if (timeout == 0)
    1918                 :           0 :                 return STATUS_OK;   /* default is set but unknown */
    1919                 :             :             else
    1920                 :           0 :                 return STATUS_ERROR;
    1921                 :             :         }
    1922                 :             :     }
    1923                 :             : 
    1924         [ #  # ]:           0 :     if (timeout == 0)
    1925                 :           0 :         timeout = port->default_tcp_user_timeout;
    1926                 :             : 
    1927         [ #  # ]:           0 :     if (setsockopt(port->sock, IPPROTO_TCP, TCP_USER_TIMEOUT,
    1928                 :             :                    (char *) &timeout, sizeof(timeout)) < 0)
    1929                 :             :     {
    1930         [ #  # ]:           0 :         ereport(LOG,
    1931                 :             :                 (errmsg("%s(%s) failed: %m", "setsockopt", "TCP_USER_TIMEOUT")));
    1932                 :           0 :         return STATUS_ERROR;
    1933                 :             :     }
    1934                 :             : 
    1935                 :           0 :     port->tcp_user_timeout = timeout;
    1936                 :             : #else
    1937                 :             :     if (timeout != 0)
    1938                 :             :     {
    1939                 :             :         ereport(LOG,
    1940                 :             :                 (errmsg("%s(%s) not supported", "setsockopt", "TCP_USER_TIMEOUT")));
    1941                 :             :         return STATUS_ERROR;
    1942                 :             :     }
    1943                 :             : #endif
    1944                 :             : 
    1945                 :           0 :     return STATUS_OK;
    1946                 :             : }
    1947                 :             : 
    1948                 :             : /*
    1949                 :             :  * GUC assign_hook for tcp_keepalives_idle
    1950                 :             :  */
    1951                 :             : void
    1952                 :        1311 : assign_tcp_keepalives_idle(int newval, void *extra)
    1953                 :             : {
    1954                 :             :     /*
    1955                 :             :      * The kernel API provides no way to test a value without setting it; and
    1956                 :             :      * once we set it we might fail to unset it.  So there seems little point
    1957                 :             :      * in fully implementing the check-then-assign GUC API for these
    1958                 :             :      * variables.  Instead we just do the assignment on demand.
    1959                 :             :      * pq_setkeepalivesidle reports any problems via ereport(LOG).
    1960                 :             :      *
    1961                 :             :      * This approach means that the GUC value might have little to do with the
    1962                 :             :      * actual kernel value, so we use a show_hook that retrieves the kernel
    1963                 :             :      * value rather than trusting GUC's copy.
    1964                 :             :      */
    1965                 :        1311 :     (void) pq_setkeepalivesidle(newval, MyProcPort);
    1966                 :        1311 : }
    1967                 :             : 
    1968                 :             : /*
    1969                 :             :  * GUC show_hook for tcp_keepalives_idle
    1970                 :             :  */
    1971                 :             : const char *
    1972                 :        1926 : show_tcp_keepalives_idle(void)
    1973                 :             : {
    1974                 :             :     /* See comments in assign_tcp_keepalives_idle */
    1975                 :             :     static char nbuf[16];
    1976                 :             : 
    1977                 :        1926 :     snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesidle(MyProcPort));
    1978                 :        1926 :     return nbuf;
    1979                 :             : }
    1980                 :             : 
    1981                 :             : /*
    1982                 :             :  * GUC assign_hook for tcp_keepalives_interval
    1983                 :             :  */
    1984                 :             : void
    1985                 :        1311 : assign_tcp_keepalives_interval(int newval, void *extra)
    1986                 :             : {
    1987                 :             :     /* See comments in assign_tcp_keepalives_idle */
    1988                 :        1311 :     (void) pq_setkeepalivesinterval(newval, MyProcPort);
    1989                 :        1311 : }
    1990                 :             : 
    1991                 :             : /*
    1992                 :             :  * GUC show_hook for tcp_keepalives_interval
    1993                 :             :  */
    1994                 :             : const char *
    1995                 :        1926 : show_tcp_keepalives_interval(void)
    1996                 :             : {
    1997                 :             :     /* See comments in assign_tcp_keepalives_idle */
    1998                 :             :     static char nbuf[16];
    1999                 :             : 
    2000                 :        1926 :     snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesinterval(MyProcPort));
    2001                 :        1926 :     return nbuf;
    2002                 :             : }
    2003                 :             : 
    2004                 :             : /*
    2005                 :             :  * GUC assign_hook for tcp_keepalives_count
    2006                 :             :  */
    2007                 :             : void
    2008                 :        1311 : assign_tcp_keepalives_count(int newval, void *extra)
    2009                 :             : {
    2010                 :             :     /* See comments in assign_tcp_keepalives_idle */
    2011                 :        1311 :     (void) pq_setkeepalivescount(newval, MyProcPort);
    2012                 :        1311 : }
    2013                 :             : 
    2014                 :             : /*
    2015                 :             :  * GUC show_hook for tcp_keepalives_count
    2016                 :             :  */
    2017                 :             : const char *
    2018                 :        1926 : show_tcp_keepalives_count(void)
    2019                 :             : {
    2020                 :             :     /* See comments in assign_tcp_keepalives_idle */
    2021                 :             :     static char nbuf[16];
    2022                 :             : 
    2023                 :        1926 :     snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivescount(MyProcPort));
    2024                 :        1926 :     return nbuf;
    2025                 :             : }
    2026                 :             : 
    2027                 :             : /*
    2028                 :             :  * GUC assign_hook for tcp_user_timeout
    2029                 :             :  */
    2030                 :             : void
    2031                 :        1311 : assign_tcp_user_timeout(int newval, void *extra)
    2032                 :             : {
    2033                 :             :     /* See comments in assign_tcp_keepalives_idle */
    2034                 :        1311 :     (void) pq_settcpusertimeout(newval, MyProcPort);
    2035                 :        1311 : }
    2036                 :             : 
    2037                 :             : /*
    2038                 :             :  * GUC show_hook for tcp_user_timeout
    2039                 :             :  */
    2040                 :             : const char *
    2041                 :        1926 : show_tcp_user_timeout(void)
    2042                 :             : {
    2043                 :             :     /* See comments in assign_tcp_keepalives_idle */
    2044                 :             :     static char nbuf[16];
    2045                 :             : 
    2046                 :        1926 :     snprintf(nbuf, sizeof(nbuf), "%d", pq_gettcpusertimeout(MyProcPort));
    2047                 :        1926 :     return nbuf;
    2048                 :             : }
    2049                 :             : 
    2050                 :             : /*
    2051                 :             :  * Check if the client is still connected.
    2052                 :             :  */
    2053                 :             : bool
    2054                 :           0 : pq_check_connection(void)
    2055                 :             : {
    2056                 :             :     WaitEvent   events[FeBeWaitSetNEvents];
    2057                 :             :     int         rc;
    2058                 :             : 
    2059                 :             :     /*
    2060                 :             :      * It's OK to modify the socket event filter without restoring, because
    2061                 :             :      * all FeBeWaitSet socket wait sites do the same.
    2062                 :             :      */
    2063                 :           0 :     ModifyWaitEvent(FeBeWaitSet, FeBeWaitSetSocketPos, WL_SOCKET_CLOSED, NULL);
    2064                 :             : 
    2065                 :           0 : retry:
    2066                 :           0 :     rc = WaitEventSetWait(FeBeWaitSet, 0, events, lengthof(events), 0);
    2067         [ #  # ]:           0 :     for (int i = 0; i < rc; ++i)
    2068                 :             :     {
    2069         [ #  # ]:           0 :         if (events[i].events & WL_SOCKET_CLOSED)
    2070                 :           0 :             return false;
    2071         [ #  # ]:           0 :         if (events[i].events & WL_LATCH_SET)
    2072                 :             :         {
    2073                 :             :             /*
    2074                 :             :              * A latch event might be preventing other events from being
    2075                 :             :              * reported.  Reset it and poll again.  No need to restore it
    2076                 :             :              * because no code should expect latches to survive across
    2077                 :             :              * CHECK_FOR_INTERRUPTS().
    2078                 :             :              */
    2079                 :           0 :             ResetLatch(MyLatch);
    2080                 :           0 :             goto retry;
    2081                 :             :         }
    2082                 :             :     }
    2083                 :             : 
    2084                 :           0 :     return true;
    2085                 :             : }
        

Generated by: LCOV version 2.0-1