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_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 pq_startcopyout()   (PqCommMethods->startcopyout())
 
#define pq_endcopyout(errorAbort)   (PqCommMethods->endcopyout(errorAbort))
 

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, char *hostName, unsigned short portNumber, 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)
 
int pq_getstring (StringInfo s)
 
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_putbytes (const char *s, size_t len)
 
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_dh_params_file
 
char * ssl_passphrase_command
 
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

◆ pq_comm_reset

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

Definition at line 38 of file libpq.h.

Referenced by PostgresMain().

◆ pq_endcopyout

#define pq_endcopyout (   errorAbort)    (PqCommMethods->endcopyout(errorAbort))

Definition at line 47 of file libpq.h.

Referenced by DoCopyTo(), errfinish(), SendCopyEnd(), and socket_comm_reset().

◆ pq_flush

◆ pq_flush_if_writable

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

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

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

◆ pq_putmessage

◆ pq_putmessage_noblock

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

Definition at line 44 of file libpq.h.

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

◆ pq_startcopyout

#define pq_startcopyout ( )    (PqCommMethods->startcopyout())

Definition at line 46 of file libpq.h.

Referenced by SendCopyBegin().

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 116 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, 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:570
#define LOG
Definition: elog.h:26
#define FATAL
Definition: elog.h:52
static char * buf
Definition: pg_test_fsync.c:68
#define S_IRWXG
Definition: win32_port.h:290
int errdetail(const char *fmt,...)
Definition: elog.c:860
int errcode_for_file_access(void)
Definition: elog.c:593
#define S_IWGRP
Definition: win32_port.h:284
#define ereport(elevel, rest)
Definition: elog.h:141
#define S_ISREG(m)
Definition: win32_port.h:308
#define stat(a, b)
Definition: win32_port.h:264
#define S_IXGRP
Definition: win32_port.h:287
int errmsg(const char *fmt,...)
Definition: elog.c:784
char * ssl_key_file
Definition: be-secure.c:43
#define S_IRWXO
Definition: win32_port.h:302

◆ pq_endmsgread()

void pq_endmsgread ( void  )

Definition at line 1235 of file pqcomm.c.

References Assert, and PqCommReadingMsg.

Referenced by CopyFrom(), ProcessRepliesIfAny(), ProcessStartupPacket(), and SocketBackend().

1236 {
1238 
1239  PqCommReadingMsg = false;
1240 }
#define Assert(condition)
Definition: c.h:732
static bool PqCommReadingMsg
Definition: pqcomm.c:150

◆ pq_getbyte()

int pq_getbyte ( void  )

Definition at line 1001 of file pqcomm.c.

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

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

1002 {
1004 
1005  while (PqRecvPointer >= PqRecvLength)
1006  {
1007  if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1008  return EOF; /* Failed to recv data */
1009  }
1010  return (unsigned char) PqRecvBuffer[PqRecvPointer++];
1011 }
static char PqRecvBuffer[PQ_RECV_BUFFER_SIZE]
Definition: pqcomm.c:142
static int PqRecvLength
Definition: pqcomm.c:144
static int pq_recvbuf(void)
Definition: pqcomm.c:940
#define Assert(condition)
Definition: c.h:732
static int PqRecvPointer
Definition: pqcomm.c:143
static bool PqCommReadingMsg
Definition: pqcomm.c:150

◆ pq_getbyte_if_available()

int pq_getbyte_if_available ( unsigned char *  c)

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

