PostgreSQL Source Code git master
Loading...
Searching...
No Matches
libpq.h File Reference
#include <netinet/in.h>
#include "lib/stringinfo.h"
#include "libpq/libpq-be.h"
Include dependency graph for libpq.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  PQcommMethods
 

Macros

#define PQ_SMALL_MESSAGE_LIMIT   10000
 
#define PQ_LARGE_MESSAGE_LIMIT   (MaxAllocSize - 1)
 
#define pq_comm_reset()   (PqCommMethods->comm_reset())
 
#define pq_flush()   (PqCommMethods->flush())
 
#define pq_flush_if_writable()   (PqCommMethods->flush_if_writable())
 
#define pq_is_send_pending()   (PqCommMethods->is_send_pending())
 
#define pq_putmessage(msgtype, s, len)    (PqCommMethods->putmessage(msgtype, s, len))
 
#define pq_putmessage_noblock(msgtype, s, len)    (PqCommMethods->putmessage_noblock(msgtype, s, len))
 
#define FeBeWaitSetSocketPos   0
 
#define FeBeWaitSetLatchPos   1
 
#define FeBeWaitSetNEvents   3
 
#define SSL_LIBRARY   ""
 
#define DEFAULT_SSL_CIPHERS   "none"
 
#define DEFAULT_SSL_GROUPS   "none"
 

Typedefs

typedef struct WaitEventSet WaitEventSet
 

Enumerations

enum  ssl_protocol_versions {
  PG_TLS_ANY = 0 , PG_TLS1_VERSION , PG_TLS1_1_VERSION , PG_TLS1_2_VERSION ,
  PG_TLS1_3_VERSION
}
 

Functions

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)
 
Portpq_init (ClientSocket *client_sock)
 
int pq_getbytes (void *b, size_t len)
 
void pq_startmsgread (void)
 
void pq_endmsgread (void)
 
bool pq_is_reading_msg (void)
 
int pq_getmessage (StringInfo s, int maxlen)
 
int pq_getbyte (void)
 
int pq_peekbyte (void)
 
int pq_getbyte_if_available (unsigned char *c)
 
ssize_t pq_buffer_remaining_data (void)
 
int pq_putmessage_v2 (char msgtype, const char *s, size_t len)
 
bool pq_check_connection (void)
 
int secure_initialize (bool isServerStart)
 
bool secure_loaded_verify_locations (void)
 
void secure_destroy (void)
 
int secure_open_server (Port *port)
 
void secure_close (Port *port)
 
ssize_t secure_read (Port *port, void *ptr, size_t len)
 
ssize_t secure_write (Port *port, const void *ptr, size_t len)
 
ssize_t secure_raw_read (Port *port, void *ptr, size_t len)
 
ssize_t secure_raw_write (Port *port, const void *ptr, size_t len)
 
int run_ssl_passphrase_command (const char *prompt, bool is_server_start, char *buf, int size)
 
bool check_ssl_key_file_permissions (const char *ssl_key_file, bool isServerStart)
 

Variables

const PGDLLIMPORT PQcommMethodsPqCommMethods
 
PGDLLIMPORT WaitEventSetFeBeWaitSet
 
PGDLLIMPORT charssl_library
 
PGDLLIMPORT charssl_ca_file
 
PGDLLIMPORT charssl_cert_file
 
PGDLLIMPORT charssl_crl_file
 
PGDLLIMPORT charssl_crl_dir
 
PGDLLIMPORT charssl_key_file
 
PGDLLIMPORT int ssl_min_protocol_version
 
PGDLLIMPORT int ssl_max_protocol_version
 
PGDLLIMPORT charssl_passphrase_command
 
PGDLLIMPORT bool ssl_passphrase_command_supports_reload
 
PGDLLIMPORT charssl_dh_params_file
 
PGDLLIMPORT charSSLCipherSuites
 
PGDLLIMPORT charSSLCipherList
 
PGDLLIMPORT charSSLECDHCurve
 
PGDLLIMPORT bool SSLPreferServerCiphers
 

Macro Definition Documentation

