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

Go to the source code of this file.

Data Structures

struct  PQcommMethods
 

Macros

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

Enumerations

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

Functions

int StreamServerPort (int family, const char *hostName, unsigned short portNumber, const char *unixSocketDir, pgsocket ListenSocket[], int *NumListenSockets, 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)
 
bool pq_buffer_has_data (void)
 
int pq_putmessage_v2 (char msgtype, const char *s, size_t len)
 
bool pq_check_connection (void)
 
int secure_initialize (bool isServerStart)
 
bool secure_loaded_verify_locations (void)
 
void secure_destroy (void)
 
int secure_open_server (Port *port)
 
void secure_close (Port *port)
 
ssize_t secure_read (Port *port, void *ptr, size_t len)
 
ssize_t secure_write (Port *port, void *ptr, size_t len)
 
ssize_t secure_raw_read (Port *port, void *ptr, size_t len)
 
ssize_t secure_raw_write (Port *port, const void *ptr, size_t len)
 
int run_ssl_passphrase_command (const char *prompt, bool is_server_start, char *buf, int size)
 
bool check_ssl_key_file_permissions (const char *ssl_key_file, bool isServerStart)
 

Variables

const PGDLLIMPORT PQcommMethodsPqCommMethods
 
PGDLLIMPORT WaitEventSetFeBeWaitSet
 
PGDLLIMPORT char * ssl_library
 
PGDLLIMPORT char * ssl_cert_file
 
PGDLLIMPORT char * ssl_key_file
 
PGDLLIMPORT char * ssl_ca_file
 
PGDLLIMPORT char * ssl_crl_file
 
PGDLLIMPORT char * ssl_crl_dir
 
PGDLLIMPORT char * ssl_dh_params_file
 
PGDLLIMPORT char * ssl_passphrase_command
 
PGDLLIMPORT bool ssl_passphrase_command_supports_reload
 
PGDLLIMPORT char * SSLCipherSuites
 
PGDLLIMPORT char * SSLECDHCurve
 
PGDLLIMPORT bool SSLPreferServerCiphers
 
PGDLLIMPORT int ssl_min_protocol_version
 
PGDLLIMPORT int ssl_max_protocol_version
 

Macro Definition Documentation

◆ FeBeWaitSetLatchPos

#define FeBeWaitSetLatchPos   1

Definition at line 64 of file libpq.h.

◆ FeBeWaitSetNEvents

#define FeBeWaitSetNEvents   3

Definition at line 65 of file libpq.h.

◆ FeBeWaitSetSocketPos

#define FeBeWaitSetSocketPos   0

Definition at line 63 of file libpq.h.

◆ pq_comm_reset

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

Definition at line 45 of file libpq.h.

◆ pq_flush

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

Definition at line 46 of file libpq.h.

◆ pq_flush_if_writable

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

Definition at line 47 of file libpq.h.

◆ pq_is_send_pending

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

Definition at line 48 of file libpq.h.

◆ PQ_LARGE_MESSAGE_LIMIT

#define PQ_LARGE_MESSAGE_LIMIT   (MaxAllocSize - 1)

Definition at line 31 of file libpq.h.

◆ pq_putmessage

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

Definition at line 49 of file libpq.h.

◆ pq_putmessage_noblock

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

Definition at line 51 of file libpq.h.

◆ PQ_SMALL_MESSAGE_LIMIT

#define PQ_SMALL_MESSAGE_LIMIT   10000

Definition at line 30 of file libpq.h.

Enumeration Type Documentation

◆ ssl_protocol_versions

Enumerator
PG_TLS_ANY 
PG_TLS1_VERSION 
PG_TLS1_1_VERSION 
PG_TLS1_2_VERSION 
PG_TLS1_3_VERSION 

Definition at line 127 of file libpq.h.

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

Function Documentation

◆ check_ssl_key_file_permissions()

bool check_ssl_key_file_permissions ( const char *  ssl_key_file,
bool  isServerStart 
)

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

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

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

Referenced by be_tls_init().

◆ pq_buffer_has_data()

bool pq_buffer_has_data ( void  )

Definition at line 1143 of file pqcomm.c.