1042 {
1043  int r;
1044 
1046 
1048  {
1050  return 1;
1051  }
1052 
1053  /* Put the socket into non-blocking mode */
1054  socket_set_nonblocking(true);
1055 
1056  r = secure_read(MyProcPort, c, 1);
1057  if (r < 0)
1058  {
1059  /*
1060  * Ok if no data available without blocking or interrupted (though
1061  * EINTR really shouldn't happen with a non-blocking socket). Report
1062  * other errors.
1063  */
1064  if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
1065  r = 0;
1066  else
1067  {
1068  /*
1069  * Careful: an ereport() that tries to write to the client would
1070  * cause recursion to here, leading to stack overflow and core
1071  * dump! This message must go *only* to the postmaster log.
1072  */
1075  errmsg("could not receive data from client: %m")));
1076  r = EOF;
1077  }
1078  }
1079  else if (r == 0)
1080  {
1081  /* EOF detected */
1082  r = EOF;
1083  }
1084 
1085  return r;
1086 }
static char PqRecvBuffer[PQ_RECV_BUFFER_SIZE]
Definition: pqcomm.c:142
struct Port * MyProcPort
Definition: globals.c:43
#define EAGAIN
Definition: win32_port.h:330
ssize_t secure_read(Port *port, void *ptr, size_t len)
Definition: be-secure.c:146
static void socket_set_nonblocking(bool nonblocking)
Definition: pqcomm.c:923
static int PqRecvLength
Definition: pqcomm.c:144
char * c
#define COMMERROR
Definition: elog.h:30
#define ereport(elevel, rest)
Definition: elog.h:141
int errcode_for_socket_access(void)
Definition: elog.c:664
#define Assert(condition)
Definition: c.h:732
int errmsg(const char *fmt,...)
Definition: elog.c:784
static int PqRecvPointer
Definition: pqcomm.c:143
#define EWOULDBLOCK
Definition: win32_port.h:338
static bool PqCommReadingMsg
Definition: pqcomm.c:150
#define EINTR
Definition: win32_port.h:332

◆ pq_getbytes()

int pq_getbytes ( char *  s,
size_t  len 
)

Definition at line 1095 of file pqcomm.c.

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

Referenced by CopyGetData(), GetOldFunctionMessage(), pq_getmessage(), and ProcessStartupPacket().

1096 {
1097  size_t amount;
1098 
1100 
1101  while (len > 0)
1102  {
1103  while (PqRecvPointer >= PqRecvLength)
1104  {
1105  if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1106  return EOF; /* Failed to recv data */
1107  }
1108  amount = PqRecvLength - PqRecvPointer;
1109  if (amount > len)
1110  amount = len;
1111  memcpy(s, PqRecvBuffer + PqRecvPointer, amount);
1112  PqRecvPointer += amount;
1113  s += amount;
1114  len -= amount;
1115  }
1116  return 0;
1117 }
static char PqRecvBuffer[PQ_RECV_BUFFER_SIZE]
Definition: pqcomm.c:142
static int PqRecvLength
Definition: pqcomm.c:144
static int pq_recvbuf(void)
Definition: pqcomm.c:940
#define Assert(condition)
Definition: c.h:732
static int PqRecvPointer
Definition: pqcomm.c:143
static bool PqCommReadingMsg
Definition: pqcomm.c:150

◆ pq_getmessage()

int pq_getmessage ( StringInfo  s,
int  maxlen 
)

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

1274 {
1275  int32 len;
1276 
1278 
1279  resetStringInfo(s);
1280 
1281  /* Read message length word */
1282  if (pq_getbytes((char *) &len, 4) == EOF)
1283  {
1285  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1286  errmsg("unexpected EOF within message length word")));
1287  return EOF;
1288  }
1289 
1290  len = pg_ntoh32(len);
1291 
1292  if (len < 4 ||
1293  (maxlen > 0 && len > maxlen))
1294  {
1296  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1297  errmsg("invalid message length")));
1298  return EOF;
1299  }
1300 
1301  len -= 4; /* discount length itself */
1302 
1303  if (len > 0)
1304  {
1305  /*
1306  * Allocate space for message. If we run out of room (ridiculously
1307  * large message), we will elog(ERROR), but we want to discard the
1308  * message body so as not to lose communication sync.
1309  */
1310  PG_TRY();
1311  {
1312  enlargeStringInfo(s, len);
1313  }
1314  PG_CATCH();
1315  {
1316  if (pq_discardbytes(len) == EOF)
1318  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1319  errmsg("incomplete message from client")));
1320 
1321  /* we discarded the rest of the message so we're back in sync. */
1322  PqCommReadingMsg = false;
1323  PG_RE_THROW();
1324  }
1325  PG_END_TRY();
1326 
1327  /* And grab the message */
1328  if (pq_getbytes(s->data, len) == EOF)
1329  {
1331  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1332  errmsg("incomplete message from client")));
1333  return EOF;
1334  }
1335  s->len = len;
1336  /* Place a trailing null per StringInfo convention */
1337  s->data[len] = '\0';
1338  }
1339 
1340  /* finished reading the message. */
1341  PqCommReadingMsg = false;
1342 
1343  return 0;
1344 }
static int pq_discardbytes(size_t len)
Definition: pqcomm.c:1129
int errcode(int sqlerrcode)
Definition: elog.c:570
signed int int32
Definition: c.h:346
#define pg_ntoh32(x)
Definition: pg_bswap.h:125
int pq_getbytes(char *s, size_t len)
Definition: pqcomm.c:1095
#define COMMERROR
Definition: elog.h:30
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:270
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:62
#define ereport(elevel, rest)
Definition: elog.h:141
#define PG_CATCH()
Definition: elog.h:310
#define Assert(condition)
Definition: c.h:732
#define PG_RE_THROW()
Definition: elog.h:331
int errmsg(const char *fmt,...)
Definition: elog.c:784
static bool PqCommReadingMsg
Definition: pqcomm.c:150
#define PG_TRY()
Definition: elog.h:301
#define PG_END_TRY()
Definition: elog.h:317

