PostgreSQL Source Code git master
Loading...
Searching...
No Matches
pqcomm.c File Reference
#include "postgres.h"
#include <poll.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 <netinet/tcp.h>
#include <utime.h>
#include "common/ip.h"
#include "libpq/libpq.h"
#include "miscadmin.h"
#include "port/pg_bswap.h"
#include "postmaster/postmaster.h"
#include "storage/ipc.h"
#include "storage/latch.h"
#include "utils/guc_hooks.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 void *b, size_t len)
 
static int internal_flush (void)
 
static pg_noinline int internal_flush_buffer (const char *buf, size_t *start, size_t *end)
 
static int Lock_AF_UNIX (const char *unixSocketDir, const char *unixSocketPath)
 
static int Setup_AF_UNIX (const char *sock_path)
 
Portpq_init (ClientSocket *client_sock)
 
int ListenServerPort (int family, const char *hostName, unsigned short portNumber, const char *unixSocketDir, pgsocket ListenSockets[], int *NumListenSockets, int MaxListen)
 
int AcceptConnection (pgsocket server_fd, ClientSocket *client_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 (void *b, size_t len)
 
static int pq_discardbytes (size_t len)
 
ssize_t pq_buffer_remaining_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)
 
void assign_tcp_keepalives_idle (int newval, void *extra)
 
const charshow_tcp_keepalives_idle (void)
 
void assign_tcp_keepalives_interval (int newval, void *extra)
 
const charshow_tcp_keepalives_interval (void)
 
void assign_tcp_keepalives_count (int newval, void *extra)
 
const charshow_tcp_keepalives_count (void)
 
void assign_tcp_user_timeout (int newval, void *extra)
 
const charshow_tcp_user_timeout (void)
 
bool pq_check_connection (void)
 

Variables

int Unix_socket_permissions
 
charUnix_socket_group
 
static Listsock_paths = NIL
 
static charPqSendBuffer
 
static int PqSendBufferSize
 
static size_t PqSendPointer
 
static size_t 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 121 of file pqcomm.c.

◆ PQ_SEND_BUFFER_SIZE

#define PQ_SEND_BUFFER_SIZE   8192

Definition at line 120 of file pqcomm.c.

Function Documentation

◆ AcceptConnection()

int AcceptConnection ( pgsocket  server_fd,
ClientSocket client_sock 
)

Definition at line 795 of file pqcomm.c.

796{
797 /* accept connection and fill in the client (remote) address */
798 client_sock->raddr.salen = sizeof(client_sock->raddr.addr);
799 if ((client_sock->sock = accept(server_fd,
800 (struct sockaddr *) &client_sock->raddr.addr,
801 &client_sock->raddr.salen)) == PGINVALID_SOCKET)
802 {
803 ereport(LOG,
805 errmsg("could not accept new connection: %m")));
806
807 /*
808 * If accept() fails then postmaster.c will still see the server
809 * socket as read-ready, and will immediately try again. To avoid
810 * uselessly sucking lots of CPU, delay a bit before trying again.
811 * (The most likely reason for failure is being out of kernel file
812 * table slots; we can do little except hope some will get freed up.)
813 */
814 pg_usleep(100000L); /* wait 0.1 sec */
815 return STATUS_ERROR;
816 }
817
818 return STATUS_OK;
819}
#define STATUS_OK
Definition c.h:1186
#define STATUS_ERROR
Definition c.h:1187
int errcode_for_socket_access(void)
Definition elog.c:976
int errmsg(const char *fmt,...)
Definition elog.c:1093
#define LOG
Definition elog.h:31
#define ereport(elevel,...)
Definition elog.h:150
#define PGINVALID_SOCKET
Definition port.h:31
static int fb(int x)
void pg_usleep(long microsec)
Definition signal.c:53
#define accept(s, addr, addrlen)
Definition win32_port.h:498

References accept, ereport, errcode_for_socket_access(), errmsg(), fb(), LOG, pg_usleep(), PGINVALID_SOCKET, STATUS_ERROR, and STATUS_OK.

Referenced by ServerLoop().

◆ assign_tcp_keepalives_count()

void assign_tcp_keepalives_count ( int  newval,
void extra 
)

Definition at line 2011 of file pqcomm.c.

2012{
2013 /* See comments in assign_tcp_keepalives_idle */
2015}
struct Port * MyProcPort
Definition globals.c:51
#define newval
int pq_setkeepalivescount(int count, Port *port)
Definition pqcomm.c:1832

References fb(), MyProcPort, newval, and pq_setkeepalivescount().

◆ assign_tcp_keepalives_idle()

void assign_tcp_keepalives_idle ( int  newval,
void extra 
)

Definition at line 1955 of file pqcomm.c.

1956{
1957 /*
1958 * The kernel API provides no way to test a value without setting it; and
1959 * once we set it we might fail to unset it. So there seems little point
1960 * in fully implementing the check-then-assign GUC API for these
1961 * variables. Instead we just do the assignment on demand.
1962 * pq_setkeepalivesidle reports any problems via ereport(LOG).
1963 *
1964 * This approach means that the GUC value might have little to do with the
1965 * actual kernel value, so we use a show_hook that retrieves the kernel
1966 * value rather than trusting GUC's copy.
1967 */
1969}
int pq_setkeepalivesidle(int idle, Port *port)
Definition pqcomm.c:1668

References fb(), MyProcPort, newval, and pq_setkeepalivesidle().

◆ assign_tcp_keepalives_interval()

void assign_tcp_keepalives_interval ( int  newval,
void extra 
)

Definition at line 1988 of file pqcomm.c.

1989{
1990 /* See comments in assign_tcp_keepalives_idle */
1992}
int pq_setkeepalivesinterval(int interval, Port *port)
Definition pqcomm.c:1753

References fb(), MyProcPort, newval, and pq_setkeepalivesinterval().

◆ assign_tcp_user_timeout()

void assign_tcp_user_timeout ( int  newval,
void extra 
)

Definition at line 2034 of file pqcomm.c.

2035{
2036 /* See comments in assign_tcp_keepalives_idle */
2038}
int pq_settcpusertimeout(int timeout, Port *port)
Definition pqcomm.c:1907

References fb(), MyProcPort, newval, and pq_settcpusertimeout().

◆ internal_flush()

static int internal_flush ( void  )
inlinestatic

Definition at line 1350 of file pqcomm.c.

1351{
1353}
static size_t PqSendPointer
Definition pqcomm.c:125
static char * PqSendBuffer
Definition pqcomm.c:123
static pg_noinline int internal_flush_buffer(const char *buf, size_t *start, size_t *end)
Definition pqcomm.c:1363
static size_t PqSendStart
Definition pqcomm.c:126

References internal_flush_buffer(), PqSendBuffer, PqSendPointer, and PqSendStart.

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

◆ internal_flush_buffer()

static pg_noinline int internal_flush_buffer ( const char buf,
size_t start,
size_t end 
)
static

Definition at line 1363 of file pqcomm.c.

