PostgreSQL Source Code  git master
pqcomm.c File Reference
#include "postgres.h"
#include <signal.h>
#include <fcntl.h>
#include <grp.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <netdb.h>
#include <netinet/in.h>
#include <utime.h>
#include "common/ip.h"
#include "libpq/libpq.h"
#include "miscadmin.h"
#include "port/pg_bswap.h"
#include "storage/ipc.h"
#include "utils/guc.h"
#include "utils/memutils.h"
Include dependency graph for pqcomm.c:

Go to the source code of this file.

Macros

#define PQ_SEND_BUFFER_SIZE   8192
 
#define PQ_RECV_BUFFER_SIZE   8192
 

Functions

static void socket_comm_reset (void)
 
static void socket_close (int code, Datum arg)
 
static void socket_set_nonblocking (bool nonblocking)
 
static int socket_flush (void)
 
static int socket_flush_if_writable (void)
 
static bool socket_is_send_pending (void)
 
static int socket_putmessage (char msgtype, const char *s, size_t len)
 
static void socket_putmessage_noblock (char msgtype, const char *s, size_t len)
 
static int internal_putbytes (const char *s, size_t len)
 
static int internal_flush (void)
 
void pq_init (void)
 
int StreamServerPort (int family, const char *hostName, unsigned short portNumber, const char *unixSocketDir, pgsocket ListenSocket[], int MaxListen)
 
int StreamConnection (pgsocket server_fd, Port *port)
 
void StreamClose (pgsocket sock)
 
void TouchSocketFiles (void)
 
void RemoveSocketFiles (void)
 
static int pq_recvbuf (void)
 
int pq_getbyte (void)
 
int pq_peekbyte (void)
 
int pq_getbyte_if_available (unsigned char *c)
 
int pq_getbytes (char *s, size_t len)
 
static int pq_discardbytes (size_t len)
 
bool pq_buffer_has_data (void)
 
void pq_startmsgread (void)
 
void pq_endmsgread (void)
 
bool pq_is_reading_msg (void)
 
int pq_getmessage (StringInfo s, int maxlen)
 
int pq_putmessage_v2 (char msgtype, const char *s, size_t len)
 
int pq_getkeepalivesidle (Port *port)
 
int pq_setkeepalivesidle (int idle, Port *port)
 
int pq_getkeepalivesinterval (Port *port)
 
int pq_setkeepalivesinterval (int interval, Port *port)
 
int pq_getkeepalivescount (Port *port)
 
int pq_setkeepalivescount (int count, Port *port)
 
int pq_gettcpusertimeout (Port *port)
 
int pq_settcpusertimeout (int timeout, Port *port)
 
bool pq_check_connection (void)
 

Variables

int Unix_socket_permissions
 
char * Unix_socket_group
 
static Listsock_paths = NIL
 
static char * PqSendBuffer
 
static int PqSendBufferSize
 
static int PqSendPointer
 
static int PqSendStart
 
static char PqRecvBuffer [PQ_RECV_BUFFER_SIZE]
 
static int PqRecvPointer
 
static int PqRecvLength
 
static bool PqCommBusy
 
static bool PqCommReadingMsg
 
static const PQcommMethods PqCommSocketMethods
 
const PQcommMethodsPqCommMethods = &PqCommSocketMethods
 
WaitEventSetFeBeWaitSet
 

Macro Definition Documentation

◆ PQ_RECV_BUFFER_SIZE

#define PQ_RECV_BUFFER_SIZE   8192

Definition at line 122 of file pqcomm.c.

◆ PQ_SEND_BUFFER_SIZE

#define PQ_SEND_BUFFER_SIZE   8192

Definition at line 121 of file pqcomm.c.

Function Documentation

◆ internal_flush()

static int internal_flush ( void  )
static

Definition at line 1368 of file pqcomm.c.

1369 {
1370  static int last_reported_send_errno = 0;
1371 
1372  char *bufptr = PqSendBuffer + PqSendStart;
1373  char *bufend = PqSendBuffer + PqSendPointer;
1374 
1375  while (bufptr < bufend)
1376  {
1377  int r;
1378 
1379  r = secure_write(MyProcPort, bufptr, bufend - bufptr);
1380 
1381  if (r <= 0)
1382  {
1383  if (errno == EINTR)
1384  continue; /* Ok if we were interrupted */
1385 
1386  /*
1387  * Ok if no data writable without blocking, and the socket is in
1388  * non-blocking mode.
1389  */
1390  if (errno == EAGAIN ||
1391  errno == EWOULDBLOCK)
1392  {
1393  return 0;
1394  }
1395 
1396  /*
1397  * Careful: an ereport() that tries to write to the client would
1398  * cause recursion to here, leading to stack overflow and core
1399  * dump! This message must go *only* to the postmaster log.
1400  *
1401  * If a client disconnects while we're in the midst of output, we
1402  * might write quite a bit of data before we get to a safe query
1403  * abort point. So, suppress duplicate log messages.
1404  */
1405  if (errno != last_reported_send_errno)
1406  {
1407  last_reported_send_errno = errno;
1410  errmsg("could not send data to client: %m")));
1411  }
1412 
1413  /*
1414  * We drop the buffered data anyway so that processing can
1415  * continue, even though we'll probably quit soon. We also set a
1416  * flag that'll cause the next CHECK_FOR_INTERRUPTS to terminate
1417  * the connection.
1418  */
1419  PqSendStart = PqSendPointer = 0;
1421  InterruptPending = 1;
1422  return EOF;
1423  }
1424 
1425  last_reported_send_errno = 0; /* reset after any successful send */
1426  bufptr += r;
1427  PqSendStart += r;
1428  }
1429 
1430  PqSendStart = PqSendPointer = 0;
1431  return 0;
1432 }
ssize_t secure_write(Port *port, void *ptr, size_t len)
Definition: be-secure.c:260
int errcode_for_socket_access(void)
Definition: elog.c:787
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define COMMERROR
Definition: elog.h:27
#define ereport(elevel,...)
Definition: elog.h:143
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
volatile sig_atomic_t ClientConnectionLost
Definition: globals.c:34
struct Port * MyProcPort
Definition: globals.c:46
static int PqSendStart
Definition: pqcomm.c:127
static int PqSendPointer
Definition: pqcomm.c:126
static char * PqSendBuffer
Definition: pqcomm.c:124
#define EINTR
Definition: win32_port.h:351
#define EWOULDBLOCK
Definition: win32_port.h:357
#define EAGAIN
Definition: win32_port.h:349

References ClientConnectionLost, COMMERROR, EAGAIN, EINTR, ereport, errcode_for_socket_access(), errmsg(), EWOULDBLOCK, InterruptPending, MyProcPort, PqSendBuffer, PqSendPointer, PqSendStart, and secure_write().

Referenced by internal_putbytes(), socket_flush(), and socket_flush_if_writable().

◆ internal_putbytes()

static int internal_putbytes ( const char *  s,
size_t  len 
)
static

Definition at line 1315 of file pqcomm.c.

1316 {
1317  size_t amount;
1318 
1319  while (len > 0)
1320  {
1321  /* If buffer is full, then flush it out */
1323  {
1324  socket_set_nonblocking(false);
1325  if (internal_flush())
1326  return EOF;
1327  }
1328  amount = PqSendBufferSize - PqSendPointer;
1329  if (amount > len)
1330  amount = len;
1331  memcpy(PqSendBuffer + PqSendPointer, s, amount);
1332  PqSendPointer += amount;
1333  s += amount;
1334  len -= amount;
1335  }
1336  return 0;
1337 }
const void size_t len
static int internal_flush(void)
Definition: pqcomm.c:1368
static void socket_set_nonblocking(bool nonblocking)
Definition: pqcomm.c:931
static int PqSendBufferSize
Definition: pqcomm.c:125

References internal_flush(), len, PqSendBuffer, PqSendBufferSize, PqSendPointer, and socket_set_nonblocking().

Referenced by pq_putmessage_v2(), and socket_putmessage().

◆ pq_buffer_has_data()

bool pq_buffer_has_data ( void  )

Definition at line 1166 of file pqcomm.c.

1167 {
1168  return (PqRecvPointer < PqRecvLength);
1169 }
static int PqRecvLength
Definition: pqcomm.c:131
static int PqRecvPointer
Definition: pqcomm.c:130

