PostgreSQL Source Code  git master
libpq.h File Reference
#include <netinet/in.h>
#include "lib/stringinfo.h"
#include "libpq/libpq-be.h"
#include "storage/latch.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
 

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 ListenSocket[], 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 (char *s, 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)
 
bool pq_buffer_has_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, 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 char * ssl_library
 
PGDLLIMPORT char * ssl_cert_file
 
PGDLLIMPORT char * ssl_key_file
 
PGDLLIMPORT char * ssl_ca_file
 
PGDLLIMPORT char * ssl_crl_file
 
PGDLLIMPORT char * ssl_crl_dir
 
PGDLLIMPORT char * ssl_dh_params_file
 
PGDLLIMPORT char * ssl_passphrase_command
 
PGDLLIMPORT bool ssl_passphrase_command_supports_reload
 
PGDLLIMPORT char * SSLCipherSuites
 
PGDLLIMPORT char * SSLECDHCurve
 
PGDLLIMPORT bool SSLPreferServerCiphers
 
PGDLLIMPORT int ssl_min_protocol_version
 
PGDLLIMPORT int ssl_max_protocol_version
 

Macro Definition Documentation

◆ FeBeWaitSetLatchPos

#define FeBeWaitSetLatchPos   1

Definition at line 64 of file libpq.h.

◆ FeBeWaitSetNEvents

#define FeBeWaitSetNEvents   3

Definition at line 65 of file libpq.h.

◆ FeBeWaitSetSocketPos

#define FeBeWaitSetSocketPos   0

Definition at line 63 of file libpq.h.

◆ pq_comm_reset

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

Definition at line 45 of file libpq.h.

◆ pq_flush

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

Definition at line 46 of file libpq.h.

◆ pq_flush_if_writable

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

Definition at line 47 of file libpq.h.

◆ pq_is_send_pending

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

Definition at line 48 of file libpq.h.

◆ PQ_LARGE_MESSAGE_LIMIT

#define PQ_LARGE_MESSAGE_LIMIT   (MaxAllocSize - 1)

Definition at line 31 of file libpq.h.

◆ pq_putmessage

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

Definition at line 49 of file libpq.h.

◆ pq_putmessage_noblock

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

Definition at line 51 of file libpq.h.

◆ PQ_SMALL_MESSAGE_LIMIT

#define PQ_SMALL_MESSAGE_LIMIT   10000

Definition at line 30 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 126 of file libpq.h.

127 {
128  PG_TLS_ANY = 0,
133 };
@ PG_TLS1_VERSION
Definition: libpq.h:129
@ PG_TLS1_3_VERSION
Definition: libpq.h:132
@ PG_TLS1_1_VERSION
Definition: libpq.h:130
@ PG_TLS1_2_VERSION
Definition: libpq.h:131
@ PG_TLS_ANY
Definition: libpq.h:128

Function Documentation

◆ AcceptConnection()

int AcceptConnection ( pgsocket  server_fd,
ClientSocket client_sock 
)

Definition at line 791 of file pqcomm.c.

792 {
793  /* accept connection and fill in the client (remote) address */
794  client_sock->raddr.salen = sizeof(client_sock->raddr.addr);
795  if ((client_sock->sock = accept(server_fd,
796  (struct sockaddr *) &client_sock->raddr.addr,
797  &client_sock->raddr.salen)) == PGINVALID_SOCKET)
798  {
799  ereport(LOG,
801  errmsg("could not accept new connection: %m")));
802 
803  /*
804  * If accept() fails then postmaster.c will still see the server
805  * socket as read-ready, and will immediately try again. To avoid
806  * uselessly sucking lots of CPU, delay a bit before trying again.
807  * (The most likely reason for failure is being out of kernel file
808  * table slots; we can do little except hope some will get freed up.)
809  */
810  pg_usleep(100000L); /* wait 0.1 sec */
811  return STATUS_ERROR;
812  }
813 
814  return STATUS_OK;
815 }
#define STATUS_OK
Definition: c.h:1156
#define STATUS_ERROR
Definition: c.h:1157
int errcode_for_socket_access(void)
Definition: elog.c:955
int errmsg(const char *fmt,...)
Definition: elog.c:1072
#define LOG
Definition: elog.h:31
#define ereport(elevel,...)
Definition: elog.h:149
#define PGINVALID_SOCKET
Definition: port.h:31
void pg_usleep(long microsec)
Definition: signal.c:53
SockAddr raddr
Definition: libpq-be.h:225
pgsocket sock
Definition: libpq-be.h:224
struct sockaddr_storage addr
Definition: pqcomm.h:32
socklen_t salen
Definition: pqcomm.h:33
#define accept(s, addr, addrlen)
Definition: win32_port.h:493