1144 {
1145  return (PqRecvPointer < PqRecvLength);
1146 }
static int PqRecvLength
Definition: pqcomm.c:129
static int PqRecvPointer
Definition: pqcomm.c:128

References PqRecvLength, and PqRecvPointer.

Referenced by ProcessStartupPacket().

◆ pq_check_connection()

bool pq_check_connection ( void  )

Definition at line 2039 of file pqcomm.c.

2040 {
2041  WaitEvent events[FeBeWaitSetNEvents];
2042  int rc;
2043 
2044  /*
2045  * It's OK to modify the socket event filter without restoring, because
2046  * all FeBeWaitSet socket wait sites do the same.
2047  */
2049 
2050 retry:
2051  rc = WaitEventSetWait(FeBeWaitSet, 0, events, lengthof(events), 0);
2052  for (int i = 0; i < rc; ++i)
2053  {
2054  if (events[i].events & WL_SOCKET_CLOSED)
2055  return false;
2056  if (events[i].events & WL_LATCH_SET)
2057  {
2058  /*
2059  * A latch event might be preventing other events from being
2060  * reported. Reset it and poll again. No need to restore it
2061  * because no code should expect latches to survive across
2062  * CHECK_FOR_INTERRUPTS().
2063  */
2065  goto retry;
2066  }
2067  }
2068 
2069  return true;
2070 }
#define lengthof(array)
Definition: c.h:777
struct Latch * MyLatch
Definition: globals.c:59
int i
Definition: isn.c:73
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:1050
int WaitEventSetWait(WaitEventSet *set, long timeout, WaitEvent *occurred_events, int nevents, uint32 wait_event_info)
Definition: latch.c:1425
void ResetLatch(Latch *latch)
Definition: latch.c:725
#define WL_SOCKET_CLOSED
Definition: latch.h:139
#define WL_LATCH_SET
Definition: latch.h:127
#define FeBeWaitSetNEvents
Definition: libpq.h:65
#define FeBeWaitSetSocketPos
Definition: libpq.h:63
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:164

References FeBeWaitSet, FeBeWaitSetNEvents, FeBeWaitSetSocketPos, i, lengthof, ModifyWaitEvent(), MyLatch, ResetLatch(), WaitEventSetWait(), WL_LATCH_SET, and WL_SOCKET_CLOSED.

Referenced by ProcessInterrupts().

◆ pq_endmsgread()

void pq_endmsgread ( void  )

Definition at line 1180 of file pqcomm.c.

1181 {
1183 
1184  PqCommReadingMsg = false;
1185 }
Assert(fmt[strlen(fmt) - 1] !='\n')
static bool PqCommReadingMsg
Definition: pqcomm.c:135

References Assert(), and PqCommReadingMsg.

Referenced by ProcessRepliesIfAny(), and ProcessStartupPacket().

◆ pq_getbyte()

int pq_getbyte ( void  )

Definition at line 981 of file pqcomm.c.

982 {
984 
985  while (PqRecvPointer >= PqRecvLength)
986  {
987  if (pq_recvbuf()) /* If nothing in buffer, then recv some */
988  return EOF; /* Failed to recv data */
989  }
990  return (unsigned char) PqRecvBuffer[PqRecvPointer++];
991 }
static int pq_recvbuf(void)
Definition: pqcomm.c:915
static char PqRecvBuffer[PQ_RECV_BUFFER_SIZE]
Definition: pqcomm.c:127

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

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

◆ pq_getbyte_if_available()

int pq_getbyte_if_available ( unsigned char *  c)

Definition at line 1021 of file pqcomm.c.