References PqRecvLength, and PqRecvPointer.

Referenced by ProcessStartupPacket().

◆ pq_check_connection()

bool pq_check_connection ( void  )

Definition at line 1960 of file pqcomm.c.

1961 {
1962 #if defined(POLLRDHUP)
1963  /*
1964  * POLLRDHUP is a Linux extension to poll(2) to detect sockets closed by
1965  * the other end. We don't have a portable way to do that without
1966  * actually trying to read or write data on other systems. We don't want
1967  * to read because that would be confused by pipelined queries and COPY
1968  * data. Perhaps in future we'll try to write a heartbeat message instead.
1969  */
1970  struct pollfd pollfd;
1971  int rc;
1972 
1973  pollfd.fd = MyProcPort->sock;
1974  pollfd.events = POLLOUT | POLLIN | POLLRDHUP;
1975  pollfd.revents = 0;
1976 
1977  rc = poll(&pollfd, 1, 0);
1978 
1979  if (rc < 0)
1980  {
1983  errmsg("could not poll socket: %m")));
1984  return false;
1985  }
1986  else if (rc == 1 && (pollfd.revents & (POLLHUP | POLLRDHUP)))
1987  return false;
1988 #endif
1989 
1990  return true;
1991 }
pgsocket sock
Definition: libpq-be.h:127

References COMMERROR, ereport, errcode_for_socket_access(), errmsg(), MyProcPort, and Port::sock.

Referenced by ProcessInterrupts().

◆ pq_discardbytes()

static int pq_discardbytes ( size_t  len)
static

Definition at line 1137 of file pqcomm.c.

1138 {
1139  size_t amount;
1140 
1142 
1143  while (len > 0)
1144  {
1145  while (PqRecvPointer >= PqRecvLength)
1146  {
1147  if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1148  return EOF; /* Failed to recv data */
1149  }
1150  amount = PqRecvLength - PqRecvPointer;
1151  if (amount > len)
1152  amount = len;
1153  PqRecvPointer += amount;
1154  len -= amount;
1155  }
1156  return 0;
1157 }
Assert(fmt[strlen(fmt) - 1] !='\n')
static int pq_recvbuf(void)
Definition: pqcomm.c:948
static bool PqCommReadingMsg
Definition: pqcomm.c:137

References Assert(), len, pq_recvbuf(), PqCommReadingMsg, PqRecvLength, and PqRecvPointer.

Referenced by pq_getmessage().

◆ pq_endmsgread()

void pq_endmsgread ( void  )

Definition at line 1203 of file pqcomm.c.

1204 {
1206 
1207  PqCommReadingMsg = false;
1208 }

References Assert(), and PqCommReadingMsg.

Referenced by ProcessRepliesIfAny(), and ProcessStartupPacket().

◆ pq_getbyte()

int pq_getbyte ( void  )

Definition at line 1009 of file pqcomm.c.

1010 {
1012 
1013  while (PqRecvPointer >= PqRecvLength)
1014  {
1015  if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1016  return EOF; /* Failed to recv data */
1017  }
1018  return (unsigned char) PqRecvBuffer[PqRecvPointer++];
1019 }
static char PqRecvBuffer[PQ_RECV_BUFFER_SIZE]
Definition: pqcomm.c:129

References Assert(), pq_recvbuf(), PqCommReadingMsg, PqRecvBuffer, PqRecvLength, and PqRecvPointer.

Referenced by CheckSASLAuth(), CopyGetData(), recv_password_packet(), and SocketBackend().

◆ pq_getbyte_if_available()

int pq_getbyte_if_available ( unsigned char *  c)

Definition at line 1049 of file pqcomm.c.

1050 {
1051  int r;
1052 
1054 
1056  {
1058  return 1;
1059  }
1060 
1061  /* Put the socket into non-blocking mode */
1062  socket_set_nonblocking(true);
1063 
1064  r = secure_read(MyProcPort, c, 1);
1065  if (r < 0)
1066  {
1067  /*
1068  * Ok if no data available without blocking or interrupted (though
1069  * EINTR really shouldn't happen with a non-blocking socket). Report
1070  * other errors.
1071  */
1072  if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
1073  r = 0;
1074  else
1075  {
1076  /*
1077  * Careful: an ereport() that tries to write to the client would
1078  * cause recursion to here, leading to stack overflow and core
1079  * dump! This message must go *only* to the postmaster log.
1080  */
1083  errmsg("could not receive data from client: %m")));
1084  r = EOF;
1085  }
1086  }
1087  else if (r == 0)
1088  {
1089  /* EOF detected */
1090  r = EOF;
1091  }
1092 
1093  return r;
1094 }
ssize_t secure_read(Port *port, void *ptr, size_t len)
Definition: be-secure.c:147
char * c

References Assert(), COMMERROR, EAGAIN, EINTR, ereport, errcode_for_socket_access(), errmsg(), EWOULDBLOCK, MyProcPort, PqCommReadingMsg, PqRecvBuffer, PqRecvLength, PqRecvPointer, secure_read(), and socket_set_nonblocking().

Referenced by ProcessRepliesIfAny().

◆ pq_getbytes()

int pq_getbytes ( char *  s,
size_t  len 
)

Definition at line 1103 of file pqcomm.c.

1104 {
1105  size_t amount;
1106 
1108 
1109  while (len > 0)
1110  {
1111  while (PqRecvPointer >= PqRecvLength)
1112  {
1113  if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1114  return EOF; /* Failed to recv data */
1115  }
1116  amount = PqRecvLength - PqRecvPointer;
1117  if (amount > len)
1118  amount = len;
1119  memcpy(s, PqRecvBuffer + PqRecvPointer, amount);
1120  PqRecvPointer += amount;
1121  s += amount;
1122  len -= amount;
1123  }
1124  return 0;
1125 }

References Assert(), len, pq_recvbuf(), PqCommReadingMsg, PqRecvBuffer, PqRecvLength, and PqRecvPointer.

Referenced by pq_getmessage(), and ProcessStartupPacket().

◆ pq_getkeepalivescount()

int pq_getkeepalivescount ( Port port)

Definition at line 1807 of file pqcomm.c.

1808 {
1809 #ifdef TCP_KEEPCNT
1810  if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1811  return 0;
1812 
1813  if (port->keepalives_count != 0)
1814  return port->keepalives_count;
1815 
1816  if (port->default_keepalives_count == 0)
1817  {
1818  socklen_t size = sizeof(port->default_keepalives_count);
1819 
1820  if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPCNT,
1821  (char *) &port->default_keepalives_count,
1822  &size) < 0)
1823  {
1824  ereport(LOG,
1825  (errmsg("%s(%s) failed: %m", "getsockopt", "TCP_KEEPCNT")));
1826  port->default_keepalives_count = -1; /* don't know */
1827  }
1828  }
1829 
1830  return port->default_keepalives_count;
1831 #else
1832  return 0;
1833 #endif
1834 }
#define LOG
Definition: elog.h:25
#define IS_AF_UNIX(fam)
Definition: ip.h:24
static int port
Definition: pg_regress.c:92
unsigned int socklen_t
Definition: port.h:40

References ereport, errmsg(), IS_AF_UNIX, LOG, and port.

Referenced by pq_setkeepalivescount(), and show_tcp_keepalives_count().

◆ pq_getkeepalivesidle()

int pq_getkeepalivesidle ( Port port)

Definition at line 1638 of file pqcomm.c.

1639 {
1640 #if defined(PG_TCP_KEEPALIVE_IDLE) || defined(SIO_KEEPALIVE_VALS)
1641  if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1642  return 0;
1643 
1644  if (port->keepalives_idle != 0)
1645  return port->keepalives_idle;
1646 
1647  if (port->default_keepalives_idle == 0)
1648  {
1649 #ifndef WIN32
1650  socklen_t size = sizeof(port->default_keepalives_idle);
1651 
1652  if (getsockopt(port->sock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
1653  (char *) &port->default_keepalives_idle,
1654  &size) < 0)
1655  {
1656  ereport(LOG,
1657  (errmsg("%s(%s) failed: %m", "getsockopt", PG_TCP_KEEPALIVE_IDLE_STR)));
1658  port->default_keepalives_idle = -1; /* don't know */
1659  }
1660 #else /* WIN32 */
1661  /* We can't get the defaults on Windows, so return "don't know" */
1662  port->default_keepalives_idle = -1;
1663 #endif /* WIN32 */
1664  }
1665 
1666  return port->default_keepalives_idle;
1667 #else
1668  return 0;
1669 #endif
1670 }

