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
 

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 StreamServerPort (int family, const char *hostName, unsigned short portNumber, const char *unixSocketDir, pgsocket ListenSocket[], int MaxListen)
 
int StreamConnection (pgsocket server_fd, Port *port)
 
void StreamClose (pgsocket sock)
 
void TouchSocketFiles (void)
 
void RemoveSocketFiles (void)
 
void pq_init (void)
 
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)
 
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
 
WaitEventSetFeBeWaitSet
 
char * ssl_library
 
char * ssl_cert_file
 
char * ssl_key_file
 
char * ssl_ca_file
 
char * ssl_crl_file
 
char * ssl_crl_dir
 
char * ssl_dh_params_file
 
PGDLLIMPORT char * ssl_passphrase_command
 
PGDLLIMPORT bool ssl_passphrase_command_supports_reload
 
char * SSLCipherSuites
 
char * SSLECDHCurve
 
bool SSLPreferServerCiphers
 
int ssl_min_protocol_version
 
int ssl_max_protocol_version
 

Macro Definition Documentation

◆ FeBeWaitSetLatchPos

#define FeBeWaitSetLatchPos   1

Definition at line 64 of file libpq.h.

Referenced by pq_init(), SwitchBackToLocalLatch(), and SwitchToSharedLatch().

◆ FeBeWaitSetSocketPos

#define FeBeWaitSetSocketPos   0

Definition at line 63 of file libpq.h.

Referenced by pq_init(), secure_read(), secure_write(), and WalSndWait().

◆ pq_comm_reset

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

Definition at line 45 of file libpq.h.

Referenced by PostgresMain().

◆ pq_flush

◆ pq_flush_if_writable

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

Definition at line 47 of file libpq.h.

Referenced by WalSndKeepaliveIfNecessary(), WalSndLoop(), WalSndWaitForWal(), and WalSndWriteData().

◆ pq_is_send_pending

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

Definition at line 48 of file libpq.h.

Referenced by WalSndDone(), WalSndLoop(), WalSndWaitForWal(), and WalSndWriteData().

◆ PQ_LARGE_MESSAGE_LIMIT

#define PQ_LARGE_MESSAGE_LIMIT   (MaxAllocSize - 1)

Definition at line 31 of file libpq.h.

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

◆ pq_putmessage

◆ pq_putmessage_noblock

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

Definition at line 51 of file libpq.h.

Referenced by ProcessRepliesIfAny(), WalSndKeepalive(), WalSndWriteData(), and XLogSendPhysical().

◆ PQ_SMALL_MESSAGE_LIMIT

#define PQ_SMALL_MESSAGE_LIMIT   10000

Definition at line 30 of file libpq.h.

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

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 125 of file libpq.h.

Function Documentation

◆ check_ssl_key_file_permissions()

bool check_ssl_key_file_permissions ( const char *  ssl_key_file,
bool  isServerStart 
)

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

References ereport, errcode(), errcode_for_file_access(), errdetail(), errmsg(), FATAL, LOG, S_IRWXG, S_IRWXO, S_ISREG, S_IWGRP, S_IXGRP, stat::st_mode, stat::st_uid, and stat.

Referenced by be_tls_init().

