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

Generated by: LCOV version 1.13