References ereport, errmsg(), IS_AF_UNIX, LOG, and port.

Referenced by pq_setkeepalivesidle(), and show_tcp_keepalives_idle().

◆ pq_getkeepalivesinterval()

int pq_getkeepalivesinterval ( Port port)

Definition at line 1723 of file pqcomm.c.

1724 {
1725 #if defined(TCP_KEEPINTVL) || defined(SIO_KEEPALIVE_VALS)
1726  if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1727  return 0;
1728 
1729  if (port->keepalives_interval != 0)
1730  return port->keepalives_interval;
1731 
1732  if (port->default_keepalives_interval == 0)
1733  {
1734 #ifndef WIN32
1735  socklen_t size = sizeof(port->default_keepalives_interval);
1736 
1737  if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1738  (char *) &port->default_keepalives_interval,
1739  &size) < 0)
1740  {
1741  ereport(LOG,
1742  (errmsg("%s(%s) failed: %m", "getsockopt", "TCP_KEEPINTVL")));
1743  port->default_keepalives_interval = -1; /* don't know */
1744  }
1745 #else
1746  /* We can't get the defaults on Windows, so return "don't know" */
1747  port->default_keepalives_interval = -1;
1748 #endif /* WIN32 */
1749  }
1750 
1751  return port->default_keepalives_interval;
1752 #else
1753  return 0;
1754 #endif
1755 }

References ereport, errmsg(), IS_AF_UNIX, LOG, and port.

Referenced by pq_setkeepalivesinterval(), and show_tcp_keepalives_interval().

◆ pq_getmessage()

int pq_getmessage ( StringInfo  s,
int  maxlen 
)

Definition at line 1241 of file pqcomm.c.

1242 {
1243  int32 len;
1244 
1246 
1247  resetStringInfo(s);
1248 
1249  /* Read message length word */
1250  if (pq_getbytes((char *) &len, 4) == EOF)
1251  {
1253  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1254  errmsg("unexpected EOF within message length word")));
1255  return EOF;
1256  }
1257 
1258  len = pg_ntoh32(len);
1259 
1260  if (len < 4 || len > maxlen)
1261  {
1263  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1264  errmsg("invalid message length")));
1265  return EOF;
1266  }
1267 
1268  len -= 4; /* discount length itself */
1269 
1270  if (len > 0)
1271  {
1272  /*
1273  * Allocate space for message. If we run out of room (ridiculously
1274  * large message), we will elog(ERROR), but we want to discard the
1275  * message body so as not to lose communication sync.
1276  */
1277  PG_TRY();
1278  {
1279  enlargeStringInfo(s, len);
1280  }
1281  PG_CATCH();
1282  {
1283  if (pq_discardbytes(len) == EOF)
1285  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1286  errmsg("incomplete message from client")));
1287 
1288  /* we discarded the rest of the message so we're back in sync. */
1289  PqCommReadingMsg = false;
1290  PG_RE_THROW();
1291  }
1292  PG_END_TRY();
1293 
1294  /* And grab the message */
1295  if (pq_getbytes(s->data, len) == EOF)
1296  {
1298  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1299  errmsg("incomplete message from client")));
1300  return EOF;
1301  }
1302  s->len = len;
1303  /* Place a trailing null per StringInfo convention */
1304  s->data[len] = '\0';
1305  }
1306 
1307  /* finished reading the message. */
1308  PqCommReadingMsg = false;
1309 
1310  return 0;
1311 }
signed int int32
Definition: c.h:429
int errcode(int sqlerrcode)
Definition: elog.c:693
#define PG_RE_THROW()
Definition: elog.h:340
#define PG_END_TRY()
Definition: elog.h:324
#define PG_TRY()
Definition: elog.h:299
#define PG_CATCH()
Definition: elog.h:309
#define pg_ntoh32(x)
Definition: pg_bswap.h:125
static int pq_discardbytes(size_t len)
Definition: pqcomm.c:1137
int pq_getbytes(char *s, size_t len)
Definition: pqcomm.c:1103
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:283

References Assert(), COMMERROR, StringInfoData::data, enlargeStringInfo(), ereport, errcode(), errmsg(), StringInfoData::len, len, PG_CATCH, PG_END_TRY, pg_ntoh32, PG_RE_THROW, PG_TRY, pq_discardbytes(), pq_getbytes(), PqCommReadingMsg, and resetStringInfo().

Referenced by CheckSASLAuth(), CopyGetData(), ProcessRepliesIfAny(), recv_password_packet(), and SocketBackend().

◆ pq_gettcpusertimeout()

int pq_gettcpusertimeout ( Port port)

Definition at line 1882 of file pqcomm.c.

1883 {
1884 #ifdef TCP_USER_TIMEOUT
1885  if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1886  return 0;
1887 
1888  if (port->tcp_user_timeout != 0)
1889  return port->tcp_user_timeout;
1890 
1891  if (port->default_tcp_user_timeout == 0)
1892  {
1893  socklen_t size = sizeof(port->default_tcp_user_timeout);
1894 
1895  if (getsockopt(port->sock, IPPROTO_TCP, TCP_USER_TIMEOUT,
1896  (char *) &port->default_tcp_user_timeout,
1897  &size) < 0)
1898  {
1899  ereport(LOG,
1900  (errmsg("%s(%s) failed: %m", "getsockopt", "TCP_USER_TIMEOUT")));
1901  port->default_tcp_user_timeout = -1; /* don't know */
1902  }
1903  }
1904 
1905  return port->default_tcp_user_timeout;
1906 #else
1907  return 0;
1908 #endif
1909 }

References ereport, errmsg(), IS_AF_UNIX, LOG, and port.

Referenced by pq_settcpusertimeout(), and show_tcp_user_timeout().

◆ pq_init()

void pq_init ( void  )

Definition at line 176 of file pqcomm.c.

177 {
178  int socket_pos PG_USED_FOR_ASSERTS_ONLY;
179  int latch_pos PG_USED_FOR_ASSERTS_ONLY;
180 
181  /* initialize state variables */
185  PqCommBusy = false;
186  PqCommReadingMsg = false;
187 
188  /* set up process-exit hook to close the socket */
190 
191  /*
192  * In backends (as soon as forked) we operate the underlying socket in
193  * nonblocking mode and use latches to implement blocking semantics if
194  * needed. That allows us to provide safely interruptible reads and
195  * writes.
196  *
197  * Use COMMERROR on failure, because ERROR would try to send the error to
198  * the client, which might require changing the mode again, leading to
199  * infinite recursion.
200  */
201 #ifndef WIN32
204  (errmsg("could not set socket to nonblocking mode: %m")));
205 #endif
206 
209  MyProcPort->sock, NULL, NULL);
211  MyLatch, NULL);
213  NULL, NULL);
214 
215  /*
216  * The event positions match the order we added them, but let's sanity
217  * check them to be sure.
218  */
219  Assert(socket_pos == FeBeWaitSetSocketPos);
220  Assert(latch_pos == FeBeWaitSetLatchPos);
221 }
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:155
struct Latch * MyLatch
Definition: globals.c:57
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:305
WaitEventSet * CreateWaitEventSet(MemoryContext context, int nevents)
Definition: latch.c:684
int AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch, void *user_data)
Definition: latch.c:862
#define WL_LATCH_SET
Definition: latch.h:125
#define WL_POSTMASTER_DEATH
Definition: latch.h:129
#define WL_SOCKET_WRITEABLE
Definition: latch.h:127
#define FeBeWaitSetLatchPos
Definition: libpq.h:64
#define FeBeWaitSetSocketPos
Definition: libpq.h:63
MemoryContext TopMemoryContext
Definition: mcxt.c:48
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
bool pg_set_noblock(pgsocket sock)
Definition: noblock.c:25
#define PGINVALID_SOCKET
Definition: port.h:31
#define PQ_SEND_BUFFER_SIZE
Definition: pqcomm.c:121
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:168
static bool PqCommBusy
Definition: pqcomm.c:136
static void socket_close(int code, Datum arg)
Definition: pqcomm.c:247