133 {
134  int loglevel = isServerStart ? FATAL : LOG;
135  struct stat buf;
136 
137  if (stat(ssl_key_file, &buf) != 0)
138  {
139  ereport(loglevel,
141  errmsg("could not access private key file \"%s\": %m",
142  ssl_key_file)));
143  return false;
144  }
145 
146  if (!S_ISREG(buf.st_mode))
147  {
148  ereport(loglevel,
149  (errcode(ERRCODE_CONFIG_FILE_ERROR),
150  errmsg("private key file \"%s\" is not a regular file",
151  ssl_key_file)));
152  return false;
153  }
154 
155  /*
156  * Refuse to load key files owned by users other than us or root.
157  *
158  * XXX surely we can check this on Windows somehow, too.
159  */
160 #if !defined(WIN32) && !defined(__CYGWIN__)
161  if (buf.st_uid != geteuid() && buf.st_uid != 0)
162  {
163  ereport(loglevel,
164  (errcode(ERRCODE_CONFIG_FILE_ERROR),
165  errmsg("private key file \"%s\" must be owned by the database user or root",
166  ssl_key_file)));
167  return false;
168  }
169 #endif
170 
171  /*
172  * Require no public access to key file. If the file is owned by us,
173  * require mode 0600 or less. If owned by root, require 0640 or less to
174  * allow read access through our gid, or a supplementary gid that allows
175  * to read system-wide certificates.
176  *
177  * XXX temporarily suppress check when on Windows, because there may not
178  * be proper support for Unix-y file permissions. Need to think of a
179  * reasonable check to apply on Windows. (See also the data directory
180  * permission check in postmaster.c)
181  */
182 #if !defined(WIN32) && !defined(__CYGWIN__)
183  if ((buf.st_uid == geteuid() && buf.st_mode & (S_IRWXG | S_IRWXO)) ||
184  (buf.st_uid == 0 && buf.st_mode & (S_IWGRP | S_IXGRP | S_IRWXO)))
185  {
186  ereport(loglevel,
187  (errcode(ERRCODE_CONFIG_FILE_ERROR),
188  errmsg("private key file \"%s\" has group or world access",
189  ssl_key_file),
190  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.")));
191  return false;
192  }
193 #endif
194 
195  return true;
196 }
int errcode(int sqlerrcode)
Definition: elog.c:698
#define LOG
Definition: elog.h:26
#define FATAL
Definition: elog.h:49
static char * buf
Definition: pg_test_fsync.c:68
#define S_IRWXG
Definition: win32_port.h:301
int errdetail(const char *fmt,...)
Definition: elog.c:1042
int errcode_for_file_access(void)
Definition: elog.c:721
#define S_IWGRP
Definition: win32_port.h:295
#define S_ISREG(m)
Definition: win32_port.h:319
#define ereport(elevel,...)
Definition: elog.h:157
#define S_IXGRP
Definition: win32_port.h:298
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * ssl_key_file
Definition: be-secure.c:42
#define S_IRWXO
Definition: win32_port.h:313
#define stat
Definition: win32_port.h:275

◆ pq_check_connection()

bool pq_check_connection ( void  )

Definition at line 1933 of file pqcomm.c.

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

Referenced by ProcessInterrupts().

1934 {
1935 #if defined(POLLRDHUP)
1936  /*
1937  * POLLRDHUP is a Linux extension to poll(2) to detect sockets closed by
1938  * the other end. We don't have a portable way to do that without
1939  * actually trying to read or write data on other systems. We don't want
1940  * to read because that would be confused by pipelined queries and COPY
1941  * data. Perhaps in future we'll try to write a heartbeat message instead.
1942  */
1943  struct pollfd pollfd;
1944  int rc;
1945 
1946  pollfd.fd = MyProcPort->sock;
1947  pollfd.events = POLLOUT | POLLIN | POLLRDHUP;
1948  pollfd.revents = 0;
1949 
1950  rc = poll(&pollfd, 1, 0);
1951 
1952  if (rc < 0)
1953  {
1956  errmsg("could not poll socket: %m")));
1957  return false;
1958  }
1959  else if (rc == 1 && (pollfd.revents & (POLLHUP | POLLRDHUP)))
1960  return false;
1961 #endif
1962 
1963  return true;
1964 }
struct Port * MyProcPort
Definition: globals.c:46
pgsocket sock
Definition: libpq-be.h:127
#define COMMERROR
Definition: elog.h:30
int errcode_for_socket_access(void)
Definition: elog.c:792
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ pq_endmsgread()

void pq_endmsgread ( void  )

Definition at line 1176 of file pqcomm.c.

References Assert, and PqCommReadingMsg.

Referenced by ProcessRepliesIfAny(), and ProcessStartupPacket().

1177 {
1179 
1180  PqCommReadingMsg = false;
1181 }
#define Assert(condition)
Definition: c.h:804
static bool PqCommReadingMsg
Definition: pqcomm.c:137