1022 {
1023  int r;
1024 
1026 
1028  {
1030  return 1;
1031  }
1032 
1033  /* Put the socket into non-blocking mode */
1034  socket_set_nonblocking(true);
1035 
1036  errno = 0;
1037 
1038  r = secure_read(MyProcPort, c, 1);
1039  if (r < 0)
1040  {
1041  /*
1042  * Ok if no data available without blocking or interrupted (though
1043  * EINTR really shouldn't happen with a non-blocking socket). Report
1044  * other errors.
1045  */
1046  if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
1047  r = 0;
1048  else
1049  {
1050  /*
1051  * Careful: an ereport() that tries to write to the client would
1052  * cause recursion to here, leading to stack overflow and core
1053  * dump! This message must go *only* to the postmaster log.
1054  *
1055  * If errno is zero, assume it's EOF and let the caller complain.
1056  */
1057  if (errno != 0)
1060  errmsg("could not receive data from client: %m")));
1061  r = EOF;
1062  }
1063  }
1064  else if (r == 0)
1065  {
1066  /* EOF detected */
1067  r = EOF;
1068  }
1069 
1070  return r;
1071 }
ssize_t secure_read(Port *port, void *ptr, size_t len)
Definition: be-secure.c:145
int errcode_for_socket_access(void)
Definition: elog.c:958
#define COMMERROR
Definition: elog.h:33
struct Port * MyProcPort
Definition: globals.c:48
static void socket_set_nonblocking(bool nonblocking)
Definition: pqcomm.c:898
char * c
#define EINTR
Definition: win32_port.h:374
#define EWOULDBLOCK
Definition: win32_port.h:380
#define EAGAIN
Definition: win32_port.h:372

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

Referenced by ProcessRepliesIfAny().

◆ pq_getbytes()

int pq_getbytes ( char *  s,
size_t  len 
)

Definition at line 1080 of file pqcomm.c.

1081 {
1082  size_t amount;
1083 
1085 
1086  while (len > 0)
1087  {
1088  while (PqRecvPointer >= PqRecvLength)
1089  {
1090  if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1091  return EOF; /* Failed to recv data */
1092  }
1093  amount = PqRecvLength - PqRecvPointer;
1094  if (amount > len)
1095  amount = len;
1096  memcpy(s, PqRecvBuffer + PqRecvPointer, amount);
1097  PqRecvPointer += amount;
1098  s += amount;
1099  len -= amount;
1100  }
1101  return 0;
1102 }
const void size_t len

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

Referenced by pq_getmessage(), and ProcessStartupPacket().

◆ pq_getmessage()

int pq_getmessage ( StringInfo  s,
int  maxlen 
)

Definition at line 1218 of file pqcomm.c.

1219 {
1220  int32 len;
1221 
1223 
1224  resetStringInfo(s);
1225 
1226  /* Read message length word */
1227  if (pq_getbytes((char *) &len, 4) == EOF)
1228  {
1230  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1231  errmsg("unexpected EOF within message length word")));
1232  return EOF;
1233  }
1234 
1235  len = pg_ntoh32(len);
1236 
1237  if (len < 4 || len > maxlen)
1238  {
1240  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1241  errmsg("invalid message length")));
1242  return EOF;
1243  }
1244 
1245  len -= 4; /* discount length itself */
1246 
1247  if (len > 0)
1248  {
1249  /*
1250  * Allocate space for message. If we run out of room (ridiculously
1251  * large message), we will elog(ERROR), but we want to discard the
1252  * message body so as not to lose communication sync.
1253  */
1254  PG_TRY();
1255  {
1256  enlargeStringInfo(s, len);
1257  }
1258  PG_CATCH();
1259  {
1260  if (pq_discardbytes(len) == EOF)
1262  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1263  errmsg("incomplete message from client")));
1264 
1265  /* we discarded the rest of the message so we're back in sync. */
1266  PqCommReadingMsg = false;
1267  PG_RE_THROW();
1268  }
1269  PG_END_TRY();
1270 
1271  /* And grab the message */
1272  if (pq_getbytes(s->data, len) == EOF)
1273  {
1275  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1276  errmsg("incomplete message from client")));
1277  return EOF;
1278  }
1279  s->len = len;
1280  /* Place a trailing null per StringInfo convention */
1281  s->data[len] = '\0';
1282  }
1283 
1284  /* finished reading the message. */
1285  PqCommReadingMsg = false;
1286 
1287  return 0;
1288 }
signed int int32
Definition: c.h:483
#define PG_RE_THROW()
Definition: elog.h:411
#define PG_TRY(...)
Definition: elog.h:370
#define PG_END_TRY(...)
Definition: elog.h:395
#define PG_CATCH(...)
Definition: elog.h:380
#define pg_ntoh32(x)
Definition: pg_bswap.h:125
static int pq_discardbytes(size_t len)
Definition: pqcomm.c:1114
int pq_getbytes(char *s, size_t len)
Definition: pqcomm.c:1080
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:78
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:289

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

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