◆ DEFAULT_SSL_CIPHERS

#define DEFAULT_SSL_CIPHERS   "none"

Definition at line 133 of file libpq.h.

◆ DEFAULT_SSL_GROUPS

#define DEFAULT_SSL_GROUPS   "none"

Definition at line 139 of file libpq.h.

◆ FeBeWaitSetLatchPos

#define FeBeWaitSetLatchPos   1

Definition at line 67 of file libpq.h.

◆ FeBeWaitSetNEvents

#define FeBeWaitSetNEvents   3

Definition at line 68 of file libpq.h.

◆ FeBeWaitSetSocketPos

#define FeBeWaitSetSocketPos   0

Definition at line 66 of file libpq.h.

◆ pq_comm_reset

#define pq_comm_reset ( )    (PqCommMethods->comm_reset())

Definition at line 48 of file libpq.h.

◆ pq_flush

#define pq_flush ( )    (PqCommMethods->flush())

Definition at line 49 of file libpq.h.

◆ pq_flush_if_writable

#define pq_flush_if_writable ( )    (PqCommMethods->flush_if_writable())

Definition at line 50 of file libpq.h.

◆ pq_is_send_pending

#define pq_is_send_pending ( )    (PqCommMethods->is_send_pending())

Definition at line 51 of file libpq.h.

◆ PQ_LARGE_MESSAGE_LIMIT

#define PQ_LARGE_MESSAGE_LIMIT   (MaxAllocSize - 1)

Definition at line 34 of file libpq.h.

◆ pq_putmessage

#define pq_putmessage (   msgtype,
  s,
  len 
)     (PqCommMethods->putmessage(msgtype, s, len))

Definition at line 52 of file libpq.h.

131 :MEDIUM:+3DES:!aNULL"
132#else
133#define DEFAULT_SSL_CIPHERS "none"
134#endif
135
136#ifdef USE_SSL
137#define DEFAULT_SSL_GROUPS "X25519:prime256v1"
138#else
139#define DEFAULT_SSL_GROUPS "none"
140#endif
141
142/*
143 * prototypes for functions in be-secure-gssapi.c
144 */
145#ifdef ENABLE_GSS
146extern ssize_t secure_open_gssapi(Port *port);
147#endif
148
149enum ssl_protocol_versions
150{
151 PG_TLS_ANY = 0,
152 PG_TLS1_VERSION,
153 PG_TLS1_1_VERSION,
154 PG_TLS1_2_VERSION,
155 PG_TLS1_3_VERSION,
156};
157
158/*
159 * prototypes for functions in be-secure-common.c
160 */
161extern int run_ssl_passphrase_command(const char *prompt, bool is_server_start,
162 char *buf, int size);
163extern bool check_ssl_key_file_permissions(const char *ssl_key_file,
164 bool isServerStart);
165
166#endif /* LIBPQ_H */
#define none
Definition predtest.c:1671
static int fb(int x)

◆ pq_putmessage_noblock

#define pq_putmessage_noblock (   msgtype,
  s,
  len 
)     (PqCommMethods->putmessage_noblock(msgtype, s, len))

Definition at line 54 of file libpq.h.

◆ PQ_SMALL_MESSAGE_LIMIT

#define PQ_SMALL_MESSAGE_LIMIT   10000

Definition at line 33 of file libpq.h.

◆ SSL_LIBRARY

#define SSL_LIBRARY   ""

Definition at line 127 of file libpq.h.

Typedef Documentation

◆ WaitEventSet

Definition at line 24 of file libpq.h.

Enumeration Type Documentation

◆ ssl_protocol_versions

Enumerator
PG_TLS_ANY 
PG_TLS1_VERSION 
PG_TLS1_1_VERSION 
PG_TLS1_2_VERSION 
PG_TLS1_3_VERSION 

Definition at line 149 of file libpq.h.