◆ pq_getbyte()

int pq_getbyte ( void  )

Definition at line 994 of file pqcomm.c.

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

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

995 {
997 
998  while (PqRecvPointer >= PqRecvLength)
999  {
1000  if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1001  return EOF; /* Failed to recv data */
1002  }
1003  return (unsigned char) PqRecvBuffer[PqRecvPointer++];
1004 }
static char PqRecvBuffer[PQ_RECV_BUFFER_SIZE]
Definition: pqcomm.c:129
static int PqRecvLength
Definition: pqcomm.c:131
static int pq_recvbuf(void)
Definition: pqcomm.c:933
#define Assert(condition)
Definition: c.h:804
static int PqRecvPointer
Definition: pqcomm.c:130
static bool PqCommReadingMsg
Definition: pqcomm.c:137

◆ pq_getbyte_if_available()

int pq_getbyte_if_available ( unsigned char *  c)

Definition at line 1034 of file pqcomm.c.

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

Referenced by ProcessRepliesIfAny().

1035 {
1036  int r;
1037 
1039 
1041  {
1043  return 1;
1044  }
1045 
1046  /* Put the socket into non-blocking mode */
1047  socket_set_nonblocking(true);
1048 
1049  r = secure_read(MyProcPort, c, 1);
1050  if (r < 0)
1051  {
1052  /*
1053  * Ok if no data available without blocking or interrupted (though
1054  * EINTR really shouldn't happen with a non-blocking socket). Report
1055  * other errors.
1056  */
1057  if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
1058  r = 0;
1059  else
1060  {
1061  /*
1062  * Careful: an ereport() that tries to write to the client would
1063  * cause recursion to here, leading to stack overflow and core
1064  * dump! This message must go *only* to the postmaster log.
1065  */
1068  errmsg("could not receive data from client: %m")));
1069  r = EOF;
1070  }
1071  }
1072  else if (r == 0)
1073  {
1074  /* EOF detected */
1075  r = EOF;
1076  }
1077 
1078  return r;
1079 }
static char PqRecvBuffer[PQ_RECV_BUFFER_SIZE]
Definition: pqcomm.c:129
struct Port * MyProcPort
Definition: globals.c:46
#define EAGAIN
Definition: win32_port.h:341
ssize_t secure_read(Port *port, void *ptr, size_t len)
Definition: be-secure.c:147
static void socket_set_nonblocking(bool nonblocking)
Definition: pqcomm.c:916
static int PqRecvLength
Definition: pqcomm.c:131
char * c
#define COMMERROR
Definition: elog.h:30
int errcode_for_socket_access(void)
Definition: elog.c:792
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
int errmsg(const char *fmt,...)
Definition: elog.c:909
static int PqRecvPointer
Definition: pqcomm.c:130
#define EWOULDBLOCK
Definition: win32_port.h:349
static bool PqCommReadingMsg
Definition: pqcomm.c:137
#define EINTR
Definition: win32_port.h:343

◆ pq_getbytes()

int pq_getbytes ( char *  s,
size_t  len 
)

Definition at line 1088 of file pqcomm.c.

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

Referenced by pq_getmessage(), and ProcessStartupPacket().

1089 {
1090  size_t amount;
1091 
1093 
1094  while (len > 0)
1095  {
1096  while (PqRecvPointer >= PqRecvLength)
1097  {
1098  if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1099  return EOF; /* Failed to recv data */
1100  }
1101  amount = PqRecvLength - PqRecvPointer;
1102  if (amount > len)
1103  amount = len;
1104  memcpy(s, PqRecvBuffer + PqRecvPointer, amount);
1105  PqRecvPointer += amount;
1106  s += amount;
1107  len -= amount;
1108  }
1109  return 0;
1110 }
static char PqRecvBuffer[PQ_RECV_BUFFER_SIZE]
Definition: pqcomm.c:129
static int PqRecvLength
Definition: pqcomm.c:131
static int pq_recvbuf(void)
Definition: pqcomm.c:933
#define Assert(condition)
Definition: c.h:804
static int PqRecvPointer
Definition: pqcomm.c:130
static bool PqCommReadingMsg
Definition: pqcomm.c:137