◆ pq_init()

void pq_init ( void  )

Definition at line 172 of file pqcomm.c.

173 {
174  int socket_pos PG_USED_FOR_ASSERTS_ONLY;
175  int latch_pos PG_USED_FOR_ASSERTS_ONLY;
176 
177  /* initialize state variables */
181  PqCommBusy = false;
182  PqCommReadingMsg = false;
183 
184  /* set up process-exit hook to close the socket */
186 
187  /*
188  * In backends (as soon as forked) we operate the underlying socket in
189  * nonblocking mode and use latches to implement blocking semantics if
190  * needed. That allows us to provide safely interruptible reads and
191  * writes.
192  *
193  * Use COMMERROR on failure, because ERROR would try to send the error to
194  * the client, which might require changing the mode again, leading to
195  * infinite recursion.
196  */
197 #ifndef WIN32
200  (errmsg("could not set socket to nonblocking mode: %m")));
201 #endif
202 
203 #ifndef WIN32
204 
205  /* Don't give the socket to any subprograms we execute. */
206  if (fcntl(MyProcPort->sock, F_SETFD, FD_CLOEXEC) < 0)
207  elog(FATAL, "fcntl(F_SETFD) failed on socket: %m");
208 #endif
209 
212  MyProcPort->sock, NULL, NULL);
214  MyLatch, NULL);
216  NULL, NULL);
217 
218  /*
219  * The event positions match the order we added them, but let's sanity
220  * check them to be sure.
221  */
222  Assert(socket_pos == FeBeWaitSetSocketPos);
223  Assert(latch_pos == FeBeWaitSetLatchPos);
224 }
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:171
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:309
WaitEventSet * CreateWaitEventSet(ResourceOwner resowner, int nevents)
Definition: latch.c:752
int AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch, void *user_data)
Definition: latch.c:964
#define WL_POSTMASTER_DEATH
Definition: latch.h:131
#define WL_SOCKET_WRITEABLE
Definition: latch.h:129
#define FeBeWaitSetLatchPos
Definition: libpq.h:64
MemoryContext TopMemoryContext
Definition: mcxt.c:141
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1034
bool pg_set_noblock(pgsocket sock)
Definition: noblock.c:25
#define PGINVALID_SOCKET
Definition: port.h:31
static int PqSendStart
Definition: pqcomm.c:125
static int PqSendPointer
Definition: pqcomm.c:124
#define PQ_SEND_BUFFER_SIZE
Definition: pqcomm.c:119
static char * PqSendBuffer
Definition: pqcomm.c:122
static bool PqCommBusy
Definition: pqcomm.c:134
static void socket_close(int code, Datum arg)
Definition: pqcomm.c:250
static int PqSendBufferSize
Definition: pqcomm.c:123
pgsocket sock
Definition: libpq-be.h:148

References AddWaitEventToSet(), Assert(), COMMERROR, CreateWaitEventSet(), elog(), ereport, errmsg(), FATAL, FeBeWaitSet, FeBeWaitSetLatchPos, FeBeWaitSetNEvents, 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().

◆ pq_is_reading_msg()

bool pq_is_reading_msg ( void  )

Definition at line 1196 of file pqcomm.c.

1197 {
1198  return PqCommReadingMsg;
1199 }

References PqCommReadingMsg.

Referenced by PostgresMain().

◆ pq_peekbyte()

int pq_peekbyte ( void  )

Definition at line 1000 of file pqcomm.c.

1001 {
1003 
1004  while (PqRecvPointer >= PqRecvLength)
1005  {
1006  if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1007  return EOF; /* Failed to recv data */
1008  }
1009  return (unsigned char) PqRecvBuffer[PqRecvPointer];
1010 }

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

◆ pq_putmessage_v2()

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

Definition at line 1544 of file pqcomm.c.

1545 {
1546  Assert(msgtype != 0);
1547 
1548  if (PqCommBusy)
1549  return 0;
1550  PqCommBusy = true;
1551  if (internal_putbytes(&msgtype, 1))
1552  goto fail;
1553 
1554  if (internal_putbytes(s, len))
1555  goto fail;
1556  PqCommBusy = false;
1557  return 0;
1558 
1559 fail:
1560  PqCommBusy = false;
1561  return EOF;
1562 }
static int internal_putbytes(const char *s, size_t len)
Definition: pqcomm.c:1292

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