150{
151 PG_TLS_ANY = 0,
156};
@ PG_TLS1_VERSION
Definition libpq.h:152
@ PG_TLS1_3_VERSION
Definition libpq.h:155
@ PG_TLS1_1_VERSION
Definition libpq.h:153
@ PG_TLS1_2_VERSION
Definition libpq.h:154
@ PG_TLS_ANY
Definition libpq.h:151

Function Documentation

◆ AcceptConnection()

int AcceptConnection ( pgsocket  server_fd,
ClientSocket client_sock 
)
extern

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:1221
#define STATUS_ERROR
Definition c.h:1222
int errcode_for_socket_access(void)
Definition elog.c:976
#define LOG
Definition elog.h:31
#define ereport(elevel,...)
Definition elog.h:150
static char * errmsg
#define PGINVALID_SOCKET
Definition port.h:31
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().

◆ check_ssl_key_file_permissions()

bool check_ssl_key_file_permissions ( const char ssl_key_file,
bool  isServerStart 
)
extern

Definition at line 114 of file be-secure-common.c.

115{
117 struct stat buf;
118
119 if (stat(ssl_key_file, &buf) != 0)
120 {
123 errmsg("could not access private key file \"%s\": %m",
124 ssl_key_file)));
125 return false;
126 }
127
128 /* Key file must be a regular file */
129 if (!S_ISREG(buf.st_mode))
130 {
133 errmsg("private key file \"%s\" is not a regular file",
134 ssl_key_file)));
135 return false;
136 }
137
138 /*
139 * Refuse to load key files owned by users other than us or root, and
140 * require no public access to the key file. If the file is owned by us,
141 * require mode 0600 or less. If owned by root, require 0640 or less to
142 * allow read access through either our gid or a supplementary gid that
143 * allows us to read system-wide certificates.
144 *
145 * Note that roughly similar checks are performed in
146 * src/interfaces/libpq/fe-secure-openssl.c so any changes here may need
147 * to be made there as well. The environment is different though; this
148 * code can assume that we're not running as root.
149 *
150 * Ideally we would do similar permissions checks on Windows, but it is
151 * not clear how that would work since Unix-style permissions may not be
152 * available.
153 */
154#if !defined(WIN32) && !defined(__CYGWIN__)
155 if (buf.st_uid != geteuid() && buf.st_uid != 0)
156 {
159 errmsg("private key file \"%s\" must be owned by the database user or root",
160 ssl_key_file)));
161 return false;
162 }
163
164 if ((buf.st_uid == geteuid() && buf.st_mode & (S_IRWXG | S_IRWXO)) ||
165 (buf.st_uid == 0 && buf.st_mode & (S_IWGRP | S_IXGRP | S_IRWXO)))
166 {
169 errmsg("private key file \"%s\" has group or world access",
171 errdetail("File must have permissions u=rw (0600) or less if owned by the database user, or permissions u=rw,g=r (0640) or less if owned by root.")));
172 return false;
173 }
174#endif
175
176 return true;
177}
char * ssl_key_file
Definition be-secure.c:39
int errcode_for_file_access(void)
Definition elog.c:897
int errcode(int sqlerrcode)
Definition elog.c:874
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define FATAL
Definition elog.h:41
static char buf[DEFAULT_XLOG_SEG_SIZE]
#define S_IXGRP
Definition win32_port.h:297
#define stat
Definition win32_port.h:74
#define S_IRWXG
Definition win32_port.h:300
#define S_IRWXO
Definition win32_port.h:312
#define S_ISREG(m)
Definition win32_port.h:318
#define S_IWGRP
Definition win32_port.h:294

References buf, ereport, errcode(), errcode_for_file_access(), errdetail(), errmsg, FATAL, fb(), LOG, S_IRWXG, S_IRWXO, S_ISREG, S_IWGRP, S_IXGRP, ssl_key_file, and stat.

Referenced by be_tls_init().

◆ ListenServerPort()

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

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:1070
#define _(x)
Definition elog.c:95
int errhint(const char *fmt,...) pg_attribute_printf(1
#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().

◆ pq_buffer_remaining_data()

ssize_t pq_buffer_remaining_data ( void  )
extern

Definition at line 1128 of file pqcomm.c.

1129{
1131 return (PqRecvLength - PqRecvPointer);
1132}
#define Assert(condition)
Definition c.h:906
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  )
extern

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:836
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_endmsgread()