◆ pq_getmessage()

int pq_getmessage ( StringInfo  s,
int  maxlen 
)

Definition at line 1214 of file pqcomm.c.

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

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

1215 {
1216  int32 len;
1217 
1219 
1220  resetStringInfo(s);
1221 
1222  /* Read message length word */
1223  if (pq_getbytes((char *) &len, 4) == EOF)
1224  {
1226  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1227  errmsg("unexpected EOF within message length word")));
1228  return EOF;
1229  }
1230 
1231  len = pg_ntoh32(len);
1232 
1233  if (len < 4 || len > maxlen)
1234  {
1236  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1237  errmsg("invalid message length")));
1238  return EOF;
1239  }
1240 
1241  len -= 4; /* discount length itself */
1242 
1243  if (len > 0)
1244  {
1245  /*
1246  * Allocate space for message. If we run out of room (ridiculously
1247  * large message), we will elog(ERROR), but we want to discard the
1248  * message body so as not to lose communication sync.
1249  */
1250  PG_TRY();
1251  {
1252  enlargeStringInfo(s, len);
1253  }
1254  PG_CATCH();
1255  {
1256  if (pq_discardbytes(len) == EOF)
1258  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1259  errmsg("incomplete message from client")));
1260 
1261  /* we discarded the rest of the message so we're back in sync. */
1262  PqCommReadingMsg = false;
1263  PG_RE_THROW();
1264  }
1265  PG_END_TRY();
1266 
1267  /* And grab the message */
1268  if (pq_getbytes(s->data, len) == EOF)
1269  {
1271  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1272  errmsg("incomplete message from client")));
1273  return EOF;
1274  }
1275  s->len = len;
1276  /* Place a trailing null per StringInfo convention */
1277  s->data[len] = '\0';
1278  }
1279 
1280  /* finished reading the message. */
1281  PqCommReadingMsg = false;
1282 
1283  return 0;
1284 }
static int pq_discardbytes(size_t len)
Definition: pqcomm.c:1122
int errcode(int sqlerrcode)
Definition: elog.c:698
signed int int32
Definition: c.h:429
#define pg_ntoh32(x)
Definition: pg_bswap.h:125
int pq_getbytes(char *s, size_t len)
Definition: pqcomm.c:1088
#define COMMERROR
Definition: elog.h:30
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:283
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
#define ereport(elevel,...)
Definition: elog.h:157
#define PG_CATCH()
Definition: elog.h:323
#define Assert(condition)
Definition: c.h:804
#define PG_RE_THROW()
Definition: elog.h:354
int errmsg(const char *fmt,...)
Definition: elog.c:909
static bool PqCommReadingMsg
Definition: pqcomm.c:137
#define PG_TRY()
Definition: elog.h:313
#define PG_END_TRY()
Definition: elog.h:338

◆ pq_init()

void pq_init ( void  )

Definition at line 176 of file pqcomm.c.

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

Referenced by BackendInitialize().

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

◆ pq_is_reading_msg()

bool pq_is_reading_msg ( void  )

Definition at line 1192 of file pqcomm.c.

References PqCommReadingMsg.

Referenced by PostgresMain().

1193 {
1194  return PqCommReadingMsg;
1195 }
static bool PqCommReadingMsg
Definition: pqcomm.c:137

◆ pq_peekbyte()

int pq_peekbyte ( void  )

Definition at line 1013 of file pqcomm.c.

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

1014 {
1016 
1017  while (PqRecvPointer >= PqRecvLength)
1018  {
1019  if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1020  return EOF; /* Failed to recv data */
1021  }
1022  return (unsigned char) PqRecvBuffer[PqRecvPointer];
1023 }
static char PqRecvBuffer[PQ_RECV_BUFFER_SIZE]
Definition: pqcomm.c:129
static int PqRecvLength
Definition: pqcomm.c:131
static int pq_recvbuf(void)
Definition: pqcomm.c:933
#define Assert(condition)
Definition: c.h:804
static int PqRecvPointer
Definition: pqcomm.c:130
static bool PqCommReadingMsg
Definition: pqcomm.c:137