Referenced by send_message_to_frontend().

◆ pq_startmsgread()

void pq_startmsgread ( void  )

Definition at line 1156 of file pqcomm.c.

1157 {
1158  /*
1159  * There shouldn't be a read active already, but let's check just to be
1160  * sure.
1161  */
1162  if (PqCommReadingMsg)
1163  ereport(FATAL,
1164  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1165  errmsg("terminating connection because protocol synchronization was lost")));
1166 
1167  PqCommReadingMsg = true;
1168 }

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

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

◆ RemoveSocketFiles()

void RemoveSocketFiles ( void  )

Definition at line 865 of file pqcomm.c.

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 any error. */
875  (void) unlink(sock_path);
876  }
877  /* Since we're about to exit, no need to reclaim storage */
878  sock_paths = NIL;
879 }
#define lfirst(lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:68
static List * sock_paths
Definition: pqcomm.c:110

References lfirst, NIL, and sock_paths.

Referenced by CloseServerPorts().

◆ run_ssl_passphrase_command()

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

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

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

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

Referenced by ssl_external_passwd_cb().

◆ secure_close()

void secure_close ( Port port)

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

134 {
135 #ifdef USE_SSL
136  if (port->ssl_in_use)
138 #endif
139 }
void be_tls_close(Port *port)
static int port
Definition: pg_regress.c:116

References be_tls_close(), and port.

Referenced by socket_close().

◆ secure_destroy()

void secure_destroy ( void  )

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

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

References be_tls_destroy().

Referenced by process_pm_reload_request().

◆ secure_initialize()

int secure_initialize ( bool  isServerStart)

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

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

References be_tls_init().

Referenced by PostmasterMain(), and process_pm_reload_request().

◆ secure_loaded_verify_locations()

bool secure_loaded_verify_locations ( void  )

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

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

Referenced by ClientAuthentication().

◆ secure_open_server()

int secure_open_server ( Port port)

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

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

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

Referenced by ProcessStartupPacket().

◆ secure_raw_read()

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

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

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

References len, pgwin32_noblock, port, and recv.

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

◆ secure_raw_write()

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

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

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

References len, pgwin32_noblock, port, and send.

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

◆ secure_read()

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

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

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

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

Referenced by pq_getbyte_if_available(), and pq_recvbuf().

◆ secure_write()

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

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

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

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

Referenced by internal_flush().

◆ StreamClose()

void StreamClose ( pgsocket  sock)

Definition at line 831 of file pqcomm.c.

832 {
833  if (closesocket(sock) != 0)
834  elog(LOG, "could not close client or listen socket: %m");
835 }
#define closesocket
Definition: port.h:349

References closesocket, elog(), and LOG.

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

◆ StreamConnection()

int StreamConnection ( pgsocket  server_fd,
Port port 
)

Definition at line 697 of file pqcomm.c.

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

References accept, ereport, errcode_for_socket_access(), errmsg(), LOG, pg_usleep(), PGINVALID_SOCKET, port, PQ_SEND_BUFFER_SIZE, pq_setkeepalivescount(), pq_setkeepalivesidle(), pq_setkeepalivesinterval(), pq_settcpusertimeout(), STATUS_ERROR, STATUS_OK, tcp_keepalives_count, tcp_keepalives_idle, tcp_keepalives_interval, and tcp_user_timeout.

Referenced by ConnCreate().

◆ StreamServerPort()

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

Definition at line 322 of file pqcomm.c.