1364{
1365 static int last_reported_send_errno = 0;
1366
1367 const char *bufptr = buf + *start;
1368 const char *bufend = buf + *end;
1369
1370 while (bufptr < bufend)
1371 {
1372 int r;
1373
1374 r = secure_write(MyProcPort, bufptr, bufend - bufptr);
1375
1376 if (r <= 0)
1377 {
1378 if (errno == EINTR)
1379 continue; /* Ok if we were interrupted */
1380
1381 /*
1382 * Ok if no data writable without blocking, and the socket is in
1383 * non-blocking mode.
1384 */
1385 if (errno == EAGAIN ||
1386 errno == EWOULDBLOCK)
1387 {
1388 return 0;
1389 }
1390
1391 /*
1392 * Careful: an ereport() that tries to write to the client would
1393 * cause recursion to here, leading to stack overflow and core
1394 * dump! This message must go *only* to the postmaster log.
1395 *
1396 * If a client disconnects while we're in the midst of output, we
1397 * might write quite a bit of data before we get to a safe query
1398 * abort point. So, suppress duplicate log messages.
1399 */
1401 {
1405 errmsg("could not send data to client: %m")));
1406 }
1407
1408 /*
1409 * We drop the buffered data anyway so that processing can
1410 * continue, even though we'll probably quit soon. We also set a
1411 * flag that'll cause the next CHECK_FOR_INTERRUPTS to terminate
1412 * the connection.
1413 */
1414 *start = *end = 0;
1416 InterruptPending = 1;
1417 return EOF;
1418 }
1419
1420 last_reported_send_errno = 0; /* reset after any successful send */
1421 bufptr += r;
1422 *start += r;
1423 }
1424
1425 *start = *end = 0;
1426 return 0;
1427}
ssize_t secure_write(Port *port, const void *ptr, size_t len)
Definition be-secure.c:306
#define COMMERROR
Definition elog.h:33
volatile sig_atomic_t InterruptPending
Definition globals.c:32
volatile sig_atomic_t ClientConnectionLost
Definition globals.c:36
return str start
static char buf[DEFAULT_XLOG_SEG_SIZE]
#define EINTR
Definition win32_port.h:361
#define EWOULDBLOCK
Definition win32_port.h:367
#define EAGAIN
Definition win32_port.h:359

References buf, ClientConnectionLost, COMMERROR, EAGAIN, EINTR, ereport, errcode_for_socket_access(), errmsg(), EWOULDBLOCK, fb(), InterruptPending, MyProcPort, secure_write(), and start.

Referenced by internal_flush(), and internal_putbytes().

◆ internal_putbytes()

static int internal_putbytes ( const void b,
size_t  len 
)
inlinestatic

Definition at line 1278 of file pqcomm.c.

1279{
1280 const char *s = b;
1281
1282 while (len > 0)
1283 {
1284 /* If buffer is full, then flush it out */
1286 {
1288 if (internal_flush())
1289 return EOF;
1290 }
1291
1292 /*
1293 * If the buffer is empty and data length is larger than the buffer
1294 * size, send it without buffering. Otherwise, copy as much data as
1295 * possible into the buffer.
1296 */
1298 {
1299 size_t start = 0;
1300
1302 if (internal_flush_buffer(s, &start, &len))
1303 return EOF;
1304 }
1305 else
1306 {
1308
1309 if (amount > len)
1310 amount = len;
1313 s += amount;
1314 len -= amount;
1315 }
1316 }
1317
1318 return 0;
1319}
int b
Definition isn.c:74
const void size_t len
static int internal_flush(void)
Definition pqcomm.c:1350
static void socket_set_nonblocking(bool nonblocking)
Definition pqcomm.c:881
static int PqSendBufferSize
Definition pqcomm.c:124

References b, fb(), internal_flush(), internal_flush_buffer(), len, PqSendBuffer, PqSendBufferSize, PqSendPointer, PqSendStart, socket_set_nonblocking(), and start.

Referenced by pq_putmessage_v2(), and socket_putmessage().

◆ ListenServerPort()

int ListenServerPort ( int  family,
const char hostName,
unsigned short  portNumber,
const char unixSocketDir,
pgsocket  ListenSockets[],
int NumListenSockets,
int  MaxListen 
)

Definition at line 419 of file pqcomm.c.