References AddWaitEventToSet(), Assert(), COMMERROR, CreateWaitEventSet(), ereport, errmsg(), FeBeWaitSet, FeBeWaitSetLatchPos, FeBeWaitSetSocketPos, MemoryContextAlloc(), MyLatch, MyProcPort, on_proc_exit(), pg_set_noblock(), PG_USED_FOR_ASSERTS_ONLY, PGINVALID_SOCKET, PQ_SEND_BUFFER_SIZE, PqCommBusy, PqCommReadingMsg, PqRecvLength, PqRecvPointer, PqSendBuffer, PqSendBufferSize, PqSendPointer, PqSendStart, Port::sock, socket_close(), TopMemoryContext, WL_LATCH_SET, WL_POSTMASTER_DEATH, and WL_SOCKET_WRITEABLE.

Referenced by BackendInitialize().

◆ pq_is_reading_msg()

bool pq_is_reading_msg ( void  )

Definition at line 1219 of file pqcomm.c.

1220 {
1221  return PqCommReadingMsg;
1222 }

References PqCommReadingMsg.

Referenced by PostgresMain().

◆ pq_peekbyte()

int pq_peekbyte ( void  )

Definition at line 1028 of file pqcomm.c.

1029 {
1031 
1032  while (PqRecvPointer >= PqRecvLength)
1033  {
1034  if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1035  return EOF; /* Failed to recv data */
1036  }
1037  return (unsigned char) PqRecvBuffer[PqRecvPointer];
1038 }

References Assert(), pq_recvbuf(), PqCommReadingMsg, PqRecvBuffer, PqRecvLength, and PqRecvPointer.

◆ pq_putmessage_v2()

int pq_putmessage_v2 ( char  msgtype,
const char *  s,
size_t  len 
)

Definition at line 1567 of file pqcomm.c.

1568 {
1569  Assert(msgtype != 0);
1570 
1571  if (PqCommBusy)
1572  return 0;
1573  PqCommBusy = true;
1574  if (internal_putbytes(&msgtype, 1))
1575  goto fail;
1576 
1577  if (internal_putbytes(s, len))
1578  goto fail;
1579  PqCommBusy = false;
1580  return 0;
1581 
1582 fail:
1583  PqCommBusy = false;
1584  return EOF;
1585 }
static int internal_putbytes(const char *s, size_t len)
Definition: pqcomm.c:1315

References Assert(), internal_putbytes(), len, and PqCommBusy.

Referenced by send_message_to_frontend().

◆ pq_recvbuf()

static int pq_recvbuf ( void  )
static

Definition at line 948 of file pqcomm.c.

949 {
950  if (PqRecvPointer > 0)
951  {
953  {
954  /* still some unread data, left-justify it in the buffer */
958  PqRecvPointer = 0;
959  }
960  else
962  }
963 
964  /* Ensure that we're in blocking mode */
965  socket_set_nonblocking(false);
966 
967  /* Can fill buffer from PqRecvLength and upwards */
968  for (;;)
969  {
970  int r;
971 
974 
975  if (r < 0)
976  {
977  if (errno == EINTR)
978  continue; /* Ok if interrupted */
979 
980  /*
981  * Careful: an ereport() that tries to write to the client would
982  * cause recursion to here, leading to stack overflow and core
983  * dump! This message must go *only* to the postmaster log.
984  */
987  errmsg("could not receive data from client: %m")));
988  return EOF;
989  }
990  if (r == 0)
991  {
992  /*
993  * EOF detected. We used to write a log message here, but it's
994  * better to expect the ultimate caller to do that.
995  */
996  return EOF;
997  }
998  /* r contains number of bytes read, so just incr length */
999  PqRecvLength += r;
1000  return 0;
1001  }
1002 }
#define PQ_RECV_BUFFER_SIZE
Definition: pqcomm.c:122

References COMMERROR, EINTR, ereport, errcode_for_socket_access(), errmsg(), MyProcPort, PQ_RECV_BUFFER_SIZE, PqRecvBuffer, PqRecvLength, PqRecvPointer, secure_read(), and socket_set_nonblocking().

Referenced by pq_discardbytes(), pq_getbyte(), pq_getbytes(), and pq_peekbyte().

◆ pq_setkeepalivescount()

int pq_setkeepalivescount ( int  count,
Port port 
)

Definition at line 1837 of file pqcomm.c.

1838 {
1839  if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1840  return STATUS_OK;
1841 
1842 #ifdef TCP_KEEPCNT
1843  if (count == port->keepalives_count)
1844  return STATUS_OK;
1845 
1846  if (port->default_keepalives_count <= 0)
1847  {
1848  if (pq_getkeepalivescount(port) < 0)
1849  {
1850  if (count == 0)
1851  return STATUS_OK; /* default is set but unknown */
1852  else
1853  return STATUS_ERROR;
1854  }
1855  }
1856 
1857  if (count == 0)
1858  count = port->default_keepalives_count;
1859 
1860  if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPCNT,
1861  (char *) &count, sizeof(count)) < 0)
1862  {
1863  ereport(LOG,
1864  (errmsg("%s(%s) failed: %m", "setsockopt", "TCP_KEEPCNT")));
1865  return STATUS_ERROR;
1866  }
1867 
1868  port->keepalives_count = count;
1869 #else
1870  if (count != 0)
1871  {
1872  ereport(LOG,
1873  (errmsg("%s(%s) not supported", "setsockopt", "TCP_KEEPCNT")));
1874  return STATUS_ERROR;
1875  }
1876 #endif
1877 
1878  return STATUS_OK;
1879 }
#define STATUS_OK
Definition: c.h:1167
#define STATUS_ERROR
Definition: c.h:1168
int pq_getkeepalivescount(Port *port)
Definition: pqcomm.c:1807

References ereport, errmsg(), IS_AF_UNIX, LOG, port, pq_getkeepalivescount(), STATUS_ERROR, and STATUS_OK.

Referenced by assign_tcp_keepalives_count(), and StreamConnection().

◆ pq_setkeepalivesidle()

int pq_setkeepalivesidle ( int  idle,
Port port 
)

Definition at line 1673 of file pqcomm.c.

1674 {
1675  if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1676  return STATUS_OK;
1677 
1678 /* check SIO_KEEPALIVE_VALS here, not just WIN32, as some toolchains lack it */
1679 #if defined(PG_TCP_KEEPALIVE_IDLE) || defined(SIO_KEEPALIVE_VALS)
1680  if (idle == port->keepalives_idle)
1681  return STATUS_OK;
1682 
1683 #ifndef WIN32
1684  if (port->default_keepalives_idle <= 0)
1685  {
1686  if (pq_getkeepalivesidle(port) < 0)
1687  {
1688  if (idle == 0)
1689  return STATUS_OK; /* default is set but unknown */
1690  else
1691  return STATUS_ERROR;
1692  }
1693  }
1694 
1695  if (idle == 0)
1696  idle = port->default_keepalives_idle;
1697 
1698  if (setsockopt(port->sock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
1699  (char *) &idle, sizeof(idle)) < 0)
1700  {
1701  ereport(LOG,
1702  (errmsg("%s(%s) failed: %m", "setsockopt", PG_TCP_KEEPALIVE_IDLE_STR)));
1703  return STATUS_ERROR;
1704  }
1705 
1706  port->keepalives_idle = idle;
1707 #else /* WIN32 */
1708  return pq_setkeepaliveswin32(port, idle, port->keepalives_interval);
1709 #endif
1710 #else
1711  if (idle != 0)
1712  {
1713  ereport(LOG,
1714  (errmsg("setting the keepalive idle time is not supported")));
1715  return STATUS_ERROR;
1716  }
1717 #endif
1718 
1719  return STATUS_OK;
1720 }
int pq_getkeepalivesidle(Port *port)
Definition: pqcomm.c:1638

References ereport, errmsg(), IS_AF_UNIX, LOG, port, pq_getkeepalivesidle(), STATUS_ERROR, and STATUS_OK.

Referenced by assign_tcp_keepalives_idle(), and StreamConnection().

◆ pq_setkeepalivesinterval()

int pq_setkeepalivesinterval ( int  interval,
Port port 
)

Definition at line 1758 of file pqcomm.c.