325 {
326  pgsocket fd;
327  int err;
328  int maxconn;
329  int ret;
330  char portNumberStr[32];
331  const char *familyDesc;
332  char familyDescBuf[64];
333  const char *addrDesc;
334  char addrBuf[NI_MAXHOST];
335  char *service;
336  struct addrinfo *addrs = NULL,
337  *addr;
338  struct addrinfo hint;
339  int added = 0;
340  char unixSocketPath[MAXPGPATH];
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  if (family == AF_UNIX)
352  {
353  /*
354  * Create unixSocketPath from portNumber and unixSocketDir and lock
355  * that file path
356  */
357  UNIXSOCK_PATH(unixSocketPath, portNumber, unixSocketDir);
358  if (strlen(unixSocketPath) >= UNIXSOCK_PATH_BUFLEN)
359  {
360  ereport(LOG,
361  (errmsg("Unix-domain socket path \"%s\" is too long (maximum %d bytes)",
362  unixSocketPath,
363  (int) (UNIXSOCK_PATH_BUFLEN - 1))));
364  return STATUS_ERROR;
365  }
366  if (Lock_AF_UNIX(unixSocketDir, unixSocketPath) != STATUS_OK)
367  return STATUS_ERROR;
368  service = unixSocketPath;
369  }
370  else
371  {
372  snprintf(portNumberStr, sizeof(portNumberStr), "%d", portNumber);
373  service = portNumberStr;
374  }
375 
376  ret = pg_getaddrinfo_all(hostName, service, &hint, &addrs);
377  if (ret || !addrs)
378  {
379  if (hostName)
380  ereport(LOG,
381  (errmsg("could not translate host name \"%s\", service \"%s\" to address: %s",
382  hostName, service, gai_strerror(ret))));
383  else
384  ereport(LOG,
385  (errmsg("could not translate service \"%s\" to address: %s",
386  service, gai_strerror(ret))));
387  if (addrs)
388  pg_freeaddrinfo_all(hint.ai_family, addrs);
389  return STATUS_ERROR;
390  }
391 
392  for (addr = addrs; addr; addr = addr->ai_next)
393  {
394  if (family != AF_UNIX && addr->ai_family == AF_UNIX)
395  {
396  /*
397  * Only set up a unix domain socket when they really asked for it.
398  * The service/port is different in that case.
399  */
400  continue;
401  }
402 
403  /* See if there is still room to add 1 more socket. */
404  if (*NumListenSockets == MaxListen)
405  {
406  ereport(LOG,
407  (errmsg("could not bind to all requested addresses: MAXLISTEN (%d) exceeded",
408  MaxListen)));
409  break;
410  }
411 
412  /* set up address family name for log messages */
413  switch (addr->ai_family)
414  {
415  case AF_INET:
416  familyDesc = _("IPv4");
417  break;
418  case AF_INET6:
419  familyDesc = _("IPv6");
420  break;
421  case AF_UNIX:
422  familyDesc = _("Unix");
423  break;
424  default:
425  snprintf(familyDescBuf, sizeof(familyDescBuf),
426  _("unrecognized address family %d"),
427  addr->ai_family);
428  familyDesc = familyDescBuf;
429  break;
430  }
431 
432  /* set up text form of address for log messages */
433  if (addr->ai_family == AF_UNIX)
434  addrDesc = unixSocketPath;
435  else
436  {
437  pg_getnameinfo_all((const struct sockaddr_storage *) addr->ai_addr,
438  addr->ai_addrlen,
439  addrBuf, sizeof(addrBuf),
440  NULL, 0,
441  NI_NUMERICHOST);
442  addrDesc = addrBuf;
443  }
444 
445  if ((fd = socket(addr->ai_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
446  {
447  ereport(LOG,
449  /* translator: first %s is IPv4, IPv6, or Unix */
450  errmsg("could not create %s socket for address \"%s\": %m",
451  familyDesc, addrDesc)));
452  continue;
453  }
454 
455 #ifndef WIN32
456  /* Don't give the listen socket to any subprograms we execute. */
457  if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0)
458  elog(FATAL, "fcntl(F_SETFD) failed on socket: %m");
459 
460  /*
461  * Without the SO_REUSEADDR flag, a new postmaster can't be started
462  * right away after a stop or crash, giving "address already in use"
463  * error on TCP ports.
464  *
465  * On win32, however, this behavior only happens if the
466  * SO_EXCLUSIVEADDRUSE is set. With SO_REUSEADDR, win32 allows
467  * multiple servers to listen on the same address, resulting in
468  * unpredictable behavior. With no flags at all, win32 behaves as Unix
469  * with SO_REUSEADDR.
470  */
471  if (addr->ai_family != AF_UNIX)
472  {
473  if ((setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
474  (char *) &one, sizeof(one))) == -1)
475  {
476  ereport(LOG,
478  /* translator: third %s is IPv4, IPv6, or Unix */
479  errmsg("%s(%s) failed for %s address \"%s\": %m",
480  "setsockopt", "SO_REUSEADDR",
481  familyDesc, addrDesc)));
482  closesocket(fd);
483  continue;
484  }
485  }
486 #endif
487 
488 #ifdef IPV6_V6ONLY
489  if (addr->ai_family == AF_INET6)
490  {
491  if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY,
492  (char *) &one, sizeof(one)) == -1)
493  {
494  ereport(LOG,
496  /* translator: third %s is IPv4, IPv6, or Unix */
497  errmsg("%s(%s) failed for %s address \"%s\": %m",
498  "setsockopt", "IPV6_V6ONLY",
499  familyDesc, addrDesc)));
500  closesocket(fd);
501  continue;
502  }
503  }
504 #endif
505 
506  /*
507  * Note: This might fail on some OS's, like Linux older than
508  * 2.4.21-pre3, that don't have the IPV6_V6ONLY socket option, and map
509  * ipv4 addresses to ipv6. It will show ::ffff:ipv4 for all ipv4
510  * connections.
511  */
512  err = bind(fd, addr->ai_addr, addr->ai_addrlen);
513  if (err < 0)
514  {
515  int saved_errno = errno;
516 
517  ereport(LOG,
519  /* translator: first %s is IPv4, IPv6, or Unix */
520  errmsg("could not bind %s address \"%s\": %m",
521  familyDesc, addrDesc),
522  saved_errno == EADDRINUSE ?
523  (addr->ai_family == AF_UNIX ?
524  errhint("Is another postmaster already running on port %d?",
525  (int) portNumber) :
526  errhint("Is another postmaster already running on port %d?"
527  " If not, wait a few seconds and retry.",
528  (int) portNumber)) : 0));
529  closesocket(fd);
530  continue;
531  }
532 
533  if (addr->ai_family == AF_UNIX)
534  {
535  if (Setup_AF_UNIX(service) != STATUS_OK)
536  {
537  closesocket(fd);
538  break;
539  }
540  }
541 
542  /*
543  * Select appropriate accept-queue length limit. It seems reasonable
544  * to use a value similar to the maximum number of child processes
545  * that the postmaster will permit.
546  */
547  maxconn = MaxConnections * 2;
548 
549  err = listen(fd, maxconn);
550  if (err < 0)
551  {
552  ereport(LOG,
554  /* translator: first %s is IPv4, IPv6, or Unix */
555  errmsg("could not listen on %s address \"%s\": %m",
556  familyDesc, addrDesc)));
557  closesocket(fd);
558  continue;
559  }
560 
561  if (addr->ai_family == AF_UNIX)
562  ereport(LOG,
563  (errmsg("listening on Unix socket \"%s\"",
564  addrDesc)));
565  else
566  ereport(LOG,
567  /* translator: first %s is IPv4 or IPv6 */
568  (errmsg("listening on %s address \"%s\", port %d",
569  familyDesc, addrDesc, (int) portNumber)));
570 
572  (*NumListenSockets)++;
573  added++;
574  }
575 
576  pg_freeaddrinfo_all(hint.ai_family, addrs);
577 
578  if (!added)
579  return STATUS_ERROR;
580 
581  return STATUS_OK;
582 }
#define MemSet(start, val, len)
Definition: c.h:1009
int errhint(const char *fmt,...)
Definition: elog.c:1322
#define _(x)
Definition: elog.c:91
void err(int eval, const char *fmt,...)
Definition: err.c:43
int MaxConnections
Definition: globals.c:140
void pg_freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai)
Definition: ip.c:82
int pg_getnameinfo_all(const struct sockaddr_storage *addr, int salen, char *node, int nodelen, char *service, int servicelen, int flags)
Definition: ip.c:114
int pg_getaddrinfo_all(const char *hostname, const char *servname, const struct addrinfo *hintp, struct addrinfo **result)
Definition: ip.c:53
#define MAXPGPATH
int pgsocket
Definition: port.h:29
#define snprintf
Definition: port.h:238
static pgsocket * ListenSockets
Definition: postmaster.c:231
static int NumListenSockets
Definition: postmaster.c:230
static int Lock_AF_UNIX(const char *unixSocketDir, const char *unixSocketPath)
Definition: pqcomm.c:589
static int Setup_AF_UNIX(const char *sock_path)
Definition: pqcomm.c:624
#define UNIXSOCK_PATH(path, port, sockdir)
Definition: pqcomm.h:44
#define UNIXSOCK_PATH_BUFLEN
Definition: pqcomm.h:60
static int fd(const char *x, int i)
Definition: preproc-init.c:105
const char * gai_strerror(int ecode)
#define bind(s, addr, addrlen)
Definition: win32_port.h:491
#define EADDRINUSE
Definition: win32_port.h:400
#define socket(af, type, protocol)
Definition: win32_port.h:490
#define listen(s, backlog)
Definition: win32_port.h:492