void pq_endmsgread ( void  )
extern

Definition at line 1166 of file pqcomm.c.

1167{
1169
1170 PqCommReadingMsg = false;
1171}
static bool PqCommReadingMsg
Definition pqcomm.c:136

References Assert, and PqCommReadingMsg.

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

◆ pq_getbyte()

int pq_getbyte ( void  )
extern

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 int pq_recvbuf(void)
Definition pqcomm.c:898
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)
extern

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
#define COMMERROR
Definition elog.h:33
struct Port * MyProcPort
Definition globals.c:51
static void socket_set_nonblocking(bool nonblocking)
Definition pqcomm.c:881
char * c
#define EINTR
Definition win32_port.h:361
#define EWOULDBLOCK
Definition win32_port.h:367
#define EAGAIN
Definition win32_port.h:359

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 
)
extern

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}
int b
Definition isn.c:74
const void size_t len

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

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

◆ pq_getmessage()

int pq_getmessage ( StringInfo  s,
int  maxlen 
)
extern

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:575
#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_init()

Port * pq_init ( ClientSocket client_sock)
extern

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
static int port
Definition pg_regress.c:115
bool pg_set_noblock(pgsocket sock)
Definition noblock.c:25
int pq_setkeepalivesinterval(int interval, Port *port)
Definition pqcomm.c:1753
static size_t PqSendPointer
Definition pqcomm.c:125
int pq_settcpusertimeout(int timeout, Port *port)
Definition pqcomm.c:1907
#define PQ_SEND_BUFFER_SIZE
Definition pqcomm.c:120
int pq_setkeepalivesidle(int idle, Port *port)
Definition pqcomm.c:1668
static char * PqSendBuffer
Definition pqcomm.c:123
static bool PqCommBusy
Definition pqcomm.c:135
static void socket_close(int code, Datum arg)
Definition pqcomm.c:350
static int PqSendBufferSize
Definition pqcomm.c:124
int pq_setkeepalivescount(int count, Port *port)
Definition pqcomm.c:1832
static size_t PqSendStart
Definition pqcomm.c:126
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  )
extern

Definition at line 1182 of file pqcomm.c.

1183{
1184 return PqCommReadingMsg;
1185}

References PqCommReadingMsg.

Referenced by PostgresMain().

◆ pq_peekbyte()

int pq_peekbyte ( void  )
extern

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 
)
extern

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_startmsgread()

void pq_startmsgread ( void  )
extern

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  )
extern

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
static List * sock_paths
Definition pqcomm.c:111

References fb(), lfirst, and sock_paths.

Referenced by CloseServerPorts().

◆ run_ssl_passphrase_command()

int run_ssl_passphrase_command ( const char prompt,
bool  is_server_start,
char buf,
int  size 
)
extern

Definition at line 40 of file be-secure-common.c.