References accept, SockAddr::addr, ereport, errcode_for_socket_access(), errmsg(), LOG, pg_usleep(), PGINVALID_SOCKET, ClientSocket::raddr, SockAddr::salen, ClientSocket::sock, 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 
)

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

111 {
112  int loglevel = isServerStart ? FATAL : LOG;
113  struct stat buf;
114 
115  if (stat(ssl_key_file, &buf) != 0)
116  {
117  ereport(loglevel,
119  errmsg("could not access private key file \"%s\": %m",
120  ssl_key_file)));
121  return false;
122  }
123 
124  /* Key file must be a regular file */
125  if (!S_ISREG(buf.st_mode))
126  {
127  ereport(loglevel,
128  (errcode(ERRCODE_CONFIG_FILE_ERROR),
129  errmsg("private key file \"%s\" is not a regular file",
130  ssl_key_file)));
131  return false;
132  }
133 
134  /*
135  * Refuse to load key files owned by users other than us or root, and
136  * require no public access to the key file. If the file is owned by us,
137  * require mode 0600 or less. If owned by root, require 0640 or less to
138  * allow read access through either our gid or a supplementary gid that
139  * allows us to read system-wide certificates.
140  *
141  * Note that roughly similar checks are performed in
142  * src/interfaces/libpq/fe-secure-openssl.c so any changes here may need
143  * to be made there as well. The environment is different though; this
144  * code can assume that we're not running as root.
145  *
146  * Ideally we would do similar permissions checks on Windows, but it is
147  * not clear how that would work since Unix-style permissions may not be
148  * available.
149  */
150 #if !defined(WIN32) && !defined(__CYGWIN__)
151  if (buf.st_uid != geteuid() && buf.st_uid != 0)
152  {
153  ereport(loglevel,
154  (errcode(ERRCODE_CONFIG_FILE_ERROR),
155  errmsg("private key file \"%s\" must be owned by the database user or root",
156  ssl_key_file)));
157  return false;
158  }
159 
160  if ((buf.st_uid == geteuid() && buf.st_mode & (S_IRWXG | S_IRWXO)) ||
161  (buf.st_uid == 0 && buf.st_mode & (S_IWGRP | S_IXGRP | S_IRWXO)))
162  {
163  ereport(loglevel,
164  (errcode(ERRCODE_CONFIG_FILE_ERROR),
165  errmsg("private key file \"%s\" has group or world access",
166  ssl_key_file),
167  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.")));
168  return false;
169  }
170 #endif
171 
172  return true;
173 }
char * ssl_key_file
Definition: be-secure.c:37
int errcode_for_file_access(void)
Definition: elog.c:882
int errdetail(const char *fmt,...)
Definition: elog.c:1205
int errcode(int sqlerrcode)
Definition: elog.c:859
#define FATAL
Definition: elog.h:41
static char * buf
Definition: pg_test_fsync.c:73
#define S_IXGRP
Definition: win32_port.h:307
#define stat
Definition: win32_port.h:284
#define S_IRWXG
Definition: win32_port.h:310
#define S_IRWXO
Definition: win32_port.h:322
#define S_ISREG(m)
Definition: win32_port.h:328
#define S_IWGRP
Definition: win32_port.h:304

References buf, ereport, errcode(), errcode_for_file_access(), errdetail(), errmsg(), FATAL, 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  ListenSocket[],
int *  NumListenSockets,
int  MaxListen 
)

Definition at line 415 of file pqcomm.c.

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

References _, bind, closesocket, EADDRINUSE, elog, ereport, err(), errcode_for_socket_access(), errhint(), errmsg(), FATAL, 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_has_data()

bool pq_buffer_has_data ( void  )

Definition at line 1123 of file pqcomm.c.

1124 {
1125  return (PqRecvPointer < PqRecvLength);
1126 }
static int PqRecvLength
Definition: pqcomm.c:128
static int PqRecvPointer
Definition: pqcomm.c:127

References PqRecvLength, and PqRecvPointer.

Referenced by ProcessStartupPacket().

◆ pq_check_connection()

bool pq_check_connection ( void  )