References _, bind, closesocket, EADDRINUSE, elog(), ereport, err(), errcode_for_socket_access(), errhint(), errmsg(), FATAL, fd(), gai_strerror(), listen, ListenSockets, Lock_AF_UNIX(), LOG, MaxConnections, MAXPGPATH, MemSet, NumListenSockets, pg_freeaddrinfo_all(), pg_getaddrinfo_all(), pg_getnameinfo_all(), PGINVALID_SOCKET, Setup_AF_UNIX(), snprintf, socket, STATUS_ERROR, STATUS_OK, UNIXSOCK_PATH, and UNIXSOCK_PATH_BUFLEN.

Referenced by PostmasterMain().

◆ TouchSocketFiles()

void TouchSocketFiles ( void  )

Definition at line 847 of file pqcomm.c.

848 {
849  ListCell *l;
850 
851  /* Loop through all created sockets... */
852  foreach(l, sock_paths)
853  {
854  char *sock_path = (char *) lfirst(l);
855 
856  /* Ignore errors; there's no point in complaining */
857  (void) utime(sock_path, NULL);
858  }
859 }

References lfirst, and sock_paths.

Referenced by ServerLoop().

Variable Documentation

◆ FeBeWaitSet

◆ PqCommMethods

const PGDLLIMPORT PQcommMethods* PqCommMethods
extern