422{
423 pgsocket fd;
424 int err;
425 int maxconn;
426 int ret;
427 char portNumberStr[32];
428 const char *familyDesc;
429 char familyDescBuf[64];
430 const char *addrDesc;
431 char addrBuf[NI_MAXHOST];
432 char *service;
433 struct addrinfo *addrs = NULL,
434 *addr;
435 struct addrinfo hint;
436 int added = 0;
438#if !defined(WIN32) || defined(IPV6_V6ONLY)
439 int one = 1;
440#endif
441
442 /* Initialize hint structure */
443 MemSet(&hint, 0, sizeof(hint));
444 hint.ai_family = family;
445 hint.ai_flags = AI_PASSIVE;
446 hint.ai_socktype = SOCK_STREAM;
447
448 if (family == AF_UNIX)
449 {
450 /*
451 * Create unixSocketPath from portNumber and unixSocketDir and lock
452 * that file path
453 */
456 {
457 ereport(LOG,
458 (errmsg("Unix-domain socket path \"%s\" is too long (maximum %zu bytes)",
460 (UNIXSOCK_PATH_BUFLEN - 1))));
461 return STATUS_ERROR;
462 }
464 return STATUS_ERROR;
466 }
467 else
468 {
471 }
472
473 ret = pg_getaddrinfo_all(hostName, service, &hint, &addrs);
474 if (ret || !addrs)
475 {
476 if (hostName)
477 ereport(LOG,
478 (errmsg("could not translate host name \"%s\", service \"%s\" to address: %s",
479 hostName, service, gai_strerror(ret))));
480 else
481 ereport(LOG,
482 (errmsg("could not translate service \"%s\" to address: %s",
483 service, gai_strerror(ret))));
484 if (addrs)
485 pg_freeaddrinfo_all(hint.ai_family, addrs);
486 return STATUS_ERROR;
487 }
488
489 for (addr = addrs; addr; addr = addr->ai_next)
490 {
491 if (family != AF_UNIX && addr->ai_family == AF_UNIX)
492 {
493 /*
494 * Only set up a unix domain socket when they really asked for it.
495 * The service/port is different in that case.
496 */
497 continue;
498 }
499
500 /* See if there is still room to add 1 more socket. */
502 {
503 ereport(LOG,
504 (errmsg("could not bind to all requested addresses: MAXLISTEN (%d) exceeded",
505 MaxListen)));
506 break;
507 }
508
509 /* set up address family name for log messages */
510 switch (addr->ai_family)
511 {
512 case AF_INET:
513 familyDesc = _("IPv4");
514 break;
515 case AF_INET6:
516 familyDesc = _("IPv6");
517 break;
518 case AF_UNIX:
519 familyDesc = _("Unix");
520 break;
521 default:
523 _("unrecognized address family %d"),
524 addr->ai_family);
526 break;
527 }
528
529 /* set up text form of address for log messages */
530 if (addr->ai_family == AF_UNIX)
532 else
533 {
534 pg_getnameinfo_all((const struct sockaddr_storage *) addr->ai_addr,
535 addr->ai_addrlen,
536 addrBuf, sizeof(addrBuf),
537 NULL, 0,
540 }
541
542 if ((fd = socket(addr->ai_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
543 {
544 ereport(LOG,
546 /* translator: first %s is IPv4, IPv6, or Unix */
547 errmsg("could not create %s socket for address \"%s\": %m",
549 continue;
550 }
551
552#ifndef WIN32
553 /* Don't give the listen socket to any subprograms we execute. */
554 if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0)
555 elog(FATAL, "fcntl(F_SETFD) failed on socket: %m");
556
557 /*
558 * Without the SO_REUSEADDR flag, a new postmaster can't be started
559 * right away after a stop or crash, giving "address already in use"
560 * error on TCP ports.
561 *
562 * On win32, however, this behavior only happens if the
563 * SO_EXCLUSIVEADDRUSE is set. With SO_REUSEADDR, win32 allows
564 * multiple servers to listen on the same address, resulting in
565 * unpredictable behavior. With no flags at all, win32 behaves as Unix
566 * with SO_REUSEADDR.
567 */
568 if (addr->ai_family != AF_UNIX)
569 {
571 (char *) &one, sizeof(one))) == -1)
572 {
573 ereport(LOG,
575 /* translator: third %s is IPv4 or IPv6 */
576 errmsg("%s(%s) failed for %s address \"%s\": %m",
577 "setsockopt", "SO_REUSEADDR",
580 continue;
581 }
582 }
583#endif
584
585#ifdef IPV6_V6ONLY
586 if (addr->ai_family == AF_INET6)
587 {
589 (char *) &one, sizeof(one)) == -1)
590 {
591 ereport(LOG,
593 /* translator: third %s is IPv6 */
594 errmsg("%s(%s) failed for %s address \"%s\": %m",
595 "setsockopt", "IPV6_V6ONLY",
598 continue;
599 }
600 }
601#endif
602
603 /*
604 * Note: This might fail on some OS's, like Linux older than
605 * 2.4.21-pre3, that don't have the IPV6_V6ONLY socket option, and map
606 * ipv4 addresses to ipv6. It will show ::ffff:ipv4 for all ipv4
607 * connections.
608 */
609 err = bind(fd, addr->ai_addr, addr->ai_addrlen);
610 if (err < 0)
611 {
612 int saved_errno = errno;
613
614 ereport(LOG,
616 /* translator: first %s is IPv4, IPv6, or Unix */
617 errmsg("could not bind %s address \"%s\": %m",
619 saved_errno == EADDRINUSE ?
620 (addr->ai_family == AF_UNIX ?
621 errhint("Is another postmaster already running on port %d?",
622 portNumber) :
623 errhint("Is another postmaster already running on port %d?"
624 " If not, wait a few seconds and retry.",
625 portNumber)) : 0));
627 continue;
628 }
629
630 if (addr->ai_family == AF_UNIX)
631 {
633 {
635 break;
636 }
637 }
638
639 /*
640 * Select appropriate accept-queue length limit. It seems reasonable
641 * to use a value similar to the maximum number of child processes
642 * that the postmaster will permit.
643 */
645
646 err = listen(fd, maxconn);
647 if (err < 0)
648 {
649 ereport(LOG,
651 /* translator: first %s is IPv4, IPv6, or Unix */
652 errmsg("could not listen on %s address \"%s\": %m",
655 continue;
656 }
657
658 if (addr->ai_family == AF_UNIX)
659 ereport(LOG,
660 (errmsg("listening on Unix socket \"%s\"",
661 addrDesc)));
662 else
663 ereport(LOG,
664 /* translator: first %s is IPv4 or IPv6 */
665 (errmsg("listening on %s address \"%s\", port %d",
667
669 (*NumListenSockets)++;
670 added++;
671 }
672
673 pg_freeaddrinfo_all(hint.ai_family, addrs);
674
675 if (!added)
676 return STATUS_ERROR;
677
678 return STATUS_OK;
679}
#define MemSet(start, val, len)
Definition c.h:1035
#define _(x)
Definition elog.c:95
int errhint(const char *fmt,...) pg_attribute_printf(1
#define FATAL
Definition elog.h:41
#define elog(elevel,...)
Definition elog.h:226
void err(int eval, const char *fmt,...)
Definition err.c:43
int MaxConnections
Definition globals.c:143
void pg_freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai)
Definition ip.c:85
int pg_getnameinfo_all(const struct sockaddr_storage *addr, int salen, char *node, int nodelen, char *service, int servicelen, int flags)
Definition ip.c:117
int pg_getaddrinfo_all(const char *hostname, const char *servname, const struct addrinfo *hintp, struct addrinfo **result)
Definition ip.c:56
#define MAXPGPATH
int pgsocket
Definition port.h:29
#define snprintf
Definition port.h:260
#define closesocket
Definition port.h:397
static pgsocket * ListenSockets
Definition postmaster.c:235
static int NumListenSockets
Definition postmaster.c:234
static int Lock_AF_UNIX(const char *unixSocketDir, const char *unixSocketPath)
Definition pqcomm.c:686
static int Setup_AF_UNIX(const char *sock_path)
Definition pqcomm.c:721
#define UNIXSOCK_PATH(path, port, sockdir)
Definition pqcomm.h:43
#define UNIXSOCK_PATH_BUFLEN
Definition pqcomm.h:59
static int fd(const char *x, int i)
const char * gai_strerror(int errcode)
#define bind(s, addr, addrlen)
Definition win32_port.h:496
#define EADDRINUSE
Definition win32_port.h:387
#define socket(af, type, protocol)
Definition win32_port.h:495
#define listen(s, backlog)
Definition win32_port.h:497

References _, bind, closesocket, EADDRINUSE, elog, ereport, err(), errcode_for_socket_access(), errhint(), errmsg(), FATAL, fb(), fd(), gai_strerror(), listen, ListenSockets, Lock_AF_UNIX(), LOG, MaxConnections, MAXPGPATH, MemSet, NumListenSockets, pg_freeaddrinfo_all(), pg_getaddrinfo_all(), pg_getnameinfo_all(), PGINVALID_SOCKET, Setup_AF_UNIX(), snprintf, socket, STATUS_ERROR, STATUS_OK, UNIXSOCK_PATH, and UNIXSOCK_PATH_BUFLEN.

Referenced by PostmasterMain().

◆ Lock_AF_UNIX()

static int Lock_AF_UNIX ( const char unixSocketDir,
const char unixSocketPath 
)
static

Definition at line 686 of file pqcomm.c.

687{
688 /* no lock file for abstract sockets */
689 if (unixSocketPath[0] == '@')
690 return STATUS_OK;
691
692 /*
693 * Grab an interlock file associated with the socket file.
694 *
695 * Note: there are two reasons for using a socket lock file, rather than
696 * trying to interlock directly on the socket itself. First, it's a lot
697 * more portable, and second, it lets us remove any pre-existing socket
698 * file without race conditions.
699 */
701
702 /*
703 * Once we have the interlock, we can safely delete any pre-existing
704 * socket file to avoid failure at bind() time.
705 */
707
708 /*
709 * Remember socket file pathnames for later maintenance.
710 */
712
713 return STATUS_OK;
714}
List * lappend(List *list, void *datum)
Definition list.c:339
char * pstrdup(const char *in)
Definition mcxt.c:1781
void CreateSocketLockFile(const char *socketfile, bool amPostmaster, const char *socketDir)
Definition miscinit.c:1472
static List * sock_paths
Definition pqcomm.c:111

References CreateSocketLockFile(), fb(), lappend(), pstrdup(), sock_paths, and STATUS_OK.

Referenced by ListenServerPort().

◆ pq_buffer_remaining_data()

ssize_t pq_buffer_remaining_data ( void  )

Definition at line 1128 of file pqcomm.c.

1129{
1131 return (PqRecvLength - PqRecvPointer);
1132}
#define Assert(condition)
Definition c.h:885
static int PqRecvLength
Definition pqcomm.c:130
static int PqRecvPointer
Definition pqcomm.c:129

References Assert, PqRecvLength, and PqRecvPointer.

Referenced by ProcessStartupPacket(), and secure_open_server().

◆ pq_check_connection()

bool pq_check_connection ( void  )

Definition at line 2057 of file pqcomm.c.

2058{
2060 int rc;
2061
2062 /*
2063 * It's OK to modify the socket event filter without restoring, because
2064 * all FeBeWaitSet socket wait sites do the same.
2065 */
2067
2068retry:
2069 rc = WaitEventSetWait(FeBeWaitSet, 0, events, lengthof(events), 0);
2070 for (int i = 0; i < rc; ++i)
2071 {
2072 if (events[i].events & WL_SOCKET_CLOSED)
2073 return false;
2074 if (events[i].events & WL_LATCH_SET)
2075 {
2076 /*
2077 * A latch event might be preventing other events from being
2078 * reported. Reset it and poll again. No need to restore it
2079 * because no code should expect latches to survive across
2080 * CHECK_FOR_INTERRUPTS().
2081 */
2083 goto retry;
2084 }
2085 }
2086
2087 return true;
2088}
#define lengthof(array)
Definition c.h:815
struct Latch * MyLatch
Definition globals.c:63
int i
Definition isn.c:77
void ResetLatch(Latch *latch)
Definition latch.c:374
#define FeBeWaitSetNEvents
Definition libpq.h:68
#define FeBeWaitSetSocketPos
Definition libpq.h:66
WaitEventSet * FeBeWaitSet
Definition pqcomm.c:167
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
int WaitEventSetWait(WaitEventSet *set, long timeout, WaitEvent *occurred_events, int nevents, uint32 wait_event_info)
#define WL_SOCKET_CLOSED
#define WL_LATCH_SET

References fb(), FeBeWaitSet, FeBeWaitSetNEvents, FeBeWaitSetSocketPos, i, lengthof, ModifyWaitEvent(), MyLatch, ResetLatch(), WaitEventSetWait(), WL_LATCH_SET, and WL_SOCKET_CLOSED.

Referenced by ProcessInterrupts().

◆ pq_discardbytes()

static int pq_discardbytes ( size_t  len)
static

Definition at line 1098 of file pqcomm.c.

1099{
1100 size_t amount;
1101
1103
1104 while (len > 0)
1105 {
1106 while (PqRecvPointer >= PqRecvLength)
1107 {
1108 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1109 return EOF; /* Failed to recv data */
1110 }
1112 if (amount > len)
1113 amount = len;
1115 len -= amount;
1116 }
1117 return 0;
1118}
static int pq_recvbuf(void)
Definition pqcomm.c:898
static bool PqCommReadingMsg
Definition pqcomm.c:136

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

Referenced by pq_getmessage().

◆ pq_endmsgread()

void pq_endmsgread ( void  )

Definition at line 1166 of file pqcomm.c.

1167{
1169
1170 PqCommReadingMsg = false;
1171}

References Assert, and PqCommReadingMsg.

Referenced by ProcessRepliesIfAny(), ProcessSSLStartup(), ProcessStartupPacket(), and secure_open_server().

◆ pq_getbyte()

int pq_getbyte ( void  )

Definition at line 964 of file pqcomm.c.

965{
967
968 while (PqRecvPointer >= PqRecvLength)
969 {
970 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
971 return EOF; /* Failed to recv data */
972 }
973 return (unsigned char) PqRecvBuffer[PqRecvPointer++];
974}
static char PqRecvBuffer[PQ_RECV_BUFFER_SIZE]
Definition pqcomm.c:128

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

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

◆ pq_getbyte_if_available()

int pq_getbyte_if_available ( unsigned char c)

Definition at line 1004 of file pqcomm.c.

1005{
1006 int r;
1007
1009
1011 {
1013 return 1;
1014 }
1015
1016 /* Put the socket into non-blocking mode */
1018
1019 errno = 0;
1020
1021 r = secure_read(MyProcPort, c, 1);
1022 if (r < 0)
1023 {
1024 /*
1025 * Ok if no data available without blocking or interrupted (though
1026 * EINTR really shouldn't happen with a non-blocking socket). Report
1027 * other errors.
1028 */
1029 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
1030 r = 0;
1031 else
1032 {
1033 /*
1034 * Careful: an ereport() that tries to write to the client would
1035 * cause recursion to here, leading to stack overflow and core
1036 * dump! This message must go *only* to the postmaster log.
1037 *
1038 * If errno is zero, assume it's EOF and let the caller complain.
1039 */
1040 if (errno != 0)
1043 errmsg("could not receive data from client: %m")));
1044 r = EOF;
1045 }
1046 }
1047 else if (r == 0)
1048 {
1049 /* EOF detected */
1050 r = EOF;
1051 }
1052
1053 return r;
1054}
ssize_t secure_read(Port *port, void *ptr, size_t len)
Definition be-secure.c:180
char * c

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

Referenced by ProcessRepliesIfAny().

◆ pq_getbytes()

int pq_getbytes ( void b,
size_t  len 
)

Definition at line 1063 of file pqcomm.c.

1064{
1065 char *s = b;
1066 size_t amount;
1067
1069
1070 while (len > 0)
1071 {
1072 while (PqRecvPointer >= PqRecvLength)
1073 {
1074 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1075 return EOF; /* Failed to recv data */
1076 }
1078 if (amount > len)
1079 amount = len;
1082 s += amount;
1083 len -= amount;
1084 }
1085 return 0;
1086}

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

Referenced by pq_getmessage(), ProcessStartupPacket(), and secure_open_server().

◆ pq_getkeepalivescount()

int pq_getkeepalivescount ( Port port)

Definition at line 1802 of file pqcomm.c.

1803{
1804#ifdef TCP_KEEPCNT
1805 if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
1806 return 0;
1807
1808 if (port->keepalives_count != 0)
1809 return port->keepalives_count;
1810
1811 if (port->default_keepalives_count == 0)
1812 {
1813 socklen_t size = sizeof(port->default_keepalives_count);
1814
1816 (char *) &port->default_keepalives_count,
1817 &size) < 0)
1818 {
1819 ereport(LOG,
1820 (errmsg("%s(%s) failed: %m", "getsockopt", "TCP_KEEPCNT")));
1821 port->default_keepalives_count = -1; /* don't know */
1822 }
1823 }
1824
1825 return port->default_keepalives_count;
1826#else
1827 return 0;
1828#endif
1829}
static int port
Definition pg_regress.c:115
unsigned int socklen_t
Definition port.h:40

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

Referenced by pq_setkeepalivescount(), and show_tcp_keepalives_count().

◆ pq_getkeepalivesidle()

int pq_getkeepalivesidle ( Port port)

Definition at line 1633 of file pqcomm.c.

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

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

Referenced by pq_setkeepalivesidle(), and show_tcp_keepalives_idle().

◆ pq_getkeepalivesinterval()

int pq_getkeepalivesinterval ( Port port)

Definition at line 1718 of file pqcomm.c.

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

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

Referenced by pq_setkeepalivesinterval(), and show_tcp_keepalives_interval().

◆ pq_getmessage()

int pq_getmessage ( StringInfo  s,
int  maxlen 
)

Definition at line 1204 of file pqcomm.c.

1205{
1206 int32 len;
1207
1209
1210 resetStringInfo(s);
1211
1212 /* Read message length word */
1213 if (pq_getbytes(&len, 4) == EOF)
1214 {
1217 errmsg("unexpected EOF within message length word")));
1218 return EOF;
1219 }
1220
1221 len = pg_ntoh32(len);
1222
1223 if (len < 4 || len > maxlen)
1224 {
1227 errmsg("invalid message length")));
1228 return EOF;
1229 }
1230
1231 len -= 4; /* discount length itself */
1232
1233 if (len > 0)
1234 {
1235 /*
1236 * Allocate space for message. If we run out of room (ridiculously
1237 * large message), we will elog(ERROR), but we want to discard the
1238 * message body so as not to lose communication sync.
1239 */
1240 PG_TRY();
1241 {
1243 }
1244 PG_CATCH();
1245 {
1246 if (pq_discardbytes(len) == EOF)
1249 errmsg("incomplete message from client")));
1250
1251 /* we discarded the rest of the message so we're back in sync. */
1252 PqCommReadingMsg = false;
1253 PG_RE_THROW();
1254 }
1255 PG_END_TRY();
1256
1257 /* And grab the message */
1258 if (pq_getbytes(s->data, len) == EOF)
1259 {
1262 errmsg("incomplete message from client")));
1263 return EOF;
1264 }
1265 s->len = len;
1266 /* Place a trailing null per StringInfo convention */
1267 s->data[len] = '\0';
1268 }
1269
1270 /* finished reading the message. */
1271 PqCommReadingMsg = false;
1272
1273 return 0;
1274}
int32_t int32
Definition c.h:554
int errcode(int sqlerrcode)
Definition elog.c:874
#define PG_RE_THROW()
Definition elog.h:405
#define PG_TRY(...)
Definition elog.h:372
#define PG_END_TRY(...)
Definition elog.h:397
#define PG_CATCH(...)
Definition elog.h:382
#define ERRCODE_PROTOCOL_VIOLATION
Definition fe-connect.c:96
#define pg_ntoh32(x)
Definition pg_bswap.h:125
static int pq_discardbytes(size_t len)
Definition pqcomm.c:1098
int pq_getbytes(void *b, size_t len)
Definition pqcomm.c:1063
void resetStringInfo(StringInfo str)
Definition stringinfo.c:126
void enlargeStringInfo(StringInfo str, int needed)
Definition stringinfo.c:337