Definition at line 2019 of file pqcomm.c.

2020 {
2021  WaitEvent events[FeBeWaitSetNEvents];
2022  int rc;
2023 
2024  /*
2025  * It's OK to modify the socket event filter without restoring, because
2026  * all FeBeWaitSet socket wait sites do the same.
2027  */
2029 
2030 retry:
2031  rc = WaitEventSetWait(FeBeWaitSet, 0, events, lengthof(events), 0);
2032  for (int i = 0; i < rc; ++i)
2033  {
2034  if (events[i].events & WL_SOCKET_CLOSED)
2035  return false;
2036  if (events[i].events & WL_LATCH_SET)
2037  {
2038  /*
2039  * A latch event might be preventing other events from being
2040  * reported. Reset it and poll again. No need to restore it
2041  * because no code should expect latches to survive across
2042  * CHECK_FOR_INTERRUPTS().
2043  */
2045  goto retry;
2046  }
2047  }
2048 
2049  return true;
2050 }
#define lengthof(array)
Definition: c.h:775
struct Latch * MyLatch
Definition: globals.c:60
int i
Definition: isn.c:73
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:1049
int WaitEventSetWait(WaitEventSet *set, long timeout, WaitEvent *occurred_events, int nevents, uint32 wait_event_info)
Definition: latch.c:1424
void ResetLatch(Latch *latch)
Definition: latch.c:724
#define WL_SOCKET_CLOSED
Definition: latch.h:139
#define WL_LATCH_SET
Definition: latch.h:127
#define FeBeWaitSetNEvents
Definition: libpq.h:65
#define FeBeWaitSetSocketPos
Definition: libpq.h:63
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:163

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

Definition at line 1160 of file pqcomm.c.

1161 {
1163 
1164  PqCommReadingMsg = false;
1165 }
Assert(fmt[strlen(fmt) - 1] !='\n')
static bool PqCommReadingMsg
Definition: pqcomm.c:134

References Assert(), and PqCommReadingMsg.

Referenced by ProcessRepliesIfAny(), and ProcessStartupPacket().

◆ pq_getbyte()

int pq_getbyte ( void  )

Definition at line 961 of file pqcomm.c.

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

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

1002 {
1003  int r;
1004 
1006 
1008  {
1010  return 1;
1011  }
1012 
1013  /* Put the socket into non-blocking mode */
1014  socket_set_nonblocking(true);
1015 
1016  errno = 0;
1017 
1018  r = secure_read(MyProcPort, c, 1);
1019  if (r < 0)
1020  {
1021  /*
1022  * Ok if no data available without blocking or interrupted (though
1023  * EINTR really shouldn't happen with a non-blocking socket). Report
1024  * other errors.
1025  */
1026  if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
1027  r = 0;
1028  else
1029  {
1030  /*
1031  * Careful: an ereport() that tries to write to the client would
1032  * cause recursion to here, leading to stack overflow and core
1033  * dump! This message must go *only* to the postmaster log.
1034  *
1035  * If errno is zero, assume it's EOF and let the caller complain.
1036  */
1037  if (errno != 0)
1040  errmsg("could not receive data from client: %m")));
1041  r = EOF;
1042  }
1043  }
1044  else if (r == 0)
1045  {
1046  /* EOF detected */
1047  r = EOF;
1048  }
1049 
1050  return r;
1051 }
ssize_t secure_read(Port *port, void *ptr, size_t len)
Definition: be-secure.c:142
#define COMMERROR
Definition: elog.h:33
struct Port * MyProcPort
Definition: globals.c:49
static void socket_set_nonblocking(bool nonblocking)
Definition: pqcomm.c:878
char * c
#define EINTR
Definition: win32_port.h:374
#define EWOULDBLOCK
Definition: win32_port.h:380
#define EAGAIN
Definition: win32_port.h:372

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

Referenced by ProcessRepliesIfAny().

◆ pq_getbytes()

int pq_getbytes ( char *  s,
size_t  len 
)

Definition at line 1060 of file pqcomm.c.

1061 {
1062  size_t amount;
1063 
1065 
1066  while (len > 0)
1067  {
1068  while (PqRecvPointer >= PqRecvLength)
1069  {
1070  if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1071  return EOF; /* Failed to recv data */
1072  }
1073  amount = PqRecvLength - PqRecvPointer;
1074  if (amount > len)
1075  amount = len;
1076  memcpy(s, PqRecvBuffer + PqRecvPointer, amount);
1077  PqRecvPointer += amount;
1078  s += amount;
1079  len -= amount;
1080  }
1081  return 0;
1082 }
const void size_t len

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