41{
43 char *command;
44 FILE *fh;
45 int pclose_rc;
46 size_t len = 0;
47
49 Assert(size > 0);
50 buf[0] = '\0';
51
52 command = replace_percent_placeholders(ssl_passphrase_command, "ssl_passphrase_command", "p", prompt);
53
54 fh = OpenPipeStream(command, "r");
55 if (fh == NULL)
56 {
59 errmsg("could not execute command \"%s\": %m",
60 command)));
61 goto error;
62 }
63
64 if (!fgets(buf, size, fh))
65 {
66 if (ferror(fh))
67 {
68 explicit_bzero(buf, size);
71 errmsg("could not read from command \"%s\": %m",
72 command)));
73 goto error;
74 }
75 }
76
78 if (pclose_rc == -1)
79 {
80 explicit_bzero(buf, size);
83 errmsg("could not close pipe to external command: %m")));
84 goto error;
85 }
86 else if (pclose_rc != 0)
87 {
88 char *reason;
89
90 explicit_bzero(buf, size);
94 errmsg("command \"%s\" failed",
95 command),
96 errdetail_internal("%s", reason)));
97 pfree(reason);
98 goto error;
99 }
100
101 /* strip trailing newline and carriage return */
103
104error:
105 pfree(command);
106 return len;
107}
char * ssl_passphrase_command
Definition be-secure.c:44
int int errdetail_internal(const char *fmt,...) pg_attribute_printf(1
#define ERROR
Definition elog.h:39
FILE * OpenPipeStream(const char *command, const char *mode)
Definition fd.c:2731
int ClosePipeStream(FILE *file)
Definition fd.c:3039
void pfree(void *pointer)
Definition mcxt.c:1616
char * replace_percent_placeholders(const char *instr, const char *param_name, const char *letters,...)
Definition percentrepl.c:59
void explicit_bzero(void *buf, size_t len)
static void error(void)
int pg_strip_crlf(char *str)
Definition string.c:154
char * wait_result_to_str(int exitstatus)
Definition wait_error.c:33

References Assert, buf, ClosePipeStream(), ereport, errcode_for_file_access(), errdetail_internal(), errmsg, ERROR, error(), explicit_bzero(), fb(), len, LOG, OpenPipeStream(), pfree(), pg_strip_crlf(), replace_percent_placeholders(), ssl_passphrase_command, and wait_result_to_str().

Referenced by ssl_external_passwd_cb().

◆ secure_close()

void secure_close ( Port port)
extern

Definition at line 168 of file be-secure.c.

169{
170#ifdef USE_SSL
171 if (port->ssl_in_use)
173#endif
174}
void be_tls_close(Port *port)

References be_tls_close(), and port.

Referenced by socket_close().

◆ secure_destroy()

void secure_destroy ( void  )
extern

Definition at line 89 of file be-secure.c.

90{
91#ifdef USE_SSL
93#endif
94}
void be_tls_destroy(void)

References be_tls_destroy().

Referenced by process_pm_reload_request().

◆ secure_initialize()

int secure_initialize ( bool  isServerStart)
extern

Definition at line 76 of file be-secure.c.

77{
78#ifdef USE_SSL
80#else
81 return 0;
82#endif
83}
int be_tls_init(bool isServerStart)

References be_tls_init(), and fb().

Referenced by BackendMain(), PostmasterMain(), and process_pm_reload_request().

◆ secure_loaded_verify_locations()

bool secure_loaded_verify_locations ( void  )
extern

Definition at line 100 of file be-secure.c.

101{
102#ifdef USE_SSL
104#else
105 return false;
106#endif
107}

References fb().

Referenced by ClientAuthentication().

◆ secure_open_server()

int secure_open_server ( Port port)
extern

Definition at line 113 of file be-secure.c.

114{
115#ifdef USE_SSL
116 int r = 0;
117 ssize_t len;
118
119 /* push unencrypted buffered data back through SSL setup */
121 if (len > 0)
122 {
123 char *buf = palloc(len);
124
126 if (pq_getbytes(buf, len) == EOF)
127 return STATUS_ERROR; /* shouldn't be possible */
129 port->raw_buf = buf;
130 port->raw_buf_remaining = len;
131 port->raw_buf_consumed = 0;
132 }
134
135 INJECTION_POINT("backend-ssl-startup", NULL);
136
138
139 if (port->raw_buf_remaining > 0)
140 {
141 /*
142 * This shouldn't be possible -- it would mean the client sent
143 * encrypted data before we established a session key...
144 */
145 elog(LOG, "buffered unencrypted data remains after negotiating SSL connection");
146 return STATUS_ERROR;
147 }
148 if (port->raw_buf != NULL)
149 {
150 pfree(port->raw_buf);
151 port->raw_buf = NULL;
152 }
153
155 (errmsg_internal("SSL connection from DN:\"%s\" CN:\"%s\"",
156 port->peer_dn ? port->peer_dn : "(anonymous)",
157 port->peer_cn ? port->peer_cn : "(anonymous)")));
158 return r;
159#else
160 return 0;
161#endif
162}
int be_tls_open_server(Port *port)
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
#define DEBUG2
Definition elog.h:29
#define INJECTION_POINT(name, arg)
void * palloc(Size size)
Definition mcxt.c:1387
ssize_t pq_buffer_remaining_data(void)
Definition pqcomm.c:1128
void pq_endmsgread(void)
Definition pqcomm.c:1166
void pq_startmsgread(void)
Definition pqcomm.c:1142

