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

795 {
796  /* accept connection and fill in the client (remote) address */
797  client_sock->raddr.salen = sizeof(client_sock->raddr.addr);
798  if ((client_sock->sock = accept(server_fd,
799  (struct sockaddr *) &client_sock->raddr.addr,
800  &client_sock->raddr.salen)) == PGINVALID_SOCKET)
801  {
802  ereport(LOG,
804  errmsg("could not accept new connection: %m")));
805 
806  /*
807  * If accept() fails then postmaster.c will still see the server
808  * socket as read-ready, and will immediately try again. To avoid
809  * uselessly sucking lots of CPU, delay a bit before trying again.
810  * (The most likely reason for failure is being out of kernel file
811  * table slots; we can do little except hope some will get freed up.)
812  */
813  pg_usleep(100000L); /* wait 0.1 sec */
814  return STATUS_ERROR;
815  }
816 
817  return STATUS_OK;
818 }
#define STATUS_OK
Definition: c.h:1169
#define STATUS_ERROR
Definition: c.h:1170
int errcode_for_socket_access(void)
Definition: elog.c:951
int errmsg(const char *fmt,...)
Definition: elog.c:1068
#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:239
pgsocket sock
Definition: libpq-be.h:238
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 114 of file be-secure-common.c.

115 {
116  int loglevel = isServerStart ? FATAL : LOG;
117  struct stat buf;
118 
119  if (stat(ssl_key_file, &buf) != 0)
120  {
121  ereport(loglevel,
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  {
131  ereport(loglevel,
132  (errcode(ERRCODE_CONFIG_FILE_ERROR),
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  {
157  ereport(loglevel,
158  (errcode(ERRCODE_CONFIG_FILE_ERROR),
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  {
167  ereport(loglevel,
168  (errcode(ERRCODE_CONFIG_FILE_ERROR),
169  errmsg("private key file \"%s\" has group or world access",
170  ssl_key_file),
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:37
int errcode_for_file_access(void)
Definition: elog.c:878
int errdetail(const char *fmt,...)
Definition: elog.c:1201
int errcode(int sqlerrcode)
Definition: elog.c:855
#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  ListenSockets[],
int *  NumListenSockets,
int  MaxListen 
)

Definition at line 418 of file pqcomm.c.

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

ssize_t pq_buffer_remaining_data ( void  )

Definition at line 1127 of file pqcomm.c.

1128 {
1130  return (PqRecvLength - PqRecvPointer);
1131 }
#define Assert(condition)
Definition: c.h:858
static int PqRecvLength
Definition: pqcomm.c:129
static int PqRecvPointer
Definition: pqcomm.c:128

References Assert, PqRecvLength, and PqRecvPointer.

Referenced by ProcessStartupPacket(), and secure_open_server().

◆ pq_check_connection()

bool pq_check_connection ( void  )

Definition at line 2054 of file pqcomm.c.

2055 {
2056  WaitEvent events[FeBeWaitSetNEvents];
2057  int rc;
2058 
2059  /*
2060  * It's OK to modify the socket event filter without restoring, because
2061  * all FeBeWaitSet socket wait sites do the same.
2062  */
2064 
2065 retry:
2066  rc = WaitEventSetWait(FeBeWaitSet, 0, events, lengthof(events), 0);
2067  for (int i = 0; i < rc; ++i)
2068  {
2069  if (events[i].events & WL_SOCKET_CLOSED)
2070  return false;
2071  if (events[i].events & WL_LATCH_SET)
2072  {
2073  /*
2074  * A latch event might be preventing other events from being
2075  * reported. Reset it and poll again. No need to restore it
2076  * because no code should expect latches to survive across
2077  * CHECK_FOR_INTERRUPTS().
2078  */
2080  goto retry;
2081  }
2082  }
2083 
2084  return true;
2085 }
#define lengthof(array)
Definition: c.h:788
struct Latch * MyLatch
Definition: globals.c:61
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:166

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 1165 of file pqcomm.c.

1166 {
1168 
1169  PqCommReadingMsg = false;
1170 }
static bool PqCommReadingMsg
Definition: pqcomm.c:135

References Assert, and PqCommReadingMsg.

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

◆ pq_getbyte()

int pq_getbyte ( void  )

Definition at line 964 of file pqcomm.c.

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

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 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 */
1017  socket_set_nonblocking(true);
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:175
#define COMMERROR
Definition: elog.h:33
struct Port * MyProcPort
Definition: globals.c:50
static void socket_set_nonblocking(bool nonblocking)
Definition: pqcomm.c:881
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 1063 of file pqcomm.c.

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

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

Definition at line 1203 of file pqcomm.c.

1204 {
1205  int32 len;
1206 
1208 
1209  resetStringInfo(s);
1210 
1211  /* Read message length word */
1212  if (pq_getbytes((char *) &len, 4) == EOF)
1213  {
1215  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1216  errmsg("unexpected EOF within message length word")));
1217  return EOF;
1218  }
1219 
1220  len = pg_ntoh32(len);
1221 
1222  if (len < 4 || len > maxlen)
1223  {
1225  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1226  errmsg("invalid message length")));
1227  return EOF;
1228  }
1229 
1230  len -= 4; /* discount length itself */
1231 
1232  if (len > 0)
1233  {
1234  /*
1235  * Allocate space for message. If we run out of room (ridiculously
1236  * large message), we will elog(ERROR), but we want to discard the
1237  * message body so as not to lose communication sync.
1238  */
1239  PG_TRY();
1240  {
1241  enlargeStringInfo(s, len);
1242  }
1243  PG_CATCH();
1244  {
1245  if (pq_discardbytes(len) == EOF)
1247  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1248  errmsg("incomplete message from client")));
1249 
1250  /* we discarded the rest of the message so we're back in sync. */
1251  PqCommReadingMsg = false;
1252  PG_RE_THROW();
1253  }
1254  PG_END_TRY();
1255 
1256  /* And grab the message */
1257  if (pq_getbytes(s->data, len) == EOF)
1258  {
1260  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1261  errmsg("incomplete message from client")));
1262  return EOF;
1263  }
1264  s->len = len;
1265  /* Place a trailing null per StringInfo convention */
1266  s->data[len] = '\0';
1267  }
1268 
1269  /* finished reading the message. */
1270  PqCommReadingMsg = false;
1271 
1272  return 0;
1273 }
signed int int32
Definition: c.h:494
#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:1097
int pq_getbytes(char *s, size_t len)
Definition: pqcomm.c:1063
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 174 of file pqcomm.c.

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

1182 {
1183  return PqCommReadingMsg;
1184 }

References PqCommReadingMsg.

Referenced by PostgresMain().

◆ pq_peekbyte()

int pq_peekbyte ( void  )

Definition at line 983 of file pqcomm.c.

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

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

Referenced by ProcessSSLStartup().

◆ pq_putmessage_v2()

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

Definition at line 1559 of file pqcomm.c.

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

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

Referenced by send_message_to_frontend().

◆ pq_startmsgread()

void pq_startmsgread ( void  )

Definition at line 1141 of file pqcomm.c.

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

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

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

◆ RemoveSocketFiles()

void RemoveSocketFiles ( void  )

Definition at line 848 of file pqcomm.c.

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

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  {
88  char *reason;
89 
91  reason = wait_result_to_str(pclose_rc);
92  ereport(loglevel,
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 */
102  len = pg_strip_crlf(buf);
103 
104 error:
105  pfree(command);
106  return len;
107 }
char * ssl_passphrase_command
Definition: be-secure.c:42
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1228
#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:1521
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 163 of file be-secure.c.

164 {
165 #ifdef USE_SSL
166  if (port->ssl_in_use)
168 #endif
169 }
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 #ifdef USE_SSL
113  int r = 0;
114  ssize_t len;
115 
116  /* push unencrypted buffered data back through SSL setup */
118  if (len > 0)
119  {
120  char *buf = palloc(len);
121 
122  pq_startmsgread();
123  if (pq_getbytes(buf, len) == EOF)
124  return STATUS_ERROR; /* shouldn't be possible */
125  pq_endmsgread();
126  port->raw_buf = buf;
127  port->raw_buf_remaining = len;
128  port->raw_buf_consumed = 0;
129  }
131 
133 
134  if (port->raw_buf_remaining > 0)
135  {
136  /*
137  * This shouldn't be possible -- it would mean the client sent
138  * encrypted data before we established a session key...
139  */
140  elog(LOG, "buffered unencrypted data remains after negotiating SSL connection");
141  return STATUS_ERROR;
142  }
143  if (port->raw_buf != NULL)
144  {
145  pfree(port->raw_buf);
146  port->raw_buf = NULL;
147  }
148 
149  ereport(DEBUG2,
150  (errmsg_internal("SSL connection from DN:\"%s\" CN:\"%s\"",
151  port->peer_dn ? port->peer_dn : "(anonymous)",
152  port->peer_cn ? port->peer_cn : "(anonymous)")));
153  return r;
154 #else
155  return 0;
156 #endif
157 }
int be_tls_open_server(Port *port)
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1155
#define DEBUG2
Definition: elog.h:29
void * palloc(Size size)
Definition: mcxt.c:1317
ssize_t pq_buffer_remaining_data(void)
Definition: pqcomm.c:1127
void pq_endmsgread(void)
Definition: pqcomm.c:1165
void pq_startmsgread(void)
Definition: pqcomm.c:1141

References Assert, be_tls_open_server(), buf, DEBUG2, elog, ereport, errmsg_internal(), 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 
)

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

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

References Assert, 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 373 of file be-secure.c.

374 {
375  ssize_t n;
376 
377 #ifdef WIN32
378  pgwin32_noblock = true;
379 #endif
380  n = send(port->sock, ptr, len, 0);
381 #ifdef WIN32
382  pgwin32_noblock = false;
383 #endif
384 
385  return n;
386 }
#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 175 of file be-secure.c.

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

302 {
303  ssize_t n;
304  int waitfor;
305 
306  /* Deal with any already-pending interrupt condition. */
308 
309 retry:
310  waitfor = 0;
311 #ifdef USE_SSL
312  if (port->ssl_in_use)
313  {
314  n = be_tls_write(port, ptr, len, &waitfor);
315  }
316  else
317 #endif
318 #ifdef ENABLE_GSS
319  if (port->gss && port->gss->enc)
320  {
321  n = be_gssapi_write(port, ptr, len);
322  waitfor = WL_SOCKET_WRITEABLE;
323  }
324  else
325 #endif
326  {
327  n = secure_raw_write(port, ptr, len);
328  waitfor = WL_SOCKET_WRITEABLE;
329  }
330 
331  if (n < 0 && !port->noblock && (errno == EWOULDBLOCK || errno == EAGAIN))
332  {
333  WaitEvent event;
334 
335  Assert(waitfor);
336 
338 
339  WaitEventSetWait(FeBeWaitSet, -1 /* no timeout */ , &event, 1,
340  WAIT_EVENT_CLIENT_WRITE);
341 
342  /* See comments in secure_read. */
343  if (event.events & WL_POSTMASTER_DEATH)
344  ereport(FATAL,
345  (errcode(ERRCODE_ADMIN_SHUTDOWN),
346  errmsg("terminating connection due to unexpected postmaster exit")));
347 
348  /* Handle interrupt. */
349  if (event.events & WL_LATCH_SET)
350  {
353 
354  /*
355  * We'll retry the write. Most likely it will return immediately
356  * because there's still no buffer space available, and we'll wait
357  * for the socket to become ready again.
358  */
359  }
360  goto retry;
361  }
362 
363  /*
364  * Process interrupts that happened during a successful (or non-blocking,
365  * or hard-failed) write.
366  */
368 
369  return n;
370 }
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:373
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_buffer(), and ProcessStartupPacket().

◆ TouchSocketFiles()

void TouchSocketFiles ( void  )

Definition at line 830 of file pqcomm.c.

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

References lfirst, and sock_paths.

Referenced by ServerLoop().

Variable Documentation

◆ FeBeWaitSet

◆ PqCommMethods

const PGDLLIMPORT PQcommMethods* PqCommMethods
extern

Definition at line 164 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().