Referenced by pq_getmessage(), and ProcessStartupPacket().

◆ pq_getmessage()

int pq_getmessage ( StringInfo  s,
int  maxlen 
)

Definition at line 1198 of file pqcomm.c.

1199 {
1200  int32 len;
1201 
1203 
1204  resetStringInfo(s);
1205 
1206  /* Read message length word */
1207  if (pq_getbytes((char *) &len, 4) == EOF)
1208  {
1210  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1211  errmsg("unexpected EOF within message length word")));
1212  return EOF;
1213  }
1214 
1215  len = pg_ntoh32(len);
1216 
1217  if (len < 4 || len > maxlen)
1218  {
1220  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1221  errmsg("invalid message length")));
1222  return EOF;
1223  }
1224 
1225  len -= 4; /* discount length itself */
1226 
1227  if (len > 0)
1228  {
1229  /*
1230  * Allocate space for message. If we run out of room (ridiculously
1231  * large message), we will elog(ERROR), but we want to discard the
1232  * message body so as not to lose communication sync.
1233  */
1234  PG_TRY();
1235  {
1236  enlargeStringInfo(s, len);
1237  }
1238  PG_CATCH();
1239  {
1240  if (pq_discardbytes(len) == EOF)
1242  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1243  errmsg("incomplete message from client")));
1244 
1245  /* we discarded the rest of the message so we're back in sync. */
1246  PqCommReadingMsg = false;
1247  PG_RE_THROW();
1248  }
1249  PG_END_TRY();
1250 
1251  /* And grab the message */
1252  if (pq_getbytes(s->data, len) == EOF)
1253  {
1255  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1256  errmsg("incomplete message from client")));
1257  return EOF;
1258  }
1259  s->len = len;
1260  /* Place a trailing null per StringInfo convention */
1261  s->data[len] = '\0';
1262  }
1263 
1264  /* finished reading the message. */
1265  PqCommReadingMsg = false;
1266 
1267  return 0;
1268 }
signed int int32
Definition: c.h:481
#define PG_RE_THROW()
Definition: elog.h:411
#define PG_TRY(...)
Definition: elog.h:370
#define PG_END_TRY(...)
Definition: elog.h:395
#define PG_CATCH(...)
Definition: elog.h:380
#define pg_ntoh32(x)
Definition: pg_bswap.h:125
static int pq_discardbytes(size_t len)
Definition: pqcomm.c:1094
int pq_getbytes(char *s, size_t len)
Definition: pqcomm.c:1060
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:78
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:289

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

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

◆ pq_init()

Port* pq_init ( ClientSocket client_sock)

Definition at line 171 of file pqcomm.c.

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

References SockAddr::addr, AddWaitEventToSet(), Assert(), CreateWaitEventSet(), elog, ereport, errmsg(), FATAL, FeBeWaitSet, FeBeWaitSetLatchPos, FeBeWaitSetNEvents, FeBeWaitSetSocketPos, MemoryContextAlloc(), MyLatch, on_proc_exit(), palloc0(), 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, ClientSocket::raddr, SockAddr::salen, ClientSocket::sock, 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 1176 of file pqcomm.c.

1177 {
1178  return PqCommReadingMsg;
1179 }

References PqCommReadingMsg.

Referenced by PostgresMain().

◆ pq_peekbyte()

int pq_peekbyte ( void  )

Definition at line 980 of file pqcomm.c.

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

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

◆ pq_putmessage_v2()

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

Definition at line 1524 of file pqcomm.c.

1525 {
1526  Assert(msgtype != 0);
1527 
1528  if (PqCommBusy)
1529  return 0;
1530  PqCommBusy = true;
1531  if (internal_putbytes(&msgtype, 1))
1532  goto fail;
1533 
1534  if (internal_putbytes(s, len))
1535  goto fail;
1536  PqCommBusy = false;
1537  return 0;
1538 
1539 fail:
1540  PqCommBusy = false;
1541  return EOF;
1542 }
static int internal_putbytes(const char *s, size_t len)
Definition: pqcomm.c:1272

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

Referenced by send_message_to_frontend().

◆ pq_startmsgread()

void pq_startmsgread ( void  )

Definition at line 1136 of file pqcomm.c.