1759 {
1760  if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1761  return STATUS_OK;
1762 
1763 #if defined(TCP_KEEPINTVL) || defined(SIO_KEEPALIVE_VALS)
1764  if (interval == port->keepalives_interval)
1765  return STATUS_OK;
1766 
1767 #ifndef WIN32
1768  if (port->default_keepalives_interval <= 0)
1769  {
1770  if (pq_getkeepalivesinterval(port) < 0)
1771  {
1772  if (interval == 0)
1773  return STATUS_OK; /* default is set but unknown */
1774  else
1775  return STATUS_ERROR;
1776  }
1777  }
1778 
1779  if (interval == 0)
1780  interval = port->default_keepalives_interval;
1781 
1782  if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1783  (char *) &interval, sizeof(interval)) < 0)
1784  {
1785  ereport(LOG,
1786  (errmsg("%s(%s) failed: %m", "setsockopt", "TCP_KEEPINTVL")));
1787  return STATUS_ERROR;
1788  }
1789 
1790  port->keepalives_interval = interval;
1791 #else /* WIN32 */
1792  return pq_setkeepaliveswin32(port, port->keepalives_idle, interval);
1793 #endif
1794 #else
1795  if (interval != 0)
1796  {
1797  ereport(LOG,
1798  (errmsg("%s(%s) not supported", "setsockopt", "TCP_KEEPINTVL")));
1799  return STATUS_ERROR;
1800  }
1801 #endif
1802 
1803  return STATUS_OK;
1804 }
int pq_getkeepalivesinterval(Port *port)
Definition: pqcomm.c:1723

References ereport, errmsg(), IS_AF_UNIX, LOG, port, pq_getkeepalivesinterval(), STATUS_ERROR, and STATUS_OK.

Referenced by assign_tcp_keepalives_interval(), and StreamConnection().

◆ pq_settcpusertimeout()

int pq_settcpusertimeout ( int  timeout,
Port port 
)

Definition at line 1912 of file pqcomm.c.

1913 {
1914  if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1915  return STATUS_OK;
1916 
1917 #ifdef TCP_USER_TIMEOUT
1918  if (timeout == port->tcp_user_timeout)
1919  return STATUS_OK;
1920 
1921  if (port->default_tcp_user_timeout <= 0)
1922  {
1923  if (pq_gettcpusertimeout(port) < 0)
1924  {
1925  if (timeout == 0)
1926  return STATUS_OK; /* default is set but unknown */
1927  else
1928  return STATUS_ERROR;
1929  }
1930  }
1931 
1932  if (timeout == 0)
1933  timeout = port->default_tcp_user_timeout;
1934 
1935  if (setsockopt(port->sock, IPPROTO_TCP, TCP_USER_TIMEOUT,
1936  (char *) &timeout, sizeof(timeout)) < 0)
1937  {
1938  ereport(LOG,
1939  (errmsg("%s(%s) failed: %m", "setsockopt", "TCP_USER_TIMEOUT")));
1940  return STATUS_ERROR;
1941  }
1942 
1943  port->tcp_user_timeout = timeout;
1944 #else
1945  if (timeout != 0)
1946  {
1947  ereport(LOG,
1948  (errmsg("%s(%s) not supported", "setsockopt", "TCP_USER_TIMEOUT")));
1949  return STATUS_ERROR;
1950  }
1951 #endif
1952 
1953  return STATUS_OK;
1954 }
int pq_gettcpusertimeout(Port *port)
Definition: pqcomm.c:1882

References ereport, errmsg(), IS_AF_UNIX, LOG, port, pq_gettcpusertimeout(), STATUS_ERROR, and STATUS_OK.

Referenced by assign_tcp_user_timeout(), and StreamConnection().

◆ pq_startmsgread()

void pq_startmsgread ( void  )

Definition at line 1179 of file pqcomm.c.

1180 {
1181  /*
1182  * There shouldn't be a read active already, but let's check just to be
1183  * sure.
1184  */
1185  if (PqCommReadingMsg)
1186  ereport(FATAL,
1187  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1188  errmsg("terminating connection because protocol synchronization was lost")));
1189 
1190  PqCommReadingMsg = true;
1191 }
#define FATAL
Definition: elog.h:35

References ereport, errcode(), errmsg(), FATAL, and PqCommReadingMsg.

Referenced by CheckSASLAuth(), CopyGetData(), ProcessRepliesIfAny(), ProcessStartupPacket(), recv_password_packet(), and SocketBackend().

◆ RemoveSocketFiles()

void RemoveSocketFiles ( void  )

Definition at line 898 of file pqcomm.c.

899 {
900  ListCell *l;
901 
902  /* Loop through all created sockets... */
903  foreach(l, sock_paths)
904  {
905  char *sock_path = (char *) lfirst(l);
906 
907  /* Ignore any error. */
908  (void) unlink(sock_path);
909  }
910  /* Since we're about to exit, no need to reclaim storage */
911  sock_paths = NIL;
912 }
#define lfirst(lc)
Definition: pg_list.h:169
#define NIL
Definition: pg_list.h:65
static List * sock_paths
Definition: pqcomm.c:112

References lfirst, NIL, and sock_paths.

Referenced by CloseServerPorts().

◆ socket_close()

static void socket_close ( int  code,
Datum  arg 
)
static

Definition at line 247 of file pqcomm.c.

248 {
249  /* Nothing to do in a standalone backend, where MyProcPort is NULL. */
250  if (MyProcPort != NULL)
251  {
252 #ifdef ENABLE_GSS
253  /*
254  * Shutdown GSSAPI layer. This section does nothing when interrupting
255  * BackendInitialize(), because pg_GSS_recvauth() makes first use of
256  * "ctx" and "cred".
257  *
258  * Note that we don't bother to free MyProcPort->gss, since we're
259  * about to exit anyway.
260  */
261  if (MyProcPort->gss)
262  {
263  OM_uint32 min_s;
264 
265  if (MyProcPort->gss->ctx != GSS_C_NO_CONTEXT)
266  gss_delete_sec_context(&min_s, &MyProcPort->gss->ctx, NULL);
267 
268  if (MyProcPort->gss->cred != GSS_C_NO_CREDENTIAL)
269  gss_release_cred(&min_s, &MyProcPort->gss->cred);
270  }
271 #endif /* ENABLE_GSS */
272 
273  /*
274  * Cleanly shut down SSL layer. Nowhere else does a postmaster child
275  * call this, so this is safe when interrupting BackendInitialize().
276  */
278 
279  /*
280  * On most platforms, we leave the socket open until the process dies.
281  * This allows clients to perform a "synchronous close" if they care
282  * --- wait till the transport layer reports connection closure, and
283  * you can be sure the backend has exited. Saves a kernel call, too.
284  *
285  * However, that does not work on Windows: if the kernel closes the
286  * socket it will invoke an "abortive shutdown" that discards any data
287  * not yet sent to the client. (This is a flat-out violation of the
288  * TCP RFCs, but count on Microsoft not to care about that.) To get
289  * the spec-compliant "graceful shutdown" behavior, we must invoke
290  * closesocket() explicitly. When using OpenSSL, it seems that clean
291  * shutdown also requires an explicit shutdown() call.
292  *
293  * This code runs late enough during process shutdown that we should
294  * have finished all externally-visible shutdown activities, so that
295  * in principle it's good enough to act as a synchronous close on
296  * Windows too. But it's a lot more fragile than the other way.
297  */
298 #ifdef WIN32
299  shutdown(MyProcPort->sock, SD_SEND);
301 #endif
302 
303  /* In any case, set sock to PGINVALID_SOCKET to prevent further I/O */
305  }
306 }
void secure_close(Port *port)
Definition: be-secure.c:135
#define closesocket
Definition: port.h:342
void * gss
Definition: libpq-be.h:203

References closesocket, Port::gss, MyProcPort, PGINVALID_SOCKET, secure_close(), and Port::sock.

Referenced by pq_init().

◆ socket_comm_reset()

static void socket_comm_reset ( void  )
static

Definition at line 232 of file pqcomm.c.

233 {
234  /* Do not throw away pending data, but do reset the busy flag */
235  PqCommBusy = false;
236 }

References PqCommBusy.

◆ socket_flush()

static int socket_flush ( void  )
static

Definition at line 1346 of file pqcomm.c.