◆ pq_getstring()

int pq_getstring ( StringInfo  s)

Definition at line 1167 of file pqcomm.c.

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

Referenced by GetOldFunctionMessage(), and SocketBackend().

1168 {
1169  int i;
1170 
1172 
1173  resetStringInfo(s);
1174 
1175  /* Read until we get the terminating '\0' */
1176  for (;;)
1177  {
1178  while (PqRecvPointer >= PqRecvLength)
1179  {
1180  if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1181  return EOF; /* Failed to recv data */
1182  }
1183 
1184  for (i = PqRecvPointer; i < PqRecvLength; i++)
1185  {
1186  if (PqRecvBuffer[i] == '\0')
1187  {
1188  /* include the '\0' in the copy */
1190  i - PqRecvPointer + 1);
1191  PqRecvPointer = i + 1; /* advance past \0 */
1192  return 0;
1193  }
1194  }
1195 
1196  /* If we're here we haven't got the \0 in the buffer yet. */
1198  PqRecvLength - PqRecvPointer);
1200  }
1201 }
static char PqRecvBuffer[PQ_RECV_BUFFER_SIZE]
Definition: pqcomm.c:142
static int PqRecvLength
Definition: pqcomm.c:144
static int pq_recvbuf(void)
Definition: pqcomm.c:940
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:62
#define Assert(condition)
Definition: c.h:732
int i
static int PqRecvPointer
Definition: pqcomm.c:143
static bool PqCommReadingMsg
Definition: pqcomm.c:150
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:214

◆ pq_init()

void pq_init ( void  )

Definition at line 194 of file pqcomm.c.

References AddWaitEventToSet(), COMMERROR, CreateWaitEventSet(), DoingCopyOut, ereport, errmsg(), MemoryContextAlloc(), MyLatch, MyProcPort, on_proc_exit(), pg_set_noblock(), 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().

195 {
196  /* initialize state variables */
200  PqCommBusy = false;
201  PqCommReadingMsg = false;
202  DoingCopyOut = false;
203 
204  /* set up process-exit hook to close the socket */
206 
207  /*
208  * In backends (as soon as forked) we operate the underlying socket in
209  * nonblocking mode and use latches to implement blocking semantics if
210  * needed. That allows us to provide safely interruptible reads and
211  * writes.
212  *
213  * Use COMMERROR on failure, because ERROR would try to send the error to
214  * the client, which might require changing the mode again, leading to
215  * infinite recursion.
216  */
217 #ifndef WIN32
220  (errmsg("could not set socket to nonblocking mode: %m")));
221 #endif
222 
225  NULL, NULL);
228 }
#define WL_SOCKET_WRITEABLE
Definition: latch.h:126
static bool DoingCopyOut
Definition: pqcomm.c:151
struct Port * MyProcPort
Definition: globals.c:43
int AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch, void *user_data)
Definition: latch.c:690
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:305
static char * PqSendBuffer
Definition: pqcomm.c:137
static int PqSendStart
Definition: pqcomm.c:140
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:186
pgsocket sock
Definition: libpq-be.h:122
WaitEventSet * CreateWaitEventSet(MemoryContext context, int nevents)
Definition: latch.c:542
static int PqRecvLength
Definition: pqcomm.c:144
static int PqSendPointer
Definition: pqcomm.c:139
#define COMMERROR
Definition: elog.h:30
#define ereport(elevel, rest)
Definition: elog.h:141
MemoryContext TopMemoryContext
Definition: mcxt.c:44
static int PqSendBufferSize
Definition: pqcomm.c:138
static bool PqCommBusy
Definition: pqcomm.c:149
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
bool pg_set_noblock(pgsocket sock)
Definition: noblock.c:25
static void socket_close(int code, Datum arg)
Definition: pqcomm.c:256
int errmsg(const char *fmt,...)
Definition: elog.c:784
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:771
struct Latch * MyLatch
Definition: globals.c:54
static int PqRecvPointer
Definition: pqcomm.c:143
static bool PqCommReadingMsg
Definition: pqcomm.c:150
#define WL_LATCH_SET
Definition: latch.h:124
#define PQ_SEND_BUFFER_SIZE
Definition: pqcomm.c:134