Definition at line 162 of file pqcomm.c.

Referenced by pq_redirect_to_shm_mq(), and pq_set_parallel_leader().

◆ ssl_ca_file

PGDLLIMPORT char* ssl_ca_file
extern

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

Referenced by be_tls_init().

◆ ssl_cert_file

PGDLLIMPORT char* ssl_cert_file
extern

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

Referenced by be_tls_init().

◆ ssl_crl_dir

PGDLLIMPORT char* ssl_crl_dir
extern

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

Referenced by be_tls_init().

◆ ssl_crl_file

PGDLLIMPORT char* ssl_crl_file
extern

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

Referenced by be_tls_init().

◆ ssl_dh_params_file

PGDLLIMPORT char* ssl_dh_params_file
extern

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

Referenced by initialize_dh().

◆ ssl_key_file

PGDLLIMPORT char* ssl_key_file
extern

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

Referenced by be_tls_init(), and check_ssl_key_file_permissions().

◆ ssl_library

PGDLLIMPORT char* ssl_library
extern

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

◆ ssl_max_protocol_version

PGDLLIMPORT int ssl_max_protocol_version
extern

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

Referenced by be_tls_init(), and be_tls_open_server().

◆ ssl_min_protocol_version

PGDLLIMPORT int ssl_min_protocol_version
extern

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

Referenced by be_tls_init(), and be_tls_open_server().

◆ ssl_passphrase_command

PGDLLIMPORT char* ssl_passphrase_command
extern

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

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

◆ ssl_passphrase_command_supports_reload

PGDLLIMPORT bool ssl_passphrase_command_supports_reload
extern

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

Referenced by default_openssl_tls_init().

◆ SSLCipherSuites

PGDLLIMPORT char* SSLCipherSuites
extern

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

Referenced by be_tls_init().

◆ SSLECDHCurve

PGDLLIMPORT char* SSLECDHCurve
extern

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

Referenced by initialize_ecdh().

◆ SSLPreferServerCiphers

PGDLLIMPORT bool SSLPreferServerCiphers
extern

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

Referenced by be_tls_init().