1137 {
1138  /*
1139  * There shouldn't be a read active already, but let's check just to be
1140  * sure.
1141  */
1142  if (PqCommReadingMsg)
1143  ereport(FATAL,
1144  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1145  errmsg("terminating connection because protocol synchronization was lost")));
1146 
1147  PqCommReadingMsg = true;
1148 }

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

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

◆ RemoveSocketFiles()

void RemoveSocketFiles ( void  )

Definition at line 845 of file pqcomm.c.

846 {
847  ListCell *l;
848 
849  /* Loop through all created sockets... */
850  foreach(l, sock_paths)
851  {
852  char *sock_path = (char *) lfirst(l);
853 
854  /* Ignore any error. */
855  (void) unlink(sock_path);
856  }
857  /* Since we're about to exit, no need to reclaim storage */
858  sock_paths = NIL;
859 }
#define lfirst(lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:68
static List * sock_paths
Definition: pqcomm.c:109

References lfirst, NIL, 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 
)

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

41 {
42  int loglevel = is_server_start ? ERROR : LOG;
43  char *command;
44  FILE *fh;
45  int pclose_rc;
46  size_t len = 0;
47 
48  Assert(prompt);
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  {
57  ereport(loglevel,
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  {
69  ereport(loglevel,
71  errmsg("could not read from command \"%s\": %m",
72  command)));
73  goto error;
74  }
75  }
76 
77  pclose_rc = ClosePipeStream(fh);
78  if (pclose_rc == -1)
79  {
81  ereport(loglevel,
83  errmsg("could not close pipe to external command: %m")));
84  goto error;
85  }
86  else if (pclose_rc != 0)
87  {
89  ereport(loglevel,
91  errmsg("command \"%s\" failed",
92  command),
93  errdetail_internal("%s", wait_result_to_str(pclose_rc))));
94  goto error;
95  }
96 
97  /* strip trailing newline and carriage return */
99 
100 error:
101  pfree(command);
102  return len;
103 }
char * ssl_passphrase_command
Definition: be-secure.c:42
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1232
#define ERROR
Definition: elog.h:39
int ClosePipeStream(FILE *file)
Definition: fd.c:2991
FILE * OpenPipeStream(const char *command, const char *mode)
Definition: fd.c:2686
void pfree(void *pointer)
Definition: mcxt.c:1508
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 pg_noinline void Size size
Definition: slab.c:607
static void error(void)
Definition: sql-dyntest.c:147
int pg_strip_crlf(char *str)
Definition: string.c:155
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(), len, LOG, OpenPipeStream(), pfree(), pg_strip_crlf(), replace_percent_placeholders(), size, ssl_passphrase_command, and wait_result_to_str().

Referenced by ssl_external_passwd_cb().

◆ secure_close()

void secure_close ( Port port)

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

131 {
132 #ifdef USE_SSL
133  if (port->ssl_in_use)
135 #endif
136 }
void be_tls_close(Port *port)

References be_tls_close(), and port.

Referenced by socket_close().

◆ secure_destroy()

void secure_destroy ( void  )

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

87 {
88 #ifdef USE_SSL
90 #endif
91 }
void be_tls_destroy(void)

References be_tls_destroy().

Referenced by process_pm_reload_request().

◆ secure_initialize()

int secure_initialize ( bool  isServerStart)

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

74 {
75 #ifdef USE_SSL
76  return be_tls_init(isServerStart);
77 #else
78  return 0;
79 #endif
80 }
int be_tls_init(bool isServerStart)

References be_tls_init().

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

◆ secure_loaded_verify_locations()

bool secure_loaded_verify_locations ( void  )

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

98 {
99 #ifdef USE_SSL
100  return ssl_loaded_verify_locations;
101 #else
102  return false;
103 #endif
104 }

Referenced by ClientAuthentication().

◆ secure_open_server()

int secure_open_server ( Port port)

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

111 {
112  int r = 0;
113 
114 #ifdef USE_SSL
116 
117  ereport(DEBUG2,
118  (errmsg_internal("SSL connection from DN:\"%s\" CN:\"%s\"",
119  port->peer_dn ? port->peer_dn : "(anonymous)",
120  port->peer_cn ? port->peer_cn : "(anonymous)")));
121 #endif
122 
123  return r;
124 }
int be_tls_open_server(Port *port)
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1159
#define DEBUG2
Definition: elog.h:29

References be_tls_open_server(), DEBUG2, ereport, errmsg_internal(), and port.