◆ pq_putmessage_v2()

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

Definition at line 1540 of file pqcomm.c.

References Assert, ereport, errmsg(), internal_putbytes(), Port::keepalives_idle, Port::keepalives_interval, LOG, port, PqCommBusy, Port::sock, STATUS_ERROR, and STATUS_OK.

Referenced by send_message_to_frontend().

1541 {
1542  Assert(msgtype != 0);
1543 
1544  if (PqCommBusy)
1545  return 0;
1546  PqCommBusy = true;
1547  if (internal_putbytes(&msgtype, 1))
1548  goto fail;
1549 
1550  if (internal_putbytes(s, len))
1551  goto fail;
1552  PqCommBusy = false;
1553  return 0;
1554 
1555 fail:
1556  PqCommBusy = false;
1557  return EOF;
1558 }
static int internal_putbytes(const char *s, size_t len)
Definition: pqcomm.c:1288
static bool PqCommBusy
Definition: pqcomm.c:136
#define Assert(condition)
Definition: c.h:804

◆ pq_startmsgread()

void pq_startmsgread ( void  )

Definition at line 1152 of file pqcomm.c.

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

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

1153 {
1154  /*
1155  * There shouldn't be a read active already, but let's check just to be
1156  * sure.
1157  */
1158  if (PqCommReadingMsg)
1159  ereport(FATAL,
1160  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1161  errmsg("terminating connection because protocol synchronization was lost")));
1162 
1163  PqCommReadingMsg = true;
1164 }
int errcode(int sqlerrcode)
Definition: elog.c:698
#define FATAL
Definition: elog.h:49
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909
static bool PqCommReadingMsg
Definition: pqcomm.c:137

◆ RemoveSocketFiles()

void RemoveSocketFiles ( void  )

Definition at line 883 of file pqcomm.c.

References lfirst, and NIL.

Referenced by CloseServerPorts().

884 {
885  ListCell *l;
886 
887  /* Loop through all created sockets... */
888  foreach(l, sock_paths)
889  {
890  char *sock_path = (char *) lfirst(l);
891 
892  /* Ignore any error. */
893  (void) unlink(sock_path);
894  }
895  /* Since we're about to exit, no need to reclaim storage */
896  sock_paths = NIL;
897 }
#define NIL
Definition: pg_list.h:65
static List * sock_paths
Definition: pqcomm.c:112
#define lfirst(lc)
Definition: pg_list.h:169

◆ run_ssl_passphrase_command()

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

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

References appendStringInfoChar(), appendStringInfoString(), Assert, ClosePipeStream(), StringInfoData::data, ereport, errcode_for_file_access(), errdetail_internal(), errmsg(), ERROR, error(), explicit_bzero(), initStringInfo(), LOG, OpenPipeStream(), pfree(), pg_strip_crlf(), ssl_passphrase_command, and wait_result_to_str().

Referenced by ssl_external_passwd_cb().