References Assert, be_tls_open_server(), buf, DEBUG2, elog, ereport, errmsg_internal(), fb(), INJECTION_POINT, len, LOG, palloc(), pfree(), port, pq_buffer_remaining_data(), pq_endmsgread(), pq_getbytes(), pq_startmsgread(), and STATUS_ERROR.

Referenced by ProcessSSLStartup(), and ProcessStartupPacket().

◆ secure_raw_read()

ssize_t secure_raw_read ( Port port,
void ptr,
size_t  len 
)
extern

Definition at line 269 of file be-secure.c.

270{
271 ssize_t n;
272
273 /* Read from the "unread" buffered data first. c.f. libpq-be.h */
274 if (port->raw_buf_remaining > 0)
275 {
276 /* consume up to len bytes from the raw_buf */
277 if (len > port->raw_buf_remaining)
278 len = port->raw_buf_remaining;
279 Assert(port->raw_buf);
280 memcpy(ptr, port->raw_buf + port->raw_buf_consumed, len);
281 port->raw_buf_consumed += len;
282 port->raw_buf_remaining -= len;
283 return len;
284 }
285
286 /*
287 * Try to read from the socket without blocking. If it succeeds we're
288 * done, otherwise we'll wait for the socket using the latch mechanism.
289 */
290#ifdef WIN32
291 pgwin32_noblock = true;
292#endif
293 n = recv(port->sock, ptr, len, 0);
294#ifdef WIN32
295 pgwin32_noblock = false;
296#endif
297
298 return n;
299}
int pgwin32_noblock
Definition socket.c:28
#define recv(s, buf, len, flags)
Definition win32_port.h:501

References Assert, fb(), len, pgwin32_noblock, port, and recv.

Referenced by be_gssapi_read(), port_bio_read(), read_or_wait(), and secure_read().

◆ secure_raw_write()

ssize_t secure_raw_write ( Port port,
const void ptr,
size_t  len 
)
extern

Definition at line 378 of file be-secure.c.

379{
380 ssize_t n;
381
382#ifdef WIN32
383 pgwin32_noblock = true;
384#endif
385 n = send(port->sock, ptr, len, 0);
386#ifdef WIN32
387 pgwin32_noblock = false;
388#endif
389
390 return n;
391}
#define send(s, buf, len, flags)
Definition win32_port.h:502

References fb(), len, pgwin32_noblock, port, and send.

Referenced by be_gssapi_write(), port_bio_write(), secure_open_gssapi(), and secure_write().

◆ secure_read()

ssize_t secure_read ( Port port,
void ptr,
size_t  len 
)
extern

Definition at line 180 of file be-secure.c.