◆ pq_is_reading_msg()

bool pq_is_reading_msg ( void  )

Definition at line 1251 of file pqcomm.c.

References PqCommReadingMsg.

Referenced by PostgresMain().

1252 {
1253  return PqCommReadingMsg;
1254 }
static bool PqCommReadingMsg
Definition: pqcomm.c:150

◆ pq_peekbyte()

int pq_peekbyte ( void  )

Definition at line 1020 of file pqcomm.c.

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

Referenced by recv_password_packet().

1021 {
1023 
1024  while (PqRecvPointer >= PqRecvLength)
1025  {
1026  if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1027  return EOF; /* Failed to recv data */
1028  }
1029  return (unsigned char) PqRecvBuffer[PqRecvPointer];
1030 }
static char PqRecvBuffer[PQ_RECV_BUFFER_SIZE]
Definition: pqcomm.c:142
static int PqRecvLength
Definition: pqcomm.c:144
static int pq_recvbuf(void)
Definition: pqcomm.c:940
#define Assert(condition)
Definition: c.h:732
static int PqRecvPointer
Definition: pqcomm.c:143
static bool PqCommReadingMsg
Definition: pqcomm.c:150

◆ pq_putbytes()

int pq_putbytes ( const char *  s,
size_t  len 
)

Definition at line 1354 of file pqcomm.c.

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

Referenced by CopySendEndOfRow(), and socket_endcopyout().

1355 {
1356  int res;
1357 
1358  /* Should only be called by old-style COPY OUT */
1360  /* No-op if reentrant call */
1361  if (PqCommBusy)
1362  return 0;
1363  PqCommBusy = true;
1364  res = internal_putbytes(s, len);
1365  PqCommBusy = false;
1366  return res;
1367 }
static bool DoingCopyOut
Definition: pqcomm.c:151
static int internal_putbytes(const char *s, size_t len)
Definition: pqcomm.c:1370
static bool PqCommBusy
Definition: pqcomm.c:149
#define Assert(condition)
Definition: c.h:732

◆ pq_startmsgread()

void pq_startmsgread ( void  )

Definition at line 1211 of file pqcomm.c.

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

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

1212 {
1213  /*
1214  * There shouldn't be a read active already, but let's check just to be
1215  * sure.
1216  */
1217  if (PqCommReadingMsg)
1218  ereport(FATAL,
1219  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1220  errmsg("terminating connection because protocol synchronization was lost")));
1221 
1222  PqCommReadingMsg = true;
1223 }
int errcode(int sqlerrcode)
Definition: elog.c:570
#define FATAL
Definition: elog.h:52
#define ereport(elevel, rest)
Definition: elog.h:141
int errmsg(const char *fmt,...)
Definition: elog.c:784
static bool PqCommReadingMsg
Definition: pqcomm.c:150

◆ RemoveSocketFiles()

void RemoveSocketFiles ( void  )

Definition at line 890 of file pqcomm.c.

References lfirst, and NIL.

Referenced by CloseServerPorts().

891 {
892  ListCell *l;
893 
894  /* Loop through all created sockets... */
895  foreach(l, sock_paths)
896  {
897  char *sock_path = (char *) lfirst(l);
898 
899  /* Ignore any error. */
900  (void) unlink(sock_path);
901  }
902  /* Since we're about to exit, no need to reclaim storage */
903  sock_paths = NIL;
904 }
#define NIL
Definition: pg_list.h:65
static List * sock_paths
Definition: pqcomm.c:125
#define lfirst(lc)
Definition: pg_list.h:190