1347 {
1348  int res;
1349 
1350  /* No-op if reentrant call */
1351  if (PqCommBusy)
1352  return 0;
1353  PqCommBusy = true;
1354  socket_set_nonblocking(false);
1355  res = internal_flush();
1356  PqCommBusy = false;
1357  return res;
1358 }

References internal_flush(), PqCommBusy, res, and socket_set_nonblocking().

◆ socket_flush_if_writable()

static int socket_flush_if_writable ( void  )
static

Definition at line 1441 of file pqcomm.c.

1442 {
1443  int res;
1444 
1445  /* Quick exit if nothing to do */
1446  if (PqSendPointer == PqSendStart)
1447  return 0;
1448 
1449  /* No-op if reentrant call */
1450  if (PqCommBusy)
1451  return 0;
1452 
1453  /* Temporarily put the socket into non-blocking mode */
1454  socket_set_nonblocking(true);
1455 
1456  PqCommBusy = true;
1457  res = internal_flush();
1458  PqCommBusy = false;
1459  return res;
1460 }

References internal_flush(), PqCommBusy, PqSendPointer, PqSendStart, res, and socket_set_nonblocking().

◆ socket_is_send_pending()

static bool socket_is_send_pending ( void  )
static

Definition at line 1467 of file pqcomm.c.

1468 {
1469  return (PqSendStart < PqSendPointer);
1470 }

References PqSendPointer, and PqSendStart.

◆ socket_putmessage()

static int socket_putmessage ( char  msgtype,
const char *  s,
size_t  len 
)
static

Definition at line 1497 of file pqcomm.c.

1498 {
1499  uint32 n32;
1500 
1501  Assert(msgtype != 0);
1502 
1503  if (PqCommBusy)
1504  return 0;
1505  PqCommBusy = true;
1506  if (internal_putbytes(&msgtype, 1))
1507  goto fail;
1508 
1509  n32 = pg_hton32((uint32) (len + 4));
1510  if (internal_putbytes((char *) &n32, 4))
1511  goto fail;
1512 
1513  if (internal_putbytes(s, len))
1514  goto fail;
1515  PqCommBusy = false;
1516  return 0;
1517 
1518 fail:
1519  PqCommBusy = false;
1520  return EOF;
1521 }
unsigned int uint32
Definition: c.h:441
#define pg_hton32(x)
Definition: pg_bswap.h:121

References Assert(), internal_putbytes(), len, pg_hton32, and PqCommBusy.

◆ socket_putmessage_noblock()

static void socket_putmessage_noblock ( char  msgtype,
const char *  s,
size_t  len 
)
static

Definition at line 1530 of file pqcomm.c.

1531 {
1533  int required;
1534 
1535  /*
1536  * Ensure we have enough space in the output buffer for the message header
1537  * as well as the message itself.
1538  */
1539  required = PqSendPointer + 1 + 4 + len;
1540  if (required > PqSendBufferSize)
1541  {
1544  }
1545  res = pq_putmessage(msgtype, s, len);
1546  Assert(res == 0); /* should not fail when the message fits in
1547  * buffer */
1548 }
#define pq_putmessage(msgtype, s, len)
Definition: libpq.h:49
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1182

References Assert(), len, PG_USED_FOR_ASSERTS_ONLY, pq_putmessage, PqSendBuffer, PqSendBufferSize, PqSendPointer, repalloc(), generate_unaccent_rules::required, and res.

◆ socket_set_nonblocking()

static void socket_set_nonblocking ( bool  nonblocking)
static

Definition at line 931 of file pqcomm.c.

932 {
933  if (MyProcPort == NULL)
934  ereport(ERROR,
935  (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
936  errmsg("there is no client connection")));
937 
938  MyProcPort->noblock = nonblocking;
939 }
#define ERROR
Definition: elog.h:33
bool noblock
Definition: libpq-be.h:128

References ereport, errcode(), errmsg(), ERROR, MyProcPort, and Port::noblock.

Referenced by internal_putbytes(), pq_getbyte_if_available(), pq_recvbuf(), socket_flush(), and socket_flush_if_writable().

◆ StreamClose()

void StreamClose ( pgsocket  sock)

Definition at line 865 of file pqcomm.c.

866 {
867  closesocket(sock);
868 }

References closesocket.

Referenced by ClosePostmasterPorts(), CloseServerPorts(), ConnCreate(), and ServerLoop().

◆ StreamConnection()

int StreamConnection ( pgsocket  server_fd,
Port port 
)

Definition at line 731 of file pqcomm.c.

732 {
733  /* accept connection and fill in the client (remote) address */
734  port->raddr.salen = sizeof(port->raddr.addr);
735  if ((port->sock = accept(server_fd,
736  (struct sockaddr *) &port->raddr.addr,
737  &port->raddr.salen)) == PGINVALID_SOCKET)
738  {
739  ereport(LOG,
741  errmsg("could not accept new connection: %m")));
742 
743  /*
744  * If accept() fails then postmaster.c will still see the server
745  * socket as read-ready, and will immediately try again. To avoid
746  * uselessly sucking lots of CPU, delay a bit before trying again.
747  * (The most likely reason for failure is being out of kernel file
748  * table slots; we can do little except hope some will get freed up.)
749  */
750  pg_usleep(100000L); /* wait 0.1 sec */
751  return STATUS_ERROR;
752  }
753 
754  /* fill in the server (local) address */
755  port->laddr.salen = sizeof(port->laddr.addr);
756  if (getsockname(port->sock,
757  (struct sockaddr *) &port->laddr.addr,
758  &port->laddr.salen) < 0)
759  {
760  ereport(LOG,
761  (errmsg("%s() failed: %m", "getsockname")));
762  return STATUS_ERROR;
763  }
764 
765  /* select NODELAY and KEEPALIVE options if it's a TCP connection */
766  if (!IS_AF_UNIX(port->laddr.addr.ss_family))
767  {
768  int on;
769 #ifdef WIN32
770  int oldopt;
771  int optlen;
772  int newopt;
773 #endif
774 
775 #ifdef TCP_NODELAY
776  on = 1;
777  if (setsockopt(port->sock, IPPROTO_TCP, TCP_NODELAY,
778  (char *) &on, sizeof(on)) < 0)
779  {
780  ereport(LOG,
781  (errmsg("%s(%s) failed: %m", "setsockopt", "TCP_NODELAY")));
782  return STATUS_ERROR;
783  }
784 #endif
785  on = 1;
786  if (setsockopt(port->sock, SOL_SOCKET, SO_KEEPALIVE,
787  (char *) &on, sizeof(on)) < 0)
788  {
789  ereport(LOG,
790  (errmsg("%s(%s) failed: %m", "setsockopt", "SO_KEEPALIVE")));
791  return STATUS_ERROR;
792  }
793 
794 #ifdef WIN32
795 
796  /*
797  * This is a Win32 socket optimization. The OS send buffer should be
798  * large enough to send the whole Postgres send buffer in one go, or
799  * performance suffers. The Postgres send buffer can be enlarged if a
800  * very large message needs to be sent, but we won't attempt to
801  * enlarge the OS buffer if that happens, so somewhat arbitrarily
802  * ensure that the OS buffer is at least PQ_SEND_BUFFER_SIZE * 4.
803  * (That's 32kB with the current default).
804  *
805  * The default OS buffer size used to be 8kB in earlier Windows
806  * versions, but was raised to 64kB in Windows 2012. So it shouldn't
807  * be necessary to change it in later versions anymore. Changing it
808  * unnecessarily can even reduce performance, because setting
809  * SO_SNDBUF in the application disables the "dynamic send buffering"
810  * feature that was introduced in Windows 7. So before fiddling with
811  * SO_SNDBUF, check if the current buffer size is already large enough
812  * and only increase it if necessary.
813  *
814  * See https://support.microsoft.com/kb/823764/EN-US/ and
815  * https://msdn.microsoft.com/en-us/library/bb736549%28v=vs.85%29.aspx
816  */
817  optlen = sizeof(oldopt);
818  if (getsockopt(port->sock, SOL_SOCKET, SO_SNDBUF, (char *) &oldopt,
819  &optlen) < 0)
820  {
821  ereport(LOG,
822  (errmsg("%s(%s) failed: %m", "getsockopt", "SO_SNDBUF")));
823  return STATUS_ERROR;
824  }
825  newopt = PQ_SEND_BUFFER_SIZE * 4;
826  if (oldopt < newopt)
827  {
828  if (setsockopt(port->sock, SOL_SOCKET, SO_SNDBUF, (char *) &newopt,
829  sizeof(newopt)) < 0)
830  {
831  ereport(LOG,
832  (errmsg("%s(%s) failed: %m", "setsockopt", "SO_SNDBUF")));
833  return STATUS_ERROR;
834  }
835  }
836 #endif
837 
838  /*
839  * Also apply the current keepalive parameters. If we fail to set a
840  * parameter, don't error out, because these aren't universally
841  * supported. (Note: you might think we need to reset the GUC
842  * variables to 0 in such a case, but it's not necessary because the
843  * show hooks for these variables report the truth anyway.)
844  */
849  }
850 
851  return STATUS_OK;
852 }
int tcp_keepalives_idle
Definition: guc.c:625
int tcp_keepalives_interval
Definition: guc.c:626
int tcp_keepalives_count
Definition: guc.c:627
int tcp_user_timeout
Definition: guc.c:628
int pq_setkeepalivesinterval(int interval, Port *port)
Definition: pqcomm.c:1758
int pq_settcpusertimeout(int timeout, Port *port)
Definition: pqcomm.c:1912
int pq_setkeepalivesidle(int idle, Port *port)
Definition: pqcomm.c:1673
int pq_setkeepalivescount(int count, Port *port)
Definition: pqcomm.c:1837
void pg_usleep(long microsec)
Definition: signal.c:53
#define accept(s, addr, addrlen)
Definition: win32_port.h:472