Referenced by ProcessStartupPacket().

◆ secure_raw_read()

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

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

232 {
233  ssize_t n;
234 
235  /*
236  * Try to read from the socket without blocking. If it succeeds we're
237  * done, otherwise we'll wait for the socket using the latch mechanism.
238  */
239 #ifdef WIN32
240  pgwin32_noblock = true;
241 #endif
242  n = recv(port->sock, ptr, len, 0);
243 #ifdef WIN32
244  pgwin32_noblock = false;
245 #endif
246 
247  return n;
248 }
int pgwin32_noblock
Definition: socket.c:28
#define recv(s, buf, len, flags)
Definition: win32_port.h:496

References len, pgwin32_noblock, port, and recv.

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

◆ secure_raw_write()

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

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

328 {
329  ssize_t n;
330 
331 #ifdef WIN32
332  pgwin32_noblock = true;
333 #endif
334  n = send(port->sock, ptr, len, 0);
335 #ifdef WIN32
336  pgwin32_noblock = false;
337 #endif
338 
339  return n;
340 }
#define send(s, buf, len, flags)
Definition: win32_port.h:497

References len, pgwin32_noblock, port, and send.

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

◆ secure_read()

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

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

143 {
144  ssize_t n;
145  int waitfor;
146 
147  /* Deal with any already-pending interrupt condition. */
149 
150 retry:
151 #ifdef USE_SSL
152  waitfor = 0;
153  if (port->ssl_in_use)
154  {
155  n = be_tls_read(port, ptr, len, &waitfor);
156  }
157  else
158 #endif
159 #ifdef ENABLE_GSS
160  if (port->gss && port->gss->enc)
161  {
162  n = be_gssapi_read(port, ptr, len);
163  waitfor = WL_SOCKET_READABLE;
164  }
165  else
166 #endif
167  {
168  n = secure_raw_read(port, ptr, len);
169  waitfor = WL_SOCKET_READABLE;
170  }
171 
172  /* In blocking mode, wait until the socket is ready */
173  if (n < 0 && !port->noblock && (errno == EWOULDBLOCK || errno == EAGAIN))
174  {
175  WaitEvent event;
176 
177  Assert(waitfor);
178 
180 
181  WaitEventSetWait(FeBeWaitSet, -1 /* no timeout */ , &event, 1,
182  WAIT_EVENT_CLIENT_READ);
183 
184  /*
185  * If the postmaster has died, it's not safe to continue running,
186  * because it is the postmaster's job to kill us if some other backend
187  * exits uncleanly. Moreover, we won't run very well in this state;
188  * helper processes like walwriter and the bgwriter will exit, so
189  * performance may be poor. Finally, if we don't exit, pg_ctl will be
190  * unable to restart the postmaster without manual intervention, so no
191  * new connections can be accepted. Exiting clears the deck for a
192  * postmaster restart.
193  *
194  * (Note that we only make this check when we would otherwise sleep on
195  * our latch. We might still continue running for a while if the
196  * postmaster is killed in mid-query, or even through multiple queries
197  * if we never have to wait for read. We don't want to burn too many
198  * cycles checking for this very rare condition, and this should cause
199  * us to exit quickly in most cases.)
200  */
201  if (event.events & WL_POSTMASTER_DEATH)
202  ereport(FATAL,
203  (errcode(ERRCODE_ADMIN_SHUTDOWN),
204  errmsg("terminating connection due to unexpected postmaster exit")));
205 
206  /* Handle interrupt. */
207  if (event.events & WL_LATCH_SET)
208  {
211 
212  /*
213  * We'll retry the read. Most likely it will return immediately
214  * because there's still no data available, and we'll wait for the
215  * socket to become ready again.
216  */
217  }
218  goto retry;
219  }
220 
221  /*
222  * Process interrupts that happened during a successful (or non-blocking,
223  * or hard-failed) read.
224  */
226 
227  return n;
228 }
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:231
#define WL_SOCKET_READABLE
Definition: latch.h:128
void ProcessClientReadInterrupt(bool blocked)
Definition: postgres.c:509
uint32 events
Definition: latch.h:155

References Assert(), be_gssapi_read(), be_tls_read(), EAGAIN, ereport, errcode(), errmsg(), WaitEvent::events, EWOULDBLOCK, FATAL, 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,
void *  ptr,
size_t  len 
)

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