40 {
41  int loglevel = is_server_start ? ERROR : LOG;
42  StringInfoData command;
43  char *p;
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  initStringInfo(&command);
53 
54  for (p = ssl_passphrase_command; *p; p++)
55  {
56  if (p[0] == '%')
57  {
58  switch (p[1])
59  {
60  case 'p':
61  appendStringInfoString(&command, prompt);
62  p++;
63  break;
64  case '%':
65  appendStringInfoChar(&command, '%');
66  p++;
67  break;
68  default:
69  appendStringInfoChar(&command, p[0]);
70  }
71  }
72  else
73  appendStringInfoChar(&command, p[0]);
74  }
75 
76  fh = OpenPipeStream(command.data, "r");
77  if (fh == NULL)
78  {
79  ereport(loglevel,
81  errmsg("could not execute command \"%s\": %m",
82  command.data)));
83  goto error;
84  }
85 
86  if (!fgets(buf, size, fh))
87  {
88  if (ferror(fh))
89  {
90  explicit_bzero(buf, size);
91  ereport(loglevel,
93  errmsg("could not read from command \"%s\": %m",
94  command.data)));
95  goto error;
96  }
97  }
98 
99  pclose_rc = ClosePipeStream(fh);
100  if (pclose_rc == -1)
101  {
102  explicit_bzero(buf, size);
103  ereport(loglevel,
105  errmsg("could not close pipe to external command: %m")));
106  goto error;
107  }
108  else if (pclose_rc != 0)
109  {
110  explicit_bzero(buf, size);
111  ereport(loglevel,
113  errmsg("command \"%s\" failed",
114  command.data),
115  errdetail_internal("%s", wait_result_to_str(pclose_rc))));
116  goto error;
117  }
118 
119  /* strip trailing newline and carriage return */
120  len = pg_strip_crlf(buf);
121 
122 error:
123  pfree(command.data);
124  return len;
125 }
int pg_strip_crlf(char *str)
Definition: string.c:121
static void error(void)
Definition: sql-dyntest.c:147
#define LOG
Definition: elog.h:26
char * wait_result_to_str(int exitstatus)
Definition: wait_error.c:32
int ClosePipeStream(FILE *file)
Definition: fd.c:2782
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1069
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ERROR
Definition: elog.h:46
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:68
int errcode_for_file_access(void)
Definition: elog.c:721
FILE * OpenPipeStream(const char *command, const char *mode)
Definition: fd.c:2476
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
int errmsg(const char *fmt,...)
Definition: elog.c:909
void explicit_bzero(void *buf, size_t len)
char * ssl_passphrase_command
Definition: be-secure.c:47

◆ secure_close()

void secure_close ( Port port)

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

References be_tls_close(), and Port::ssl_in_use.

Referenced by socket_close().

136 {
137 #ifdef USE_SSL
138  if (port->ssl_in_use)
139  be_tls_close(port);
140 #endif
141 }
bool ssl_in_use
Definition: libpq-be.h:209
void be_tls_close(Port *port)

◆ secure_destroy()

void secure_destroy ( void  )

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

References be_tls_destroy().

Referenced by SIGHUP_handler().

92 {
93 #ifdef USE_SSL
95 #endif
96 }
void be_tls_destroy(void)

◆ secure_initialize()

int secure_initialize ( bool  isServerStart)

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

References be_tls_init().

Referenced by BackendRun(), PostmasterMain(), and SIGHUP_handler().

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

◆ secure_loaded_verify_locations()

bool secure_loaded_verify_locations ( void  )

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

Referenced by ClientAuthentication().

103 {
104 #ifdef USE_SSL
105  return ssl_loaded_verify_locations;
106 #else
107  return false;
108 #endif
109 }

◆ secure_open_server()

int secure_open_server ( Port port)

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

References be_tls_open_server(), DEBUG2, ereport, errmsg_internal(), Port::peer_cn, and Port::peer_dn.

Referenced by ProcessStartupPacket().

116 {
117  int r = 0;
118 
119 #ifdef USE_SSL
120  r = be_tls_open_server(port);
121 
122  ereport(DEBUG2,
123  (errmsg_internal("SSL connection from DN:\"%s\" CN:\"%s\"",
124  port->peer_dn ? port->peer_dn : "(anonymous)",
125  port->peer_cn ? port->peer_cn : "(anonymous)")));
126 #endif
127 
128  return r;
129 }
char * peer_dn
Definition: libpq-be.h:211
char * peer_cn
Definition: libpq-be.h:210
#define DEBUG2
Definition: elog.h:24
#define ereport(elevel,...)
Definition: elog.h:157
int be_tls_open_server(Port *port)
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996

◆ secure_raw_read()

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

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

References pgwin32_noblock, recv, and Port::sock.

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

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

◆ secure_raw_write()

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

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

References pgwin32_noblock, send, and Port::sock.

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

333 {
334  ssize_t n;
335 
336 #ifdef WIN32
337  pgwin32_noblock = true;
338 #endif
339  n = send(port->sock, ptr, len, 0);
340 #ifdef WIN32
341  pgwin32_noblock = false;
342 #endif
343 
344  return n;
345 }
int pgwin32_noblock
Definition: socket.c:28
pgsocket sock
Definition: libpq-be.h:127
#define send(s, buf, len, flags)
Definition: win32_port.h:466

◆ secure_read()

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

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

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

Referenced by pq_getbyte_if_available(), and pq_recvbuf().

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

◆ secure_write()

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

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

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

Referenced by internal_flush().

261 {
262  ssize_t n;
263  int waitfor;
264 
265  /* Deal with any already-pending interrupt condition. */
267 
268 retry:
269  waitfor = 0;
270 #ifdef USE_SSL
271  if (port->ssl_in_use)
272  {
273  n = be_tls_write(port, ptr, len, &waitfor);
274  }
275  else
276 #endif
277 #ifdef ENABLE_GSS
278  if (port->gss && port->gss->enc)
279  {
280  n = be_gssapi_write(port, ptr, len);
281  waitfor = WL_SOCKET_WRITEABLE;
282  }
283  else
284 #endif
285  {
286  n = secure_raw_write(port, ptr, len);
287  waitfor = WL_SOCKET_WRITEABLE;
288  }
289 
290  if (n < 0 && !port->noblock && (errno == EWOULDBLOCK || errno == EAGAIN))
291  {
292  WaitEvent event;
293 
294  Assert(waitfor);
295 
297 
298  WaitEventSetWait(FeBeWaitSet, -1 /* no timeout */ , &event, 1,
300 
301  /* See comments in secure_read. */
302  if (event.events & WL_POSTMASTER_DEATH)
303  ereport(FATAL,
304  (errcode(ERRCODE_ADMIN_SHUTDOWN),
305  errmsg("terminating connection due to unexpected postmaster exit")));
306 
307  /* Handle interrupt. */
308  if (event.events & WL_LATCH_SET)
309  {
312 
313  /*
314  * We'll retry the write. Most likely it will return immediately
315  * because there's still no buffer space available, and we'll wait
316  * for the socket to become ready again.
317  */
318  }
319  goto retry;
320  }
321 
322  /*
323  * Process interrupts that happened during a successful (or non-blocking,
324  * or hard-failed) write.
325  */
327 
328  return n;
329 }
#define FeBeWaitSetSocketPos
Definition: libpq.h:63
#define WL_SOCKET_WRITEABLE
Definition: latch.h:127
#define EAGAIN
Definition: win32_port.h:341
ssize_t secure_raw_write(Port *port, const void *ptr, size_t len)
Definition: be-secure.c:332
int errcode(int sqlerrcode)
Definition: elog.c:698
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:948
bool ssl_in_use
Definition: libpq-be.h:209
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:168
void ResetLatch(Latch *latch)
Definition: latch.c:660
#define FATAL
Definition: elog.h:49
uint32 events
Definition: latch.h:145
ssize_t be_tls_write(Port *port, void *ptr, size_t len, int *waitfor)
#define WL_POSTMASTER_DEATH
Definition: latch.h:129
ssize_t be_gssapi_write(Port *port, void *ptr, size_t len)
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
void * gss
Definition: libpq-be.h:203
int errmsg(const char *fmt,...)
Definition: elog.c:909
struct Latch * MyLatch
Definition: globals.c:57
#define EWOULDBLOCK
Definition: win32_port.h:349
#define WL_LATCH_SET
Definition: latch.h:125
int WaitEventSetWait(WaitEventSet *set, long timeout, WaitEvent *occurred_events, int nevents, uint32 wait_event_info)
Definition: latch.c:1306
void ProcessClientWriteInterrupt(bool blocked)
Definition: postgres.c:538

◆ StreamClose()

void StreamClose ( pgsocket  sock)

Definition at line 850 of file pqcomm.c.

References closesocket.

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

851 {
852  closesocket(sock);
853 }
#define closesocket
Definition: port.h:332

◆ StreamConnection()

int StreamConnection ( pgsocket  server_fd,
Port port 
)

Definition at line 716 of file pqcomm.c.

References accept, SockAddr::addr, ereport, errcode_for_socket_access(), errmsg(), IS_AF_UNIX, Port::laddr, LOG, pg_usleep(), PGINVALID_SOCKET, PQ_SEND_BUFFER_SIZE, pq_setkeepalivescount(), pq_setkeepalivesidle(), pq_setkeepalivesinterval(), pq_settcpusertimeout(), Port::raddr, SockAddr::salen, Port::sock, STATUS_ERROR, STATUS_OK, tcp_keepalives_count, tcp_keepalives_idle, tcp_keepalives_interval, and tcp_user_timeout.

Referenced by ConnCreate().

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

◆ StreamServerPort()

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

Definition at line 318 of file pqcomm.c.

References _, addrinfo::ai_family, addrinfo::ai_flags, addrinfo::ai_next, AI_PASSIVE, addrinfo::ai_socktype, Assert, bind, closesocket, CreateSocketLockFile(), EADDRINUSE, elog, ereport, errcode_for_file_access(), errcode_for_socket_access(), errhint(), errmsg(), fd(), gai_strerror, IS_AF_UNIX, lappend(), listen, LOG, MaxBackends, MAXPGPATH, MemSet, NI_MAXHOST, NI_NUMERICHOST, pg_freeaddrinfo_all(), pg_getaddrinfo_all(), pg_getnameinfo_all(), PG_SOMAXCONN, PGINVALID_SOCKET, pstrdup(), snprintf, socket, STATUS_ERROR, STATUS_OK, Unix_socket_group, Unix_socket_permissions, UNIXSOCK_PATH, UNIXSOCK_PATH_BUFLEN, val, and WARNING.

Referenced by PostmasterMain().

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

◆ TouchSocketFiles()

void TouchSocketFiles ( void  )

Definition at line 865 of file pqcomm.c.

References lfirst.

Referenced by ServerLoop().

866 {
867  ListCell *l;
868 
869  /* Loop through all created sockets... */
870  foreach(l, sock_paths)
871  {
872  char *sock_path = (char *) lfirst(l);
873 
874  /* Ignore errors; there's no point in complaining */
875  (void) utime(sock_path, NULL);
876  }
877 }
static List * sock_paths
Definition: pqcomm.c:112
#define lfirst(lc)
Definition: pg_list.h:169

Variable Documentation

◆ FeBeWaitSet

WaitEventSet* FeBeWaitSet

◆ PqCommMethods

const PGDLLIMPORT PQcommMethods* PqCommMethods

Definition at line 166 of file pqcomm.c.

Referenced by pq_redirect_to_shm_mq(), and pq_set_parallel_leader().

◆ ssl_ca_file

char* ssl_ca_file

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

Referenced by be_tls_init().

◆ ssl_cert_file

char* ssl_cert_file

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

Referenced by be_tls_init().

◆ ssl_crl_dir

char* ssl_crl_dir

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

Referenced by be_tls_init().

◆ ssl_crl_file

char* ssl_crl_file

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

Referenced by be_tls_init().

◆ ssl_dh_params_file

char* ssl_dh_params_file

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

Referenced by initialize_dh().

◆ ssl_key_file

char* ssl_key_file

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

Referenced by be_tls_init().

◆ ssl_library

char* ssl_library

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

◆ ssl_max_protocol_version

int ssl_max_protocol_version

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

Referenced by be_tls_init(), and be_tls_open_server().

◆ ssl_min_protocol_version

int ssl_min_protocol_version

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

Referenced by be_tls_init(), and be_tls_open_server().

◆ ssl_passphrase_command

PGDLLIMPORT char* ssl_passphrase_command

Definition at line 47 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

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

Referenced by default_openssl_tls_init().

◆ SSLCipherSuites

char* SSLCipherSuites

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

Referenced by be_tls_init().

◆ SSLECDHCurve

char* SSLECDHCurve

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

Referenced by initialize_ecdh().

◆ SSLPreferServerCiphers

bool SSLPreferServerCiphers

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

Referenced by be_tls_init().