References accept, ereport, errcode_for_socket_access(), errmsg(), IS_AF_UNIX, LOG, pg_usleep(), PGINVALID_SOCKET, port, PQ_SEND_BUFFER_SIZE, pq_setkeepalivescount(), pq_setkeepalivesidle(), pq_setkeepalivesinterval(), pq_settcpusertimeout(), STATUS_ERROR, STATUS_OK, tcp_keepalives_count, tcp_keepalives_idle, tcp_keepalives_interval, and tcp_user_timeout.

Referenced by ConnCreate().

◆ StreamServerPort()

int StreamServerPort ( int  family,
const char *  hostName,
unsigned short  portNumber,
const char *  unixSocketDir,
pgsocket  ListenSocket[],
int  MaxListen 
)

Definition at line 333 of file pqcomm.c.

336 {
337  pgsocket fd;
338  int err;
339  int maxconn;
340  int ret;
341  char portNumberStr[32];
342  const char *familyDesc;
343  char familyDescBuf[64];
344  const char *addrDesc;
345  char addrBuf[NI_MAXHOST];
346  char *service;
347  struct addrinfo *addrs = NULL,
348  *addr;
349  struct addrinfo hint;
350  int listen_index = 0;
351  int added = 0;
352 
353 #ifdef HAVE_UNIX_SOCKETS
354  char unixSocketPath[MAXPGPATH];
355 #endif
356 #if !defined(WIN32) || defined(IPV6_V6ONLY)
357  int one = 1;
358 #endif
359 
360  /* Initialize hint structure */
361  MemSet(&hint, 0, sizeof(hint));
362  hint.ai_family = family;
363  hint.ai_flags = AI_PASSIVE;
364  hint.ai_socktype = SOCK_STREAM;
365 
366 #ifdef HAVE_UNIX_SOCKETS
367  if (family == AF_UNIX)
368  {
369  /*
370  * Create unixSocketPath from portNumber and unixSocketDir and lock
371  * that file path
372  */
373  UNIXSOCK_PATH(unixSocketPath, portNumber, unixSocketDir);
374  if (strlen(unixSocketPath) >= UNIXSOCK_PATH_BUFLEN)
375  {
376  ereport(LOG,
377  (errmsg("Unix-domain socket path \"%s\" is too long (maximum %d bytes)",
378  unixSocketPath,
379  (int) (UNIXSOCK_PATH_BUFLEN - 1))));
380  return STATUS_ERROR;
381  }
382  if (Lock_AF_UNIX(unixSocketDir, unixSocketPath) != STATUS_OK)
383  return STATUS_ERROR;
384  service = unixSocketPath;
385  }
386  else
387 #endif /* HAVE_UNIX_SOCKETS */
388  {
389  snprintf(portNumberStr, sizeof(portNumberStr), "%d", portNumber);
390  service = portNumberStr;
391  }
392 
393  ret = pg_getaddrinfo_all(hostName, service, &hint, &addrs);
394  if (ret || !addrs)
395  {
396  if (hostName)
397  ereport(LOG,
398  (errmsg("could not translate host name \"%s\", service \"%s\" to address: %s",
399  hostName, service, gai_strerror(ret))));
400  else
401  ereport(LOG,
402  (errmsg("could not translate service \"%s\" to address: %s",
403  service, gai_strerror(ret))));
404  if (addrs)
405  pg_freeaddrinfo_all(hint.ai_family, addrs);
406  return STATUS_ERROR;
407  }
408 
409  for (addr = addrs; addr; addr = addr->ai_next)
410  {
411  if (!IS_AF_UNIX(family) && IS_AF_UNIX(addr->ai_family))
412  {
413  /*
414  * Only set up a unix domain socket when they really asked for it.
415  * The service/port is different in that case.
416  */
417  continue;
418  }
419 
420  /* See if there is still room to add 1 more socket. */
421  for (; listen_index < MaxListen; listen_index++)
422  {
423  if (ListenSocket[listen_index] == PGINVALID_SOCKET)
424  break;
425  }
426  if (listen_index >= MaxListen)
427  {
428  ereport(LOG,
429  (errmsg("could not bind to all requested addresses: MAXLISTEN (%d) exceeded",
430  MaxListen)));
431  break;
432  }
433 
434  /* set up address family name for log messages */
435  switch (addr->ai_family)
436  {
437  case AF_INET:
438  familyDesc = _("IPv4");
439  break;
440 #ifdef HAVE_IPV6
441  case AF_INET6:
442  familyDesc = _("IPv6");
443  break;
444 #endif
445 #ifdef HAVE_UNIX_SOCKETS
446  case AF_UNIX:
447  familyDesc = _("Unix");
448  break;
449 #endif
450  default:
451  snprintf(familyDescBuf, sizeof(familyDescBuf),
452  _("unrecognized address family %d"),
453  addr->ai_family);
454  familyDesc = familyDescBuf;
455  break;
456  }
457 
458  /* set up text form of address for log messages */
459 #ifdef HAVE_UNIX_SOCKETS
460  if (addr->ai_family == AF_UNIX)
461  addrDesc = unixSocketPath;
462  else
463 #endif
464  {
465  pg_getnameinfo_all((const struct sockaddr_storage *) addr->ai_addr,
466  addr->ai_addrlen,
467  addrBuf, sizeof(addrBuf),
468  NULL, 0,
470  addrDesc = addrBuf;
471  }
472 
473  if ((fd = socket(addr->ai_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
474  {
475  ereport(LOG,
477  /* translator: first %s is IPv4, IPv6, or Unix */
478  errmsg("could not create %s socket for address \"%s\": %m",
479  familyDesc, addrDesc)));
480  continue;
481  }
482 
483 #ifndef WIN32
484 
485  /*
486  * Without the SO_REUSEADDR flag, a new postmaster can't be started
487  * right away after a stop or crash, giving "address already in use"
488  * error on TCP ports.
489  *
490  * On win32, however, this behavior only happens if the
491  * SO_EXCLUSIVEADDRUSE is set. With SO_REUSEADDR, win32 allows
492  * multiple servers to listen on the same address, resulting in
493  * unpredictable behavior. With no flags at all, win32 behaves as Unix
494  * with SO_REUSEADDR.
495  */
496  if (!IS_AF_UNIX(addr->ai_family))
497  {
498  if ((setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
499  (char *) &one, sizeof(one))) == -1)
500  {
501  ereport(LOG,
503  /* translator: third %s is IPv4, IPv6, or Unix */
504  errmsg("%s(%s) failed for %s address \"%s\": %m",
505  "setsockopt", "SO_REUSEADDR",
506  familyDesc, addrDesc)));
507  closesocket(fd);
508  continue;
509  }
510  }
511 #endif
512 
513 #ifdef IPV6_V6ONLY
514  if (addr->ai_family == AF_INET6)
515  {
516  if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY,
517  (char *) &one, sizeof(one)) == -1)
518  {
519  ereport(LOG,
521  /* translator: third %s is IPv4, IPv6, or Unix */
522  errmsg("%s(%s) failed for %s address \"%s\": %m",
523  "setsockopt", "IPV6_V6ONLY",
524  familyDesc, addrDesc)));
525  closesocket(fd);
526  continue;
527  }
528  }
529 #endif
530 
531  /*
532  * Note: This might fail on some OS's, like Linux older than
533  * 2.4.21-pre3, that don't have the IPV6_V6ONLY socket option, and map
534  * ipv4 addresses to ipv6. It will show ::ffff:ipv4 for all ipv4
535  * connections.
536  */
537  err = bind(fd, addr->ai_addr, addr->ai_addrlen);
538  if (err < 0)
539  {
540  int saved_errno = errno;
541 
542  ereport(LOG,
544  /* translator: first %s is IPv4, IPv6, or Unix */
545  errmsg("could not bind %s address \"%s\": %m",
546  familyDesc, addrDesc),
547  saved_errno == EADDRINUSE ?
548  (IS_AF_UNIX(addr->ai_family) ?
549  errhint("Is another postmaster already running on port %d?",
550  (int) portNumber) :
551  errhint("Is another postmaster already running on port %d?"
552  " If not, wait a few seconds and retry.",
553  (int) portNumber)) : 0));
554  closesocket(fd);
555  continue;
556  }
557 
558 #ifdef HAVE_UNIX_SOCKETS
559  if (addr->ai_family == AF_UNIX)
560  {
561  if (Setup_AF_UNIX(service) != STATUS_OK)
562  {
563  closesocket(fd);
564  break;
565  }
566  }
567 #endif
568 
569  /*
570  * Select appropriate accept-queue length limit. PG_SOMAXCONN is only
571  * intended to provide a clamp on the request on platforms where an
572  * overly large request provokes a kernel error (are there any?).
573  */
574  maxconn = MaxBackends * 2;
575  if (maxconn > PG_SOMAXCONN)
576  maxconn = PG_SOMAXCONN;
577 
578  err = listen(fd, maxconn);
579  if (err < 0)
580  {
581  ereport(LOG,
583  /* translator: first %s is IPv4, IPv6, or Unix */
584  errmsg("could not listen on %s address \"%s\": %m",
585  familyDesc, addrDesc)));
586  closesocket(fd);
587  continue;
588  }
589 
590 #ifdef HAVE_UNIX_SOCKETS
591  if (addr->ai_family == AF_UNIX)
592  ereport(LOG,
593  (errmsg("listening on Unix socket \"%s\"",
594  addrDesc)));
595  else
596 #endif
597  ereport(LOG,
598  /* translator: first %s is IPv4 or IPv6 */
599  (errmsg("listening on %s address \"%s\", port %d",
600  familyDesc, addrDesc, (int) portNumber)));
601 
602  ListenSocket[listen_index] = fd;
603  added++;
604  }
605 
606  pg_freeaddrinfo_all(hint.ai_family, addrs);
607 
608  if (!added)
609  return STATUS_ERROR;
610 
611  return STATUS_OK;
612 }
#define MemSet(start, val, len)
Definition: c.h:1008
int errhint(const char *fmt,...)
Definition: elog.c:1151
#define _(x)
Definition: elog.c:89
#define gai_strerror
Definition: getaddrinfo.h:146
#define NI_NUMERICHOST
Definition: getaddrinfo.h:78
#define NI_MAXHOST
Definition: getaddrinfo.h:88
#define AI_PASSIVE
Definition: getaddrinfo.h:62
int MaxBackends
Definition: globals.c:139
void pg_freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai)
Definition: ip.c:88
int pg_getnameinfo_all(const struct sockaddr_storage *addr, int salen, char *node, int nodelen, char *service, int servicelen, int flags)
Definition: ip.c:122
int pg_getaddrinfo_all(const char *hostname, const char *servname, const struct addrinfo *hintp, struct addrinfo **result)
Definition: ip.c:57
#define MAXPGPATH
#define PG_SOMAXCONN
int pgsocket
Definition: port.h:29
#define snprintf
Definition: port.h:225
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:222
#define UNIXSOCK_PATH(path, port, sockdir)
Definition: pqcomm.h:70
#define UNIXSOCK_PATH_BUFLEN
Definition: pqcomm.h:86
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define bind(s, addr, addrlen)
Definition: win32_port.h:470
#define EADDRINUSE
Definition: win32_port.h:377
#define socket(af, type, protocol)
Definition: win32_port.h:469
#define listen(s, backlog)
Definition: win32_port.h:471