256 {
257  ssize_t n;
258  int waitfor;
259 
260  /* Deal with any already-pending interrupt condition. */
262 
263 retry:
264  waitfor = 0;
265 #ifdef USE_SSL
266  if (port->ssl_in_use)
267  {
268  n = be_tls_write(port, ptr, len, &waitfor);
269  }
270  else
271 #endif
272 #ifdef ENABLE_GSS
273  if (port->gss && port->gss->enc)
274  {
275  n = be_gssapi_write(port, ptr, len);
276  waitfor = WL_SOCKET_WRITEABLE;
277  }
278  else
279 #endif
280  {
281  n = secure_raw_write(port, ptr, len);
282  waitfor = WL_SOCKET_WRITEABLE;
283  }
284 
285  if (n < 0 && !port->noblock && (errno == EWOULDBLOCK || errno == EAGAIN))
286  {
287  WaitEvent event;
288 
289  Assert(waitfor);
290 
292 
293  WaitEventSetWait(FeBeWaitSet, -1 /* no timeout */ , &event, 1,
294  WAIT_EVENT_CLIENT_WRITE);
295 
296  /* See comments in secure_read. */
297  if (event.events & WL_POSTMASTER_DEATH)
298  ereport(FATAL,
299  (errcode(ERRCODE_ADMIN_SHUTDOWN),
300  errmsg("terminating connection due to unexpected postmaster exit")));
301 
302  /* Handle interrupt. */
303  if (event.events & WL_LATCH_SET)
304  {
307 
308  /*
309  * We'll retry the write. Most likely it will return immediately
310  * because there's still no buffer space available, and we'll wait
311  * for the socket to become ready again.
312  */
313  }
314  goto retry;
315  }
316 
317  /*
318  * Process interrupts that happened during a successful (or non-blocking,
319  * or hard-failed) write.
320  */
322 
323  return n;
324 }
ssize_t be_gssapi_write(Port *port, void *ptr, size_t len)
ssize_t be_tls_write(Port *port, void *ptr, size_t len, int *waitfor)
ssize_t secure_raw_write(Port *port, const void *ptr, size_t len)
Definition: be-secure.c:327
void ProcessClientWriteInterrupt(bool blocked)
Definition: postgres.c:555

References Assert(), be_gssapi_write(), be_tls_write(), EAGAIN, ereport, errcode(), errmsg(), WaitEvent::events, EWOULDBLOCK, FATAL, 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().

◆ TouchSocketFiles()

void TouchSocketFiles ( void  )

Definition at line 827 of file pqcomm.c.

828 {
829  ListCell *l;
830 
831  /* Loop through all created sockets... */
832  foreach(l, sock_paths)
833  {
834  char *sock_path = (char *) lfirst(l);
835 
836  /* Ignore errors; there's no point in complaining */
837  (void) utime(sock_path, NULL);
838  }
839 }

References lfirst, and sock_paths.

Referenced by ServerLoop().

Variable Documentation

◆ FeBeWaitSet

◆ PqCommMethods

const PGDLLIMPORT PQcommMethods* PqCommMethods
extern

Definition at line 161 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 38 of file be-secure.c.

Referenced by be_tls_init().

◆ ssl_cert_file

PGDLLIMPORT char* ssl_cert_file
extern

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

Referenced by be_tls_init().

◆ ssl_crl_dir

PGDLLIMPORT char* ssl_crl_dir
extern

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

Referenced by be_tls_init().

◆ ssl_crl_file

PGDLLIMPORT char* ssl_crl_file
extern

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

Referenced by be_tls_init().

◆ ssl_dh_params_file

PGDLLIMPORT char* ssl_dh_params_file
extern

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

Referenced by initialize_dh().

◆ ssl_key_file

PGDLLIMPORT char* ssl_key_file
extern

Definition at line 37 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 35 of file be-secure.c.

◆ ssl_max_protocol_version

PGDLLIMPORT int ssl_max_protocol_version
extern

Definition at line 59 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 58 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 42 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 43 of file be-secure.c.

Referenced by default_openssl_tls_init().

◆ SSLCipherSuites

PGDLLIMPORT char* SSLCipherSuites
extern

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

Referenced by be_tls_init().

◆ SSLECDHCurve

PGDLLIMPORT char* SSLECDHCurve
extern

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

Referenced by initialize_ecdh().

◆ SSLPreferServerCiphers

PGDLLIMPORT bool SSLPreferServerCiphers
extern

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

Referenced by be_tls_init().