◆ 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:105
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:2614
int errdetail_internal(const char *fmt,...)
Definition: elog.c:887
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ERROR
Definition: elog.h:43
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:163
static char * buf
Definition: pg_test_fsync.c:68
int errcode_for_file_access(void)
Definition: elog.c:593
FILE * OpenPipeStream(const char *command, const char *mode)
Definition: fd.c:2308
#define ereport(elevel, rest)
Definition: elog.h:141
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:175
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define Assert(condition)
Definition: c.h:732
int errmsg(const char *fmt,...)
Definition: elog.c:784
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 134 of file be-secure.c.

References be_tls_close(), and Port::ssl_in_use.

Referenced by ConnFree(), and socket_close().

135 {
136 #ifdef USE_SSL
137  if (port->ssl_in_use)
138  be_tls_close(port);
139 #endif
140 }
bool ssl_in_use
Definition: libpq-be.h:190
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(), and Port::peer_cn.

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("SSL connection from \"%s\"",
124  port->peer_cn ? port->peer_cn : "(anonymous)")));
125 #endif
126 
127  return r;
128 }
char * peer_cn
Definition: libpq-be.h:191
#define DEBUG2
Definition: elog.h:24
#define ereport(elevel, rest)
Definition: elog.h:141
int be_tls_open_server(Port *port)
int errmsg(const char *fmt,...)
Definition: elog.c:784

◆ secure_raw_read()

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

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

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

◆ secure_raw_write()

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

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

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

◆ secure_read()

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

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

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

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

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