References _, addrinfo::ai_family, addrinfo::ai_flags, addrinfo::ai_next, AI_PASSIVE, addrinfo::ai_socktype, bind, closesocket, EADDRINUSE, ereport, errcode_for_socket_access(), errhint(), errmsg(), fd(), gai_strerror, IS_AF_UNIX, listen, ListenSocket, LOG, MaxBackends, MAXPGPATH, MemSet, NI_MAXHOST, NI_NUMERICHOST, pg_freeaddrinfo_all(), pg_getaddrinfo_all(), pg_getnameinfo_all(), PG_SOMAXCONN, PGINVALID_SOCKET, snprintf, socket, STATUS_ERROR, STATUS_OK, UNIXSOCK_PATH, and UNIXSOCK_PATH_BUFLEN.

Referenced by PostmasterMain().

◆ TouchSocketFiles()

void TouchSocketFiles ( void  )

Definition at line 880 of file pqcomm.c.

881 {
882  ListCell *l;
883 
884  /* Loop through all created sockets... */
885  foreach(l, sock_paths)
886  {
887  char *sock_path = (char *) lfirst(l);
888 
889  /* Ignore errors; there's no point in complaining */
890  (void) utime(sock_path, NULL);
891  }
892 }

References lfirst, and sock_paths.

Referenced by ServerLoop().

Variable Documentation

◆ FeBeWaitSet

◆ PqCommBusy

bool PqCommBusy
static

◆ PqCommMethods

const PQcommMethods* PqCommMethods = &PqCommSocketMethods

Definition at line 166 of file pqcomm.c.

Referenced by pq_redirect_to_shm_mq(), and pq_set_parallel_leader().

◆ PqCommReadingMsg

◆ PqCommSocketMethods

const PQcommMethods PqCommSocketMethods
static
Initial value:
= {
}
static int socket_flush_if_writable(void)
Definition: pqcomm.c:1441
static int socket_flush(void)
Definition: pqcomm.c:1346
static void socket_comm_reset(void)
Definition: pqcomm.c:232
static bool socket_is_send_pending(void)
Definition: pqcomm.c:1467
static int socket_putmessage(char msgtype, const char *s, size_t len)
Definition: pqcomm.c:1497
static void socket_putmessage_noblock(char msgtype, const char *s, size_t len)
Definition: pqcomm.c:1530

Definition at line 157 of file pqcomm.c.

◆ PqRecvBuffer

char PqRecvBuffer[PQ_RECV_BUFFER_SIZE]
static

Definition at line 129 of file pqcomm.c.

Referenced by pq_getbyte(), pq_getbyte_if_available(), pq_getbytes(), pq_peekbyte(), and pq_recvbuf().

◆ PqRecvLength

int PqRecvLength
static

◆ PqRecvPointer

int PqRecvPointer
static

◆ PqSendBuffer

char* PqSendBuffer
static

Definition at line 124 of file pqcomm.c.

Referenced by internal_flush(), internal_putbytes(), pq_init(), and socket_putmessage_noblock().

◆ PqSendBufferSize

int PqSendBufferSize
static

Definition at line 125 of file pqcomm.c.

Referenced by internal_putbytes(), pq_init(), and socket_putmessage_noblock().

◆ PqSendPointer

◆ PqSendStart

int PqSendStart
static

◆ sock_paths

List* sock_paths = NIL
static

Definition at line 112 of file pqcomm.c.

Referenced by RemoveSocketFiles(), and TouchSocketFiles().

◆ Unix_socket_group

char* Unix_socket_group

Definition at line 109 of file pqcomm.c.

◆ Unix_socket_permissions

int Unix_socket_permissions

Definition at line 108 of file pqcomm.c.

Referenced by show_unix_socket_permissions().