181{
182 ssize_t n;
183 int waitfor;
184
185 /* Deal with any already-pending interrupt condition. */
187
188retry:
189#ifdef USE_SSL
190 waitfor = 0;
191 if (port->ssl_in_use)
192 {
193 n = be_tls_read(port, ptr, len, &waitfor);
194 }
195 else
196#endif
197#ifdef ENABLE_GSS
198 if (port->gss && port->gss->enc)
199 {
200 n = be_gssapi_read(port, ptr, len);
202 }
203 else
204#endif
205 {
206 n = secure_raw_read(port, ptr, len);
208 }
209
210 /* In blocking mode, wait until the socket is ready */
211 if (n < 0 && !port->noblock && (errno == EWOULDBLOCK || errno == EAGAIN))
212 {
213 WaitEvent event;
214
216
218
219 WaitEventSetWait(FeBeWaitSet, -1 /* no timeout */ , &event, 1,
221
222 /*
223 * If the postmaster has died, it's not safe to continue running,
224 * because it is the postmaster's job to kill us if some other backend
225 * exits uncleanly. Moreover, we won't run very well in this state;
226 * helper processes like walwriter and the bgwriter will exit, so
227 * performance may be poor. Finally, if we don't exit, pg_ctl will be
228 * unable to restart the postmaster without manual intervention, so no
229 * new connections can be accepted. Exiting clears the deck for a
230 * postmaster restart.
231 *
232 * (Note that we only make this check when we would otherwise sleep on
233 * our latch. We might still continue running for a while if the
234 * postmaster is killed in mid-query, or even through multiple queries
235 * if we never have to wait for read. We don't want to burn too many
236 * cycles checking for this very rare condition, and this should cause
237 * us to exit quickly in most cases.)
238 */
239 if (event.events & WL_POSTMASTER_DEATH)
242 errmsg("terminating connection due to unexpected postmaster exit")));
243
244 /* Handle interrupt. */
245 if (event.events & WL_LATCH_SET)
246 {
249
250 /*
251 * We'll retry the read. Most likely it will return immediately
252 * because there's still no data available, and we'll wait for the
253 * socket to become ready again.
254 */
255 }
256 goto retry;
257 }
258
259 /*
260 * Process interrupts that happened during a successful (or non-blocking,
261 * or hard-failed) read.
262 */
264
265 return n;
266}
ssize_t be_gssapi_read(Port *port, void *ptr, size_t len)
ssize_t be_tls_read(Port *port, void *ptr, size_t len, int *waitfor)
ssize_t secure_raw_read(Port *port, void *ptr, size_t len)
Definition be-secure.c:269
void ProcessClientReadInterrupt(bool blocked)
Definition postgres.c:501
uint32 events
#define WL_SOCKET_READABLE

References Assert, be_gssapi_read(), be_tls_read(), EAGAIN, ereport, errcode(), errmsg, WaitEvent::events, EWOULDBLOCK, FATAL, fb(), FeBeWaitSet, FeBeWaitSetSocketPos, len, ModifyWaitEvent(), MyLatch, port, ProcessClientReadInterrupt(), ResetLatch(), secure_raw_read(), WaitEventSetWait(), WL_LATCH_SET, WL_POSTMASTER_DEATH, and WL_SOCKET_READABLE.

Referenced by pq_getbyte_if_available(), and pq_recvbuf().

◆ secure_write()

ssize_t secure_write ( Port port,
const void ptr,
size_t  len 
)
extern

Definition at line 306 of file be-secure.c.

307{
308 ssize_t n;
309 int waitfor;
310
311 /* Deal with any already-pending interrupt condition. */
313
314retry:
315 waitfor = 0;
316#ifdef USE_SSL
317 if (port->ssl_in_use)
318 {
319 n = be_tls_write(port, ptr, len, &waitfor);
320 }
321 else
322#endif
323#ifdef ENABLE_GSS
324 if (port->gss && port->gss->enc)
325 {
326 n = be_gssapi_write(port, ptr, len);
328 }
329 else
330#endif
331 {
332 n = secure_raw_write(port, ptr, len);
334 }
335
336 if (n < 0 && !port->noblock && (errno == EWOULDBLOCK || errno == EAGAIN))
337 {
338 WaitEvent event;
339
341
343
344 WaitEventSetWait(FeBeWaitSet, -1 /* no timeout */ , &event, 1,
346
347 /* See comments in secure_read. */
348 if (event.events & WL_POSTMASTER_DEATH)
351 errmsg("terminating connection due to unexpected postmaster exit")));
352
353 /* Handle interrupt. */
354 if (event.events & WL_LATCH_SET)
355 {
358
359 /*
360 * We'll retry the write. Most likely it will return immediately
361 * because there's still no buffer space available, and we'll wait
362 * for the socket to become ready again.
363 */
364 }
365 goto retry;
366 }
367
368 /*
369 * Process interrupts that happened during a successful (or non-blocking,
370 * or hard-failed) write.
371 */
373
374 return n;
375}
ssize_t be_gssapi_write(Port *port, const void *ptr, size_t len)
ssize_t be_tls_write(Port *port, const void *ptr, size_t len, int *waitfor)
ssize_t secure_raw_write(Port *port, const void *ptr, size_t len)
Definition be-secure.c:378
void ProcessClientWriteInterrupt(bool blocked)
Definition postgres.c:547