260 {
261  ssize_t n;
262  int waitfor;
263 
264  /* Deal with any already-pending interrupt condition. */
266 
267 retry:
268  waitfor = 0;
269 #ifdef USE_SSL
270  if (port->ssl_in_use)
271  {
272  n = be_tls_write(port, ptr, len, &waitfor);
273  }
274  else
275 #endif
276 #ifdef ENABLE_GSS
277  if (port->gss->enc)
278  {
279  n = be_gssapi_write(port, ptr, len);
280  waitfor = WL_SOCKET_WRITEABLE;
281  }
282  else
283 #endif
284  {
285  n = secure_raw_write(port, ptr, len);
286  waitfor = WL_SOCKET_WRITEABLE;
287  }
288 
289  if (n < 0 && !port->noblock && (errno == EWOULDBLOCK || errno == EAGAIN))
290  {
291  WaitEvent event;
292 
293  Assert(waitfor);
294 
295  ModifyWaitEvent(FeBeWaitSet, 0, waitfor, NULL);
296 
297  WaitEventSetWait(FeBeWaitSet, -1 /* no timeout */ , &event, 1,
299 
300  /* See comments in secure_read. */
301  if (event.events & WL_POSTMASTER_DEATH)
302  ereport(FATAL,
303  (errcode(ERRCODE_ADMIN_SHUTDOWN),
304  errmsg("terminating connection due to unexpected postmaster exit")));
305 
306  /* Handle interrupt. */
307  if (event.events & WL_LATCH_SET)
308  {
311 
312  /*
313  * We'll retry the write. Most likely it will return immediately
314  * because there's still no buffer space available, and we'll wait
315  * for the socket to become ready again.
316  */
317  }
318  goto retry;
319  }
320 
321  /*
322  * Process interrupts that happened during a successful (or non-blocking,
323  * or hard-failed) write.
324  */
326 
327  return n;
328 }
#define WL_SOCKET_WRITEABLE
Definition: latch.h:126
#define EAGAIN
Definition: win32_port.h:330
ssize_t secure_raw_write(Port *port, const void *ptr, size_t len)
Definition: be-secure.c:331
int errcode(int sqlerrcode)
Definition: elog.c:570
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:766
bool ssl_in_use
Definition: libpq-be.h:190
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:186
void ResetLatch(Latch *latch)
Definition: latch.c:519
#define FATAL
Definition: elog.h:52
uint32 events
Definition: latch.h:144
ssize_t be_tls_write(Port *port, void *ptr, size_t len, int *waitfor)
#define ereport(elevel, rest)
Definition: elog.h:141
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
ssize_t be_gssapi_write(Port *port, void *ptr, size_t len)
#define Assert(condition)
Definition: c.h:732
void * gss
Definition: libpq-be.h:184
int errmsg(const char *fmt,...)
Definition: elog.c:784
struct Latch * MyLatch
Definition: globals.c:54
#define EWOULDBLOCK
Definition: win32_port.h:338
#define WL_LATCH_SET
Definition: latch.h:124
int WaitEventSetWait(WaitEventSet *set, long timeout, WaitEvent *occurred_events, int nevents, uint32 wait_event_info)
Definition: latch.c:953
void ProcessClientWriteInterrupt(bool blocked)
Definition: postgres.c:576

◆ StreamClose()

void StreamClose ( pgsocket  sock)

Definition at line 845 of file pqcomm.c.

References closesocket.

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

846 {
847  closesocket(sock);
848 }
#define closesocket
Definition: port.h:312

◆ StreamConnection()

int StreamConnection ( pgsocket  server_fd,
Port port 
)

Definition at line 716 of file pqcomm.c.

References accept, SockAddr::addr, elog, 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  elog(LOG, "getsockname() failed: %m");
746  return STATUS_ERROR;
747  }
748 
749  /* select NODELAY and KEEPALIVE options if it's a TCP connection */
750  if (!IS_AF_UNIX(port->laddr.addr.ss_family))
751  {
752  int on;
753 #ifdef WIN32
754  int oldopt;
755  int optlen;
756  int newopt;
757 #endif
758 
759 #ifdef TCP_NODELAY
760  on = 1;
761  if (setsockopt(port->sock, IPPROTO_TCP, TCP_NODELAY,
762  (char *) &on, sizeof(on)) < 0)
763  {
764  elog(LOG, "setsockopt(%s) failed: %m", "TCP_NODELAY");
765  return STATUS_ERROR;
766  }
767 #endif
768  on = 1;
769  if (setsockopt(port->sock, SOL_SOCKET, SO_KEEPALIVE,
770  (char *) &on, sizeof(on)) < 0)
771  {
772  elog(LOG, "setsockopt(%s) failed: %m", "SO_KEEPALIVE");
773  return STATUS_ERROR;
774  }
775 
776 #ifdef WIN32
777 
778  /*
779  * This is a Win32 socket optimization. The OS send buffer should be
780  * large enough to send the whole Postgres send buffer in one go, or
781  * performance suffers. The Postgres send buffer can be enlarged if a
782  * very large message needs to be sent, but we won't attempt to
783  * enlarge the OS buffer if that happens, so somewhat arbitrarily
784  * ensure that the OS buffer is at least PQ_SEND_BUFFER_SIZE * 4.
785  * (That's 32kB with the current default).
786  *
787  * The default OS buffer size used to be 8kB in earlier Windows
788  * versions, but was raised to 64kB in Windows 2012. So it shouldn't
789  * be necessary to change it in later versions anymore. Changing it
790  * unnecessarily can even reduce performance, because setting
791  * SO_SNDBUF in the application disables the "dynamic send buffering"
792  * feature that was introduced in Windows 7. So before fiddling with
793  * SO_SNDBUF, check if the current buffer size is already large enough
794  * and only increase it if necessary.
795  *
796  * See https://support.microsoft.com/kb/823764/EN-US/ and
797  * https://msdn.microsoft.com/en-us/library/bb736549%28v=vs.85%29.aspx
798  */
799  optlen = sizeof(oldopt);
800  if (getsockopt(port->sock, SOL_SOCKET, SO_SNDBUF, (char *) &oldopt,
801  &optlen) < 0)
802  {
803  elog(LOG, "getsockopt(%s) failed: %m", "SO_SNDBUF");
804  return STATUS_ERROR;
805  }
806  newopt = PQ_SEND_BUFFER_SIZE * 4;
807  if (oldopt < newopt)
808  {
809  if (setsockopt(port->sock, SOL_SOCKET, SO_SNDBUF, (char *) &newopt,
810  sizeof(newopt)) < 0)
811  {
812  elog(LOG, "setsockopt(%s) failed: %m", "SO_SNDBUF");
813  return STATUS_ERROR;
814  }
815  }
816 #endif
817 
818  /*
819  * Also apply the current keepalive parameters. If we fail to set a
820  * parameter, don't error out, because these aren't universally
821  * supported. (Note: you might think we need to reset the GUC
822  * variables to 0 in such a case, but it's not necessary because the
823  * show hooks for these variables report the truth anyway.)
824  */
829  }
830 
831  return STATUS_OK;
832 }
#define accept(s, addr, addrlen)
Definition: win32_port.h:443
int pq_setkeepalivesinterval(int interval, Port *port)
Definition: pqcomm.c:1813
struct sockaddr_storage addr
Definition: pqcomm.h:64
int tcp_user_timeout
Definition: guc.c:534
#define STATUS_ERROR
Definition: c.h:1090
#define LOG
Definition: elog.h:26
pgsocket sock
Definition: libpq-be.h:122
int tcp_keepalives_idle
Definition: guc.c:531
SockAddr raddr
Definition: libpq-be.h:126
void pg_usleep(long microsec)
Definition: signal.c:53
int pq_setkeepalivesidle(int idle, Port *port)
Definition: pqcomm.c:1731
#define IS_AF_UNIX(fam)
Definition: ip.h:24
ACCEPT_TYPE_ARG3 salen
Definition: pqcomm.h:65
#define ereport(elevel, rest)
Definition: elog.h:141
#define STATUS_OK
Definition: c.h:1089
int tcp_keepalives_interval
Definition: guc.c:532
int errcode_for_socket_access(void)
Definition: elog.c:664
SockAddr laddr
Definition: libpq-be.h:125
#define PGINVALID_SOCKET
Definition: port.h:33
int pq_setkeepalivescount(int count, Port *port)
Definition: pqcomm.c:1889
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
int pq_settcpusertimeout(int timeout, Port *port)
Definition: pqcomm.c:1961
int tcp_keepalives_count
Definition: guc.c:533
#define PQ_SEND_BUFFER_SIZE
Definition: pqcomm.c:134

