LCOV - code coverage report
Current view: top level - src/backend/libpq - pqcomm.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13beta1 Lines: 302 519 58.2 %
Date: 2020-06-03 09:06:53 Functions: 34 40 85.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13