References Assert, be_gssapi_write(), be_tls_write(), EAGAIN, ereport, errcode(), errmsg, WaitEvent::events, EWOULDBLOCK, FATAL, fb(), FeBeWaitSet, FeBeWaitSetSocketPos, len, ModifyWaitEvent(), MyLatch, port, ProcessClientWriteInterrupt(), ResetLatch(), secure_raw_write(), WaitEventSetWait(), WL_LATCH_SET, WL_POSTMASTER_DEATH, and WL_SOCKET_WRITEABLE.

Referenced by internal_flush_buffer(), and ProcessStartupPacket().

◆ TouchSocketFiles()

void TouchSocketFiles ( void  )
extern

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

◆ PqCommMethods

const PGDLLIMPORT PQcommMethods* PqCommMethods
extern

Definition at line 165 of file pqcomm.c.

Referenced by pq_redirect_to_shm_mq(), and pq_set_parallel_leader().

◆ ssl_ca_file

PGDLLIMPORT char* ssl_ca_file
extern

Definition at line 40 of file be-secure.c.

Referenced by be_tls_init().

◆ ssl_cert_file

PGDLLIMPORT char* ssl_cert_file
extern

Definition at line 38 of file be-secure.c.

Referenced by be_tls_init().

◆ ssl_crl_dir

PGDLLIMPORT char* ssl_crl_dir
extern

Definition at line 42 of file be-secure.c.

Referenced by be_tls_init().

◆ ssl_crl_file

PGDLLIMPORT char* ssl_crl_file
extern

Definition at line 41 of file be-secure.c.

Referenced by be_tls_init().

◆ ssl_dh_params_file

PGDLLIMPORT char* ssl_dh_params_file
extern

Definition at line 43 of file be-secure.c.

Referenced by initialize_dh().

◆ ssl_key_file

PGDLLIMPORT char* ssl_key_file
extern

Definition at line 39 of file be-secure.c.

Referenced by be_tls_init(), and check_ssl_key_file_permissions().

◆ ssl_library

PGDLLIMPORT char* ssl_library
extern

Definition at line 37 of file be-secure.c.

◆ ssl_max_protocol_version

PGDLLIMPORT int ssl_max_protocol_version
extern

Definition at line 62 of file be-secure.c.

Referenced by be_tls_init(), and be_tls_open_server().

◆ ssl_min_protocol_version

PGDLLIMPORT int ssl_min_protocol_version
extern

Definition at line 61 of file be-secure.c.

Referenced by be_tls_init(), and be_tls_open_server().

◆ ssl_passphrase_command

PGDLLIMPORT char* ssl_passphrase_command
extern

Definition at line 44 of file be-secure.c.

Referenced by default_openssl_tls_init(), run_ssl_passphrase_command(), and set_rot13().

◆ ssl_passphrase_command_supports_reload

PGDLLIMPORT bool ssl_passphrase_command_supports_reload
extern

Definition at line 45 of file be-secure.c.

Referenced by default_openssl_tls_init().

◆ SSLCipherList

PGDLLIMPORT char* SSLCipherList
extern

Definition at line 53 of file be-secure.c.

Referenced by be_tls_init().

◆ SSLCipherSuites

PGDLLIMPORT char* SSLCipherSuites
extern

Definition at line 52 of file be-secure.c.

Referenced by be_tls_init().

◆ SSLECDHCurve

PGDLLIMPORT char* SSLECDHCurve
extern

Definition at line 56 of file be-secure.c.

Referenced by initialize_ecdh().

◆ SSLPreferServerCiphers

PGDLLIMPORT bool SSLPreferServerCiphers
extern

Definition at line 59 of file be-secure.c.

Referenced by be_tls_init().