◆ StreamServerPort()

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

Definition at line 330 of file pqcomm.c.

References _, addrinfo::ai_family, addrinfo::ai_flags, addrinfo::ai_next, AI_PASSIVE, addrinfo::ai_socktype, Assert, bind, closesocket, CreateSocketLockFile(), 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().

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

◆ TouchSocketFiles()

void TouchSocketFiles ( void  )

Definition at line 860 of file pqcomm.c.

References lfirst.

Referenced by ServerLoop().

861 {
862  ListCell *l;
863 
864  /* Loop through all created sockets... */
865  foreach(l, sock_paths)
866  {
867  char *sock_path = (char *) lfirst(l);
868 
869  /*
870  * utime() is POSIX standard, utimes() is a common alternative. If we
871  * have neither, there's no way to affect the mod or access time of
872  * the socket :-(
873  *
874  * In either path, we ignore errors; there's no point in complaining.
875  */
876 #ifdef HAVE_UTIME
877  utime(sock_path, NULL);
878 #else /* !HAVE_UTIME */
879 #ifdef HAVE_UTIMES
880  utimes(sock_path, NULL);
881 #endif /* HAVE_UTIMES */
882 #endif /* HAVE_UTIME */
883  }
884 }
static List * sock_paths
Definition: pqcomm.c:125
#define lfirst(lc)
Definition: pg_list.h:190

Variable Documentation

◆ FeBeWaitSet

WaitEventSet* FeBeWaitSet

Definition at line 186 of file pqcomm.c.

Referenced by secure_read(), secure_write(), SwitchBackToLocalLatch(), and SwitchToSharedLatch().

◆ PqCommMethods

const PGDLLIMPORT PQcommMethods* PqCommMethods

Definition at line 184 of file pqcomm.c.

Referenced by pq_redirect_to_shm_mq(), and pq_set_parallel_master().

◆ ssl_ca_file

char* ssl_ca_file

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

Referenced by be_tls_init().

◆ ssl_cert_file

char* ssl_cert_file

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

Referenced by be_tls_init().

◆ ssl_crl_file

char* ssl_crl_file

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

Referenced by be_tls_init().

◆ ssl_library

char* ssl_library

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

◆ ssl_min_protocol_version

int ssl_min_protocol_version

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

Referenced by be_tls_init().

◆ ssl_passphrase_command

char* ssl_passphrase_command

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

Referenced by be_tls_init(), and run_ssl_passphrase_command().

◆ ssl_passphrase_command_supports_reload

bool ssl_passphrase_command_supports_reload

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

Referenced by be_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().