References Assert, COMMERROR, StringInfoData::data, enlargeStringInfo(), ereport, errcode(), ERRCODE_PROTOCOL_VIOLATION, errmsg(), fb(), 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(), HandleUploadManifestPacket(), ProcessRepliesIfAny(), recv_password_packet(), and SocketBackend().

◆ pq_gettcpusertimeout()

int pq_gettcpusertimeout ( Port port)

Definition at line 1877 of file pqcomm.c.

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

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

Referenced by pq_settcpusertimeout(), and show_tcp_user_timeout().

◆ pq_init()

Port * pq_init ( ClientSocket client_sock)

Definition at line 175 of file pqcomm.c.

176{
177 Port *port;
179 int latch_pos PG_USED_FOR_ASSERTS_ONLY;
180
181 /* allocate the Port struct and copy the ClientSocket contents to it */
183 port->sock = client_sock->sock;
184 memcpy(&port->raddr.addr, &client_sock->raddr.addr, client_sock->raddr.salen);
185 port->raddr.salen = client_sock->raddr.salen;
186
187 /* fill in the server (local) address */
188 port->laddr.salen = sizeof(port->laddr.addr);
189 if (getsockname(port->sock,
190 (struct sockaddr *) &port->laddr.addr,
191 &port->laddr.salen) < 0)
192 {
194 (errmsg("%s() failed: %m", "getsockname")));
195 }
196
197 /* select NODELAY and KEEPALIVE options if it's a TCP connection */
198 if (port->laddr.addr.ss_family != AF_UNIX)
199 {
200 int on;
201#ifdef WIN32
202 int oldopt;
203 int optlen;
204 int newopt;
205#endif
206
207#ifdef TCP_NODELAY
208 on = 1;
210 (char *) &on, sizeof(on)) < 0)
211 {
213 (errmsg("%s(%s) failed: %m", "setsockopt", "TCP_NODELAY")));
214 }
215#endif
216 on = 1;
218 (char *) &on, sizeof(on)) < 0)
219 {
221 (errmsg("%s(%s) failed: %m", "setsockopt", "SO_KEEPALIVE")));
222 }
223
224#ifdef WIN32
225
226 /*
227 * This is a Win32 socket optimization. The OS send buffer should be
228 * large enough to send the whole Postgres send buffer in one go, or
229 * performance suffers. The Postgres send buffer can be enlarged if a
230 * very large message needs to be sent, but we won't attempt to
231 * enlarge the OS buffer if that happens, so somewhat arbitrarily
232 * ensure that the OS buffer is at least PQ_SEND_BUFFER_SIZE * 4.
233 * (That's 32kB with the current default).
234 *
235 * The default OS buffer size used to be 8kB in earlier Windows
236 * versions, but was raised to 64kB in Windows 2012. So it shouldn't
237 * be necessary to change it in later versions anymore. Changing it
238 * unnecessarily can even reduce performance, because setting
239 * SO_SNDBUF in the application disables the "dynamic send buffering"
240 * feature that was introduced in Windows 7. So before fiddling with
241 * SO_SNDBUF, check if the current buffer size is already large enough
242 * and only increase it if necessary.
243 *
244 * See https://support.microsoft.com/kb/823764/EN-US/ and
245 * https://msdn.microsoft.com/en-us/library/bb736549%28v=vs.85%29.aspx
246 */
247 optlen = sizeof(oldopt);
248 if (getsockopt(port->sock, SOL_SOCKET, SO_SNDBUF, (char *) &oldopt,
249 &optlen) < 0)
250 {
252 (errmsg("%s(%s) failed: %m", "getsockopt", "SO_SNDBUF")));
253 }
255 if (oldopt < newopt)
256 {
257 if (setsockopt(port->sock, SOL_SOCKET, SO_SNDBUF, (char *) &newopt,
258 sizeof(newopt)) < 0)
259 {
261 (errmsg("%s(%s) failed: %m", "setsockopt", "SO_SNDBUF")));
262 }
263 }
264#endif
265
266 /*
267 * Also apply the current keepalive parameters. If we fail to set a
268 * parameter, don't error out, because these aren't universally
269 * supported. (Note: you might think we need to reset the GUC
270 * variables to 0 in such a case, but it's not necessary because the
271 * show hooks for these variables report the truth anyway.)
272 */
277 }
278
279 /* initialize state variables */
283 PqCommBusy = false;
284 PqCommReadingMsg = false;
285
286 /* set up process-exit hook to close the socket */
288
289 /*
290 * In backends (as soon as forked) we operate the underlying socket in
291 * nonblocking mode and use latches to implement blocking semantics if
292 * needed. That allows us to provide safely interruptible reads and
293 * writes.
294 */
295#ifndef WIN32
296 if (!pg_set_noblock(port->sock))
298 (errmsg("could not set socket to nonblocking mode: %m")));
299#endif
300
301#ifndef WIN32
302
303 /* Don't give the socket to any subprograms we execute. */
304 if (fcntl(port->sock, F_SETFD, FD_CLOEXEC) < 0)
305 elog(FATAL, "fcntl(F_SETFD) failed on socket: %m");
306#endif
307
310 port->sock, NULL, NULL);
312 MyLatch, NULL);
314 NULL, NULL);
315
316 /*
317 * The event positions match the order we added them, but let's sanity
318 * check them to be sure.
319 */
321 Assert(latch_pos == FeBeWaitSetLatchPos);
322
323 return port;
324}
#define PG_USED_FOR_ASSERTS_ONLY
Definition c.h:235
#define palloc0_object(type)
Definition fe_memutils.h:75
int tcp_keepalives_idle
Definition guc_tables.c:572
int tcp_keepalives_interval
Definition guc_tables.c:573
int tcp_keepalives_count
Definition guc_tables.c:574
int tcp_user_timeout
Definition guc_tables.c:575
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition ipc.c:316
#define FeBeWaitSetLatchPos
Definition libpq.h:67
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition mcxt.c:1232
MemoryContext TopMemoryContext
Definition mcxt.c:166
bool pg_set_noblock(pgsocket sock)
Definition noblock.c:25
#define PQ_SEND_BUFFER_SIZE
Definition pqcomm.c:120
static bool PqCommBusy
Definition pqcomm.c:135
static void socket_close(int code, Datum arg)
Definition pqcomm.c:350
int AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch, void *user_data)
WaitEventSet * CreateWaitEventSet(ResourceOwner resowner, int nevents)
#define WL_POSTMASTER_DEATH
#define WL_SOCKET_WRITEABLE

References AddWaitEventToSet(), Assert, CreateWaitEventSet(), elog, ereport, errmsg(), FATAL, fb(), FeBeWaitSet, FeBeWaitSetLatchPos, FeBeWaitSetNEvents, FeBeWaitSetSocketPos, MemoryContextAlloc(), MyLatch, on_proc_exit(), palloc0_object, pg_set_noblock(), PG_USED_FOR_ASSERTS_ONLY, PGINVALID_SOCKET, port, PQ_SEND_BUFFER_SIZE, pq_setkeepalivescount(), pq_setkeepalivesidle(), pq_setkeepalivesinterval(), pq_settcpusertimeout(), PqCommBusy, PqCommReadingMsg, PqRecvLength, PqRecvPointer, PqSendBuffer, PqSendBufferSize, PqSendPointer, PqSendStart, socket_close(), tcp_keepalives_count, tcp_keepalives_idle, tcp_keepalives_interval, tcp_user_timeout, 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 1182 of file pqcomm.c.

1183{
1184 return PqCommReadingMsg;
1185}

References PqCommReadingMsg.

Referenced by PostgresMain().

◆ pq_peekbyte()

int pq_peekbyte ( void  )

Definition at line 983 of file pqcomm.c.

984{
986
987 while (PqRecvPointer >= PqRecvLength)
988 {
989 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
990 return EOF; /* Failed to recv data */
991 }
992 return (unsigned char) PqRecvBuffer[PqRecvPointer];
993}

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

Referenced by ProcessSSLStartup().

◆ pq_putmessage_v2()

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

Definition at line 1562 of file pqcomm.c.

1563{
1564 Assert(msgtype != 0);
1565
1566 if (PqCommBusy)
1567 return 0;
1568 PqCommBusy = true;
1569 if (internal_putbytes(&msgtype, 1))
1570 goto fail;
1571
1572 if (internal_putbytes(s, len))
1573 goto fail;
1574 PqCommBusy = false;
1575 return 0;
1576
1577fail:
1578 PqCommBusy = false;
1579 return EOF;
1580}
static int internal_putbytes(const void *b, size_t len)
Definition pqcomm.c:1278

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

Referenced by send_message_to_frontend().

◆ pq_recvbuf()

static int pq_recvbuf ( void  )
static

Definition at line 898 of file pqcomm.c.

899{
900 if (PqRecvPointer > 0)
901 {
903 {
904 /* still some unread data, left-justify it in the buffer */
908 PqRecvPointer = 0;
909 }
910 else
912 }
913
914 /* Ensure that we're in blocking mode */
916
917 /* Can fill buffer from PqRecvLength and upwards */
918 for (;;)
919 {
920 int r;
921
922 errno = 0;
923
926
927 if (r < 0)
928 {
929 if (errno == EINTR)
930 continue; /* Ok if interrupted */
931
932 /*
933 * Careful: an ereport() that tries to write to the client would
934 * cause recursion to here, leading to stack overflow and core
935 * dump! This message must go *only* to the postmaster log.
936 *
937 * If errno is zero, assume it's EOF and let the caller complain.
938 */
939 if (errno != 0)
942 errmsg("could not receive data from client: %m")));
943 return EOF;
944 }
945 if (r == 0)
946 {
947 /*
948 * EOF detected. We used to write a log message here, but it's
949 * better to expect the ultimate caller to do that.
950 */
951 return EOF;
952 }
953 /* r contains number of bytes read, so just incr length */
954 PqRecvLength += r;
955 return 0;
956 }
957}
#define PQ_RECV_BUFFER_SIZE
Definition pqcomm.c:121

References COMMERROR, EINTR, ereport, errcode_for_socket_access(), errmsg(), fb(), 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 1832 of file pqcomm.c.

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

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

Referenced by assign_tcp_keepalives_count(), and pq_init().

◆ pq_setkeepalivesidle()

int pq_setkeepalivesidle ( int  idle,
Port port 
)

Definition at line 1668 of file pqcomm.c.

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

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

Referenced by assign_tcp_keepalives_idle(), and pq_init().

◆ pq_setkeepalivesinterval()

int pq_setkeepalivesinterval ( int  interval,
Port port 
)

Definition at line 1753 of file pqcomm.c.

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

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

Referenced by assign_tcp_keepalives_interval(), and pq_init().

◆ pq_settcpusertimeout()

int pq_settcpusertimeout ( int  timeout,
Port port 
)

Definition at line 1907 of file pqcomm.c.

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

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

Referenced by assign_tcp_user_timeout(), and pq_init().

◆ pq_startmsgread()

void pq_startmsgread ( void  )

Definition at line 1142 of file pqcomm.c.

1143{
1144 /*
1145 * There shouldn't be a read active already, but let's check just to be
1146 * sure.
1147 */
1148 if (PqCommReadingMsg)
1149 ereport(FATAL,
1151 errmsg("terminating connection because protocol synchronization was lost")));
1152
1153 PqCommReadingMsg = true;
1154}

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

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

◆ RemoveSocketFiles()

void RemoveSocketFiles ( void  )

Definition at line 849 of file pqcomm.c.

850{
851 ListCell *l;
852
853 /* Loop through all created sockets... */
854 foreach(l, sock_paths)
855 {
856 char *sock_path = (char *) lfirst(l);
857
858 /* Ignore any error. */
860 }
861 /* Since we're about to exit, no need to reclaim storage */
862}
#define lfirst(lc)
Definition pg_list.h:172

References fb(), lfirst, and sock_paths.

Referenced by CloseServerPorts().

◆ Setup_AF_UNIX()

static int Setup_AF_UNIX ( const char sock_path)
static

Definition at line 721 of file pqcomm.c.

722{
723 /* no file system permissions for abstract sockets */
724 if (sock_path[0] == '@')
725 return STATUS_OK;
726
727 /*
728 * Fix socket ownership/permission if requested. Note we must do this
729 * before we listen() to avoid a window where unwanted connections could
730 * get accepted.
731 */
733 if (Unix_socket_group[0] != '\0')
734 {
735#ifdef WIN32
736 elog(WARNING, "configuration item \"unix_socket_group\" is not supported on this platform");
737#else
738 char *endptr;
739 unsigned long val;
740 gid_t gid;
741
742 val = strtoul(Unix_socket_group, &endptr, 10);
743 if (*endptr == '\0')
744 { /* numeric group id */
745 gid = val;
746 }
747 else
748 { /* convert group name to id */
749 struct group *gr;
750
752 if (!gr)
753 {
754 ereport(LOG,
755 (errmsg("group \"%s\" does not exist",
757 return STATUS_ERROR;
758 }
759 gid = gr->gr_gid;
760 }
761 if (chown(sock_path, -1, gid) == -1)
762 {
763 ereport(LOG,
765 errmsg("could not set group of file \"%s\": %m",
766 sock_path)));
767 return STATUS_ERROR;
768 }
769#endif
770 }
771
773 {
774 ereport(LOG,
776 errmsg("could not set permissions of file \"%s\": %m",
777 sock_path)));
778 return STATUS_ERROR;
779 }
780 return STATUS_OK;
781}
int errcode_for_file_access(void)
Definition elog.c:897
#define WARNING
Definition elog.h:36
long val
Definition informix.c:689
int Unix_socket_permissions
Definition pqcomm.c:107
char * Unix_socket_group
Definition pqcomm.c:108
int gid_t
Definition win32_port.h:235

References Assert, elog, ereport, errcode_for_file_access(), errmsg(), fb(), LOG, STATUS_ERROR, STATUS_OK, Unix_socket_group, Unix_socket_permissions, val, and WARNING.

Referenced by ListenServerPort().

◆ show_tcp_keepalives_count()

const char * show_tcp_keepalives_count ( void  )

Definition at line 2021 of file pqcomm.c.

2022{
2023 /* See comments in assign_tcp_keepalives_idle */
2024 static char nbuf[16];
2025
2027 return nbuf;
2028}

References fb(), MyProcPort, pq_getkeepalivescount(), and snprintf.

◆ show_tcp_keepalives_idle()

const char * show_tcp_keepalives_idle ( void  )

Definition at line 1975 of file pqcomm.c.

1976{
1977 /* See comments in assign_tcp_keepalives_idle */
1978 static char nbuf[16];
1979
1981 return nbuf;
1982}

References fb(), MyProcPort, pq_getkeepalivesidle(), and snprintf.

◆ show_tcp_keepalives_interval()

const char * show_tcp_keepalives_interval ( void  )

Definition at line 1998 of file pqcomm.c.

1999{
2000 /* See comments in assign_tcp_keepalives_idle */
2001 static char nbuf[16];
2002
2004 return nbuf;
2005}

References fb(), MyProcPort, pq_getkeepalivesinterval(), and snprintf.

◆ show_tcp_user_timeout()

const char * show_tcp_user_timeout ( void  )

Definition at line 2044 of file pqcomm.c.

2045{
2046 /* See comments in assign_tcp_keepalives_idle */
2047 static char nbuf[16];
2048
2050 return nbuf;
2051}

References fb(), MyProcPort, pq_gettcpusertimeout(), and snprintf.

◆ socket_close()

static void socket_close ( int  code,
Datum  arg 
)
static

Definition at line 350 of file pqcomm.c.

351{
352 /* Nothing to do in a standalone backend, where MyProcPort is NULL. */
353 if (MyProcPort != NULL)
354 {
355#ifdef ENABLE_GSS
356 /*
357 * Shutdown GSSAPI layer. This section does nothing when interrupting
358 * BackendInitialize(), because pg_GSS_recvauth() makes first use of
359 * "ctx" and "cred".
360 *
361 * Note that we don't bother to free MyProcPort->gss, since we're
362 * about to exit anyway.
363 */
364 if (MyProcPort->gss)
365 {
367
368 if (MyProcPort->gss->ctx != GSS_C_NO_CONTEXT)
370
371 if (MyProcPort->gss->cred != GSS_C_NO_CREDENTIAL)
373 }
374#endif /* ENABLE_GSS */
375
376 /*
377 * Cleanly shut down SSL layer. Nowhere else does a postmaster child
378 * call this, so this is safe when interrupting BackendInitialize().
379 */
381
382 /*
383 * Formerly we did an explicit close() here, but it seems better to
384 * leave the socket open until the process dies. This allows clients
385 * to perform a "synchronous close" if they care --- wait till the
386 * transport layer reports connection closure, and you can be sure the
387 * backend has exited.
388 *
389 * We do set sock to PGINVALID_SOCKET to prevent any further I/O,
390 * though.
391 */
393 }
394}
void secure_close(Port *port)
Definition be-secure.c:168
void * gss
Definition libpq-be.h:202
pgsocket sock
Definition libpq-be.h:130

References fb(), 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 335 of file pqcomm.c.

336{
337 /* Do not throw away pending data, but do reset the busy flag */
338 PqCommBusy = false;
339}

References PqCommBusy.

◆ socket_flush()

static int socket_flush ( void  )
static

Definition at line 1328 of file pqcomm.c.

1329{
1330 int res;
1331
1332 /* No-op if reentrant call */
1333 if (PqCommBusy)
1334 return 0;
1335 PqCommBusy = true;
1337 res = internal_flush();
1338 PqCommBusy = false;
1339 return res;
1340}

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

◆ socket_flush_if_writable()

static int socket_flush_if_writable ( void  )
static

Definition at line 1436 of file pqcomm.c.

1437{
1438 int res;
1439
1440 /* Quick exit if nothing to do */
1442 return 0;
1443
1444 /* No-op if reentrant call */
1445 if (PqCommBusy)
1446 return 0;
1447
1448 /* Temporarily put the socket into non-blocking mode */
1450
1451 PqCommBusy = true;
1452 res = internal_flush();
1453 PqCommBusy = false;
1454 return res;
1455}

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

◆ socket_is_send_pending()

static bool socket_is_send_pending ( void  )
static

Definition at line 1462 of file pqcomm.c.

1463{
1464 return (PqSendStart < PqSendPointer);
1465}

References PqSendPointer, and PqSendStart.

◆ socket_putmessage()

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

Definition at line 1492 of file pqcomm.c.

1493{
1494 uint32 n32;
1495
1496 Assert(msgtype != 0);
1497
1498 if (PqCommBusy)
1499 return 0;
1500 PqCommBusy = true;
1501 if (internal_putbytes(&msgtype, 1))
1502 goto fail;
1503
1504 n32 = pg_hton32((uint32) (len + 4));
1505 if (internal_putbytes(&n32, 4))
1506 goto fail;
1507
1508 if (internal_putbytes(s, len))
1509 goto fail;
1510 PqCommBusy = false;
1511 return 0;
1512
1513fail:
1514 PqCommBusy = false;
1515 return EOF;
1516}
uint32_t uint32
Definition c.h:558
#define pg_hton32(x)
Definition pg_bswap.h:121

References Assert, fb(), 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 1525 of file pqcomm.c.

1526{
1528 int required;
1529
1530 /*
1531 * Ensure we have enough space in the output buffer for the message header
1532 * as well as the message itself.
1533 */
1534 required = PqSendPointer + 1 + 4 + len;
1535 if (required > PqSendBufferSize)
1536 {
1537 PqSendBuffer = repalloc(PqSendBuffer, required);
1539 }
1540 res = pq_putmessage(msgtype, s, len);
1541 Assert(res == 0); /* should not fail when the message fits in
1542 * buffer */
1543}
#define pq_putmessage(msgtype, s, len)
Definition libpq.h:52
void * repalloc(void *pointer, Size size)
Definition mcxt.c:1632

References Assert, fb(), len, PG_USED_FOR_ASSERTS_ONLY, pq_putmessage, PqSendBuffer, PqSendBufferSize, PqSendPointer, and repalloc().

◆ socket_set_nonblocking()

static void socket_set_nonblocking ( bool  nonblocking)
static

Definition at line 881 of file pqcomm.c.

882{
883 if (MyProcPort == NULL)
886 errmsg("there is no client connection")));
887
888 MyProcPort->noblock = nonblocking;
889}
#define ERROR
Definition elog.h:39
bool noblock
Definition libpq-be.h:131

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

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

◆ TouchSocketFiles()

void TouchSocketFiles ( void  )

Definition at line 831 of file pqcomm.c.

832{
833 ListCell *l;
834
835 /* Loop through all created sockets... */
836 foreach(l, sock_paths)
837 {
838 char *sock_path = (char *) lfirst(l);
839
840 /* Ignore errors; there's no point in complaining */
842 }
843}

References fb(), lfirst, and sock_paths.

Referenced by ServerLoop().

Variable Documentation

◆ FeBeWaitSet

◆ PqCommBusy

bool PqCommBusy
static

◆ PqCommMethods

Definition at line 165 of file pqcomm.c.

Referenced by pq_redirect_to_shm_mq(), and pq_set_parallel_leader().

◆ PqCommReadingMsg

◆ PqCommSocketMethods

const PQcommMethods PqCommSocketMethods
static
Initial value:
= {
.comm_reset = socket_comm_reset,
.flush = socket_flush,
.flush_if_writable = socket_flush_if_writable,
.is_send_pending = socket_is_send_pending,
.putmessage = socket_putmessage,
.putmessage_noblock = socket_putmessage_noblock
}
static int socket_flush_if_writable(void)
Definition pqcomm.c:1436
static int socket_flush(void)
Definition pqcomm.c:1328
static void socket_comm_reset(void)
Definition pqcomm.c:335
static bool socket_is_send_pending(void)
Definition pqcomm.c:1462
static int socket_putmessage(char msgtype, const char *s, size_t len)
Definition pqcomm.c:1492
static void socket_putmessage_noblock(char msgtype, const char *s, size_t len)
Definition pqcomm.c:1525

Definition at line 156 of file pqcomm.c.

156 {
157 .comm_reset = socket_comm_reset,
158 .flush = socket_flush,
159 .flush_if_writable = socket_flush_if_writable,
160 .is_send_pending = socket_is_send_pending,
161 .putmessage = socket_putmessage,
162 .putmessage_noblock = socket_putmessage_noblock
163};

◆ PqRecvBuffer

char PqRecvBuffer[PQ_RECV_BUFFER_SIZE]
static

Definition at line 128 of file pqcomm.c.

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

◆ PqRecvLength

◆ PqRecvPointer

◆ PqSendBuffer

char* PqSendBuffer
static

Definition at line 123 of file pqcomm.c.

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

◆ PqSendBufferSize

int PqSendBufferSize
static

Definition at line 124 of file pqcomm.c.

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

◆ PqSendPointer

◆ PqSendStart

size_t PqSendStart
static

◆ sock_paths

List* sock_paths = NIL
static

Definition at line 111 of file pqcomm.c.

Referenced by Lock_AF_UNIX(), RemoveSocketFiles(), and TouchSocketFiles().

◆ Unix_socket_group

char* Unix_socket_group

Definition at line 108 of file pqcomm.c.

Referenced by Setup_AF_UNIX().

◆ Unix_socket_permissions

int Unix_socket_permissions

Definition at line 107 of file pqcomm.c.

Referenced by Setup_AF_UNIX(), and show_unix_socket_permissions().