PostgreSQL Source Code  git master
libpq-int.h File Reference
#include "libpq-events.h"
#include <netdb.h>
#include <sys/socket.h>
#include <time.h>
#include "libpq/pqcomm.h"
#include "fe-auth-sasl.h"
#include "pqexpbuffer.h"
Include dependency graph for libpq-int.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

union  pgresult_data
 
struct  pgresParamDesc
 
struct  pgresAttValue
 
struct  pgMessageField
 
struct  PGNoticeHooks
 
struct  PGEvent
 
struct  pg_result
 
struct  PQEnvironmentOption
 
struct  pgParameterStatus
 
struct  pgLobjfuncs
 
struct  pgDataValue
 
struct  PGcmdQueueEntry
 
struct  pg_conn_host
 
struct  pg_conn
 
struct  pg_cancel
 

Macros

#define CMDSTATUS_LEN   64 /* should match COMPLETION_TAG_BUFSIZE */
 
#define NULL_LEN   (-1) /* pg_result len for NULL value */
 
#define pglock_thread()   ((void) 0)
 
#define pgunlock_thread()   ((void) 0)
 
#define pqClearConnErrorState(conn)
 
#define pgHavePendingResult(conn)    ((conn)->result != NULL || (conn)->error_result)
 
#define pqIsnonblocking(conn)   ((conn)->nonblocking)
 
#define OUTBUFFER_THRESHOLD   65536
 
#define libpq_gettext(x)   (x)
 
#define libpq_ngettext(s, p, n)   ((n) == 1 ? (s) : (p))
 
#define SOCK_ERRNO   errno
 
#define SOCK_STRERROR   strerror_r
 
#define SOCK_ERRNO_SET(e)   (errno = (e))
 

Typedefs

typedef union pgresult_data PGresult_data
 
typedef struct pgresParamDesc PGresParamDesc
 
typedef struct pgresAttValue PGresAttValue
 
typedef struct pgMessageField PGMessageField
 
typedef struct PGEvent PGEvent
 
typedef struct PQEnvironmentOption PQEnvironmentOption
 
typedef struct pgParameterStatus pgParameterStatus
 
typedef struct pgLobjfuncs PGlobjfuncs
 
typedef struct pgDataValue PGdataValue
 
typedef enum pg_conn_host_type pg_conn_host_type
 
typedef struct PGcmdQueueEntry PGcmdQueueEntry
 
typedef struct pg_conn_host pg_conn_host
 

Enumerations

enum  PGAsyncStatusType {
  PGASYNC_IDLE , PGASYNC_BUSY , PGASYNC_READY , PGASYNC_READY_MORE ,
  PGASYNC_COPY_IN , PGASYNC_COPY_OUT , PGASYNC_COPY_BOTH , PGASYNC_PIPELINE_IDLE
}
 
enum  PGTargetServerType {
  SERVER_TYPE_ANY = 0 , SERVER_TYPE_READ_WRITE , SERVER_TYPE_READ_ONLY , SERVER_TYPE_PRIMARY ,
  SERVER_TYPE_STANDBY , SERVER_TYPE_PREFER_STANDBY , SERVER_TYPE_PREFER_STANDBY_PASS2
}
 
enum  PGTernaryBool { PG_BOOL_UNKNOWN = 0 , PG_BOOL_YES , PG_BOOL_NO }
 
enum  pg_conn_host_type { CHT_HOST_NAME , CHT_HOST_ADDRESS , CHT_UNIX_SOCKET }
 
enum  PGQueryClass {
  PGQUERY_SIMPLE , PGQUERY_EXTENDED , PGQUERY_PREPARE , PGQUERY_DESCRIBE ,
  PGQUERY_SYNC , PGQUERY_CLOSE
}
 

Functions

void pqDropConnection (PGconn *conn, bool flushInput)
 
int pqPacketSend (PGconn *conn, char pack_type, const void *buf, size_t buf_len)
 
bool pqGetHomeDirectory (char *buf, int bufsize)
 
void pqSetResultError (PGresult *res, PQExpBuffer errorMessage, int offset)
 
void * pqResultAlloc (PGresult *res, size_t nBytes, bool isBinary)
 
char * pqResultStrdup (PGresult *res, const char *str)
 
void pqClearAsyncResult (PGconn *conn)
 
void pqSaveErrorResult (PGconn *conn)
 
PGresultpqPrepareAsyncResult (PGconn *conn)
 
void pqInternalNotice (const PGNoticeHooks *hooks, const char *fmt,...) pg_attribute_printf(2
 
void void pqSaveMessageField (PGresult *res, char code, const char *value)
 
void pqSaveParameterStatus (PGconn *conn, const char *name, const char *value)
 
int pqRowProcessor (PGconn *conn, const char **errmsgp)
 
void pqCommandQueueAdvance (PGconn *conn)
 
int PQsendQueryContinue (PGconn *conn, const char *query)
 
char * pqBuildStartupPacket3 (PGconn *conn, int *packetlen, const PQEnvironmentOption *options)
 
void pqParseInput3 (PGconn *conn)
 
int pqGetErrorNotice3 (PGconn *conn, bool isError)
 
void pqBuildErrorMessage3 (PQExpBuffer msg, const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
 
int pqGetNegotiateProtocolVersion3 (PGconn *conn)
 
int pqGetCopyData3 (PGconn *conn, char **buffer, int async)
 
int pqGetline3 (PGconn *conn, char *s, int maxlen)
 
int pqGetlineAsync3 (PGconn *conn, char *buffer, int bufsize)
 
int pqEndcopy3 (PGconn *conn)
 
PGresultpqFunctionCall3 (PGconn *conn, Oid fnid, int *result_buf, int *actual_result_len, int result_is_int, const PQArgBlock *args, int nargs)
 
int pqCheckOutBufferSpace (size_t bytes_needed, PGconn *conn)
 
int pqCheckInBufferSpace (size_t bytes_needed, PGconn *conn)
 
int pqGetc (char *result, PGconn *conn)
 
int pqPutc (char c, PGconn *conn)
 
int pqGets (PQExpBuffer buf, PGconn *conn)
 
int pqGets_append (PQExpBuffer buf, PGconn *conn)
 
int pqPuts (const char *s, PGconn *conn)
 
int pqGetnchar (char *s, size_t len, PGconn *conn)
 
int pqSkipnchar (size_t len, PGconn *conn)
 
int pqPutnchar (const char *s, size_t len, PGconn *conn)
 
int pqGetInt (int *result, size_t bytes, PGconn *conn)
 
int pqPutInt (int value, size_t bytes, PGconn *conn)
 
int pqPutMsgStart (char msg_type, PGconn *conn)
 
int pqPutMsgEnd (PGconn *conn)
 
int pqReadData (PGconn *conn)
 
int pqFlush (PGconn *conn)
 
int pqWait (int forRead, int forWrite, PGconn *conn)
 
int pqWaitTimed (int forRead, int forWrite, PGconn *conn, time_t finish_time)
 
int pqReadReady (PGconn *conn)
 
int pqWriteReady (PGconn *conn)
 
int pqsecure_initialize (PGconn *, bool, bool)
 
PostgresPollingStatusType pqsecure_open_client (PGconn *)
 
void pqsecure_close (PGconn *)
 
ssize_t pqsecure_read (PGconn *, void *ptr, size_t len)
 
ssize_t pqsecure_write (PGconn *, const void *ptr, size_t len)
 
ssize_t pqsecure_raw_read (PGconn *, void *ptr, size_t len)
 
ssize_t pqsecure_raw_write (PGconn *, const void *ptr, size_t len)
 
void pgtls_init_library (bool do_ssl, int do_crypto)
 
int pgtls_init (PGconn *conn, bool do_ssl, bool do_crypto)
 
PostgresPollingStatusType pgtls_open_client (PGconn *conn)
 
void pgtls_close (PGconn *conn)
 
ssize_t pgtls_read (PGconn *conn, void *ptr, size_t len)
 
bool pgtls_read_pending (PGconn *conn)
 
ssize_t pgtls_write (PGconn *conn, const void *ptr, size_t len)
 
int pgtls_verify_peer_name_matches_certificate_guts (PGconn *conn, int *names_examined, char **first_name)
 
void pqTraceOutputMessage (PGconn *conn, const char *message, bool toServer)
 
void pqTraceOutputNoTypeByteMessage (PGconn *conn, const char *message)
 
void libpq_append_error (PQExpBuffer errorMessage, const char *fmt,...) pg_attribute_printf(2
 
void void libpq_append_conn_error (PGconn *conn, const char *fmt,...) pg_attribute_printf(2
 

Variables

char *const pgresStatus []
 

Macro Definition Documentation

◆ CMDSTATUS_LEN

#define CMDSTATUS_LEN   64 /* should match COMPLETION_TAG_BUFSIZE */

Definition at line 88 of file libpq-int.h.

◆ libpq_gettext

#define libpq_gettext (   x)    (x)

Definition at line 895 of file libpq-int.h.

◆ libpq_ngettext

#define libpq_ngettext (   s,
  p,
 
)    ((n) == 1 ? (s) : (p))

Definition at line 896 of file libpq-int.h.

◆ NULL_LEN

#define NULL_LEN   (-1) /* pg_result len for NULL value */

Definition at line 135 of file libpq-int.h.

◆ OUTBUFFER_THRESHOLD

#define OUTBUFFER_THRESHOLD   65536

Definition at line 889 of file libpq-int.h.

◆ pgHavePendingResult

#define pgHavePendingResult (   conn)     ((conn)->result != NULL || (conn)->error_result)

Definition at line 877 of file libpq-int.h.

◆ pglock_thread

#define pglock_thread ( )    ((void) 0)

Definition at line 672 of file libpq-int.h.

◆ pgunlock_thread

#define pgunlock_thread ( )    ((void) 0)

Definition at line 673 of file libpq-int.h.

◆ pqClearConnErrorState

#define pqClearConnErrorState (   conn)
Value:
(resetPQExpBuffer(&(conn)->errorMessage), \
(conn)->errorReported = 0)
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:146
PGconn * conn
Definition: streamutil.c:54

Definition at line 868 of file libpq-int.h.

◆ pqIsnonblocking

#define pqIsnonblocking (   conn)    ((conn)->nonblocking)

Definition at line 884 of file libpq-int.h.

◆ SOCK_ERRNO

#define SOCK_ERRNO   errno

Definition at line 916 of file libpq-int.h.

◆ SOCK_ERRNO_SET

#define SOCK_ERRNO_SET (   e)    (errno = (e))

Definition at line 918 of file libpq-int.h.

◆ SOCK_STRERROR

#define SOCK_STRERROR   strerror_r

Definition at line 917 of file libpq-int.h.

Typedef Documentation

◆ pg_conn_host

typedef struct pg_conn_host pg_conn_host

◆ pg_conn_host_type

◆ PGcmdQueueEntry

◆ PGdataValue

typedef struct pgDataValue PGdataValue

◆ PGEvent

typedef struct PGEvent PGEvent

◆ PGlobjfuncs

typedef struct pgLobjfuncs PGlobjfuncs

◆ PGMessageField

◆ pgParameterStatus

◆ PGresAttValue

typedef struct pgresAttValue PGresAttValue

◆ PGresParamDesc

◆ PGresult_data

Definition at line 1 of file libpq-int.h.

◆ PQEnvironmentOption

Enumeration Type Documentation

◆ pg_conn_host_type

Enumerator
CHT_HOST_NAME 
CHT_HOST_ADDRESS 
CHT_UNIX_SOCKET 

Definition at line 299 of file libpq-int.h.

300 {
pg_conn_host_type
Definition: libpq-int.h:300
@ CHT_UNIX_SOCKET
Definition: libpq-int.h:303
@ CHT_HOST_ADDRESS
Definition: libpq-int.h:302
@ CHT_HOST_NAME
Definition: libpq-int.h:301

◆ PGAsyncStatusType

Enumerator
PGASYNC_IDLE 
PGASYNC_BUSY 
PGASYNC_READY 
PGASYNC_READY_MORE 
PGASYNC_COPY_IN 
PGASYNC_COPY_OUT 
PGASYNC_COPY_BOTH 
PGASYNC_PIPELINE_IDLE 

Definition at line 218 of file libpq-int.h.

219 {
220  PGASYNC_IDLE, /* nothing's happening, dude */
221  PGASYNC_BUSY, /* query in progress */
222  PGASYNC_READY, /* query done, waiting for client to fetch
223  * result */
224  PGASYNC_READY_MORE, /* query done, waiting for client to fetch
225  * result, more results expected from this
226  * query */
227  PGASYNC_COPY_IN, /* Copy In data transfer in progress */
228  PGASYNC_COPY_OUT, /* Copy Out data transfer in progress */
229  PGASYNC_COPY_BOTH, /* Copy In/Out data transfer in progress */
230  PGASYNC_PIPELINE_IDLE, /* "Idle" between commands in pipeline mode */
PGAsyncStatusType
Definition: libpq-int.h:219
@ PGASYNC_COPY_OUT
Definition: libpq-int.h:228
@ PGASYNC_READY_MORE
Definition: libpq-int.h:224
@ PGASYNC_READY
Definition: libpq-int.h:222
@ PGASYNC_COPY_BOTH
Definition: libpq-int.h:229
@ PGASYNC_IDLE
Definition: libpq-int.h:220
@ PGASYNC_COPY_IN
Definition: libpq-int.h:227
@ PGASYNC_BUSY
Definition: libpq-int.h:221
@ PGASYNC_PIPELINE_IDLE
Definition: libpq-int.h:230

◆ PGQueryClass

Enumerator
PGQUERY_SIMPLE 
PGQUERY_EXTENDED 
PGQUERY_PREPARE 
PGQUERY_DESCRIBE 
PGQUERY_SYNC 
PGQUERY_CLOSE 

Definition at line 310 of file libpq-int.h.

311 {
312  PGQUERY_SIMPLE, /* simple Query protocol (PQexec) */
313  PGQUERY_EXTENDED, /* full Extended protocol (PQexecParams) */
314  PGQUERY_PREPARE, /* Parse only (PQprepare) */
315  PGQUERY_DESCRIBE, /* Describe Statement or Portal */
316  PGQUERY_SYNC, /* Sync (at end of a pipeline) */
318 } PGQueryClass;
PGQueryClass
Definition: libpq-int.h:311
@ PGQUERY_SIMPLE
Definition: libpq-int.h:312
@ PGQUERY_SYNC
Definition: libpq-int.h:316
@ PGQUERY_EXTENDED
Definition: libpq-int.h:313
@ PGQUERY_DESCRIBE
Definition: libpq-int.h:315
@ PGQUERY_CLOSE
Definition: libpq-int.h:317
@ PGQUERY_PREPARE
Definition: libpq-int.h:314

◆ PGTargetServerType

Enumerator
SERVER_TYPE_ANY 
SERVER_TYPE_READ_WRITE 
SERVER_TYPE_READ_ONLY 
SERVER_TYPE_PRIMARY 
SERVER_TYPE_STANDBY 
SERVER_TYPE_PREFER_STANDBY 
SERVER_TYPE_PREFER_STANDBY_PASS2 

Definition at line 234 of file libpq-int.h.

235 {
236  SERVER_TYPE_ANY = 0, /* Any server (default) */
237  SERVER_TYPE_READ_WRITE, /* Read-write server */
238  SERVER_TYPE_READ_ONLY, /* Read-only server */
239  SERVER_TYPE_PRIMARY, /* Primary server */
240  SERVER_TYPE_STANDBY, /* Standby server */
241  SERVER_TYPE_PREFER_STANDBY, /* Prefer standby server */
242  SERVER_TYPE_PREFER_STANDBY_PASS2 /* second pass - behaves same as ANY */
PGTargetServerType
Definition: libpq-int.h:235
@ SERVER_TYPE_STANDBY
Definition: libpq-int.h:240
@ SERVER_TYPE_PRIMARY
Definition: libpq-int.h:239
@ SERVER_TYPE_ANY
Definition: libpq-int.h:236
@ SERVER_TYPE_READ_WRITE
Definition: libpq-int.h:237
@ SERVER_TYPE_PREFER_STANDBY_PASS2
Definition: libpq-int.h:242
@ SERVER_TYPE_PREFER_STANDBY
Definition: libpq-int.h:241
@ SERVER_TYPE_READ_ONLY
Definition: libpq-int.h:238

◆ PGTernaryBool

Enumerator
PG_BOOL_UNKNOWN 
PG_BOOL_YES 
PG_BOOL_NO 

Definition at line 246 of file libpq-int.h.

247 {
248  PG_BOOL_UNKNOWN = 0, /* Currently unknown */
249  PG_BOOL_YES, /* Yes (true) */
250  PG_BOOL_NO /* No (false) */
251 } PGTernaryBool;
PGTernaryBool
Definition: libpq-int.h:247
@ PG_BOOL_YES
Definition: libpq-int.h:249
@ PG_BOOL_NO
Definition: libpq-int.h:250
@ PG_BOOL_UNKNOWN
Definition: libpq-int.h:248

Function Documentation

◆ libpq_append_conn_error()

void void libpq_append_conn_error ( PGconn conn,
const char *  fmt,
  ... 
)

◆ libpq_append_error()

void libpq_append_error ( PQExpBuffer  errorMessage,
const char *  fmt,
  ... 
)

◆ pgtls_close()

void pgtls_close ( PGconn conn)

Definition at line 1584 of file fe-secure-openssl.c.

1585 {
1586  bool destroy_needed = false;
1587 
1588  if (conn->ssl_in_use)
1589  {
1590  if (conn->ssl)
1591  {
1592  /*
1593  * We can't destroy everything SSL-related here due to the
1594  * possible later calls to OpenSSL routines which may need our
1595  * thread callbacks, so set a flag here and check at the end.
1596  */
1597 
1598  SSL_shutdown(conn->ssl);
1599  SSL_free(conn->ssl);
1600  conn->ssl = NULL;
1601  conn->ssl_in_use = false;
1602 
1603  destroy_needed = true;
1604  }
1605 
1606  if (conn->peer)
1607  {
1608  X509_free(conn->peer);
1609  conn->peer = NULL;
1610  }
1611 
1612 #ifdef USE_SSL_ENGINE
1613  if (conn->engine)
1614  {
1615  ENGINE_finish(conn->engine);
1616  ENGINE_free(conn->engine);
1617  conn->engine = NULL;
1618  }
1619 #endif
1620  }
1621  else
1622  {
1623  /*
1624  * In the non-SSL case, just remove the crypto callbacks if the
1625  * connection has then loaded. This code path has no dependency on
1626  * any pending SSL calls.
1627  */
1628  if (conn->crypto_loaded)
1629  destroy_needed = true;
1630  }
1631 
1632  /*
1633  * This will remove our crypto locking hooks if this is the last
1634  * connection using libcrypto which means we must wait to call it until
1635  * after all the potential SSL calls have been made, otherwise we can end
1636  * up with a race condition and possible deadlocks.
1637  *
1638  * See comments above destroy_ssl_system().
1639  */
1640  if (destroy_needed)
1641  {
1643  conn->crypto_loaded = false;
1644  }
1645 }
static void destroy_ssl_system(void)
bool ssl_in_use
Definition: libpq-int.h:531

References conn, destroy_ssl_system(), and pg_conn::ssl_in_use.

Referenced by open_client_SSL(), pgtls_open_client(), and pqsecure_close().

◆ pgtls_init()

int pgtls_init ( PGconn conn,
bool  do_ssl,
bool  do_crypto 
)

Definition at line 777 of file fe-secure-openssl.c.

778 {
779 #ifdef ENABLE_THREAD_SAFETY
780 #ifdef WIN32
781  /* Also see similar code in fe-connect.c, default_threadlock() */
782  if (ssl_config_mutex == NULL)
783  {
784  while (InterlockedExchange(&win32_ssl_create_mutex, 1) == 1)
785  /* loop, another thread own the lock */ ;
786  if (ssl_config_mutex == NULL)
787  {
788  if (pthread_mutex_init(&ssl_config_mutex, NULL))
789  return -1;
790  }
791  InterlockedExchange(&win32_ssl_create_mutex, 0);
792  }
793 #endif
794  if (pthread_mutex_lock(&ssl_config_mutex))
795  return -1;
796 
797 #ifdef HAVE_CRYPTO_LOCK
798  if (pq_init_crypto_lib)
799  {
800  /*
801  * If necessary, set up an array to hold locks for libcrypto.
802  * libcrypto will tell us how big to make this array.
803  */
804  if (pq_lockarray == NULL)
805  {
806  int i;
807 
808  pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
809  if (!pq_lockarray)
810  {
811  pthread_mutex_unlock(&ssl_config_mutex);
812  return -1;
813  }
814  for (i = 0; i < CRYPTO_num_locks(); i++)
815  {
816  if (pthread_mutex_init(&pq_lockarray[i], NULL))
817  {
818  free(pq_lockarray);
819  pq_lockarray = NULL;
820  pthread_mutex_unlock(&ssl_config_mutex);
821  return -1;
822  }
823  }
824  }
825 
826  if (do_crypto && !conn->crypto_loaded)
827  {
828  if (crypto_open_connections++ == 0)
829  {
830  /*
831  * These are only required for threaded libcrypto
832  * applications, but make sure we don't stomp on them if
833  * they're already set.
834  */
835  if (CRYPTO_get_id_callback() == NULL)
836  CRYPTO_set_id_callback(pq_threadidcallback);
837  if (CRYPTO_get_locking_callback() == NULL)
838  CRYPTO_set_locking_callback(pq_lockingcallback);
839  }
840 
841  conn->crypto_loaded = true;
842  }
843  }
844 #endif /* HAVE_CRYPTO_LOCK */
845 #endif /* ENABLE_THREAD_SAFETY */
846 
847  if (!ssl_lib_initialized && do_ssl)
848  {
849  if (pq_init_ssl_lib)
850  {
851 #ifdef HAVE_OPENSSL_INIT_SSL
852  OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL);
853 #else
854  OPENSSL_config(NULL);
855  SSL_library_init();
856  SSL_load_error_strings();
857 #endif
858  }
859  ssl_lib_initialized = true;
860  }
861 
862 #ifdef ENABLE_THREAD_SAFETY
863  pthread_mutex_unlock(&ssl_config_mutex);
864 #endif
865  return 0;
866 }
static bool pq_init_crypto_lib
static bool ssl_lib_initialized
static bool pq_init_ssl_lib
#define free(a)
Definition: header.h:65
#define malloc(a)
Definition: header.h:50
int i
Definition: isn.c:73
int pthread_mutex_unlock(pthread_mutex_t *mp)
Definition: pthread-win32.c:54
int pthread_mutex_lock(pthread_mutex_t *mp)
Definition: pthread-win32.c:45
int pthread_mutex_init(pthread_mutex_t *mp, void *attr)
Definition: pthread-win32.c:35
CRITICAL_SECTION * pthread_mutex_t
Definition: pthread-win32.h:8

References conn, free, i, malloc, pq_init_crypto_lib, pq_init_ssl_lib, pthread_mutex_init(), pthread_mutex_lock(), pthread_mutex_unlock(), and ssl_lib_initialized.

Referenced by pqsecure_initialize().

◆ pgtls_init_library()

void pgtls_init_library ( bool  do_ssl,
int  do_crypto 
)

Definition at line 113 of file fe-secure-openssl.c.

114 {
115 #ifdef ENABLE_THREAD_SAFETY
116 
117  /*
118  * Disallow changing the flags while we have open connections, else we'd
119  * get completely confused.
120  */
121  if (crypto_open_connections != 0)
122  return;
123 #endif
124 
125  pq_init_ssl_lib = do_ssl;
126  pq_init_crypto_lib = do_crypto;
127 }

References pq_init_crypto_lib, and pq_init_ssl_lib.

Referenced by PQinitOpenSSL(), and PQinitSSL().

◆ pgtls_open_client()

PostgresPollingStatusType pgtls_open_client ( PGconn conn)

Definition at line 130 of file fe-secure-openssl.c.

131 {
132  /* First time through? */
133  if (conn->ssl == NULL)
134  {
135  /*
136  * Create a connection-specific SSL object, and load client
137  * certificate, private key, and trusted CA certs.
138  */
139  if (initialize_SSL(conn) != 0)
140  {
141  /* initialize_SSL already put a message in conn->errorMessage */
142  pgtls_close(conn);
143  return PGRES_POLLING_FAILED;
144  }
145  }
146 
147  /* Begin or continue the actual handshake */
148  return open_client_SSL(conn);
149 }
static int initialize_SSL(PGconn *conn)
static PostgresPollingStatusType open_client_SSL(PGconn *conn)
void pgtls_close(PGconn *conn)
@ PGRES_POLLING_FAILED
Definition: libpq-fe.h:86

References conn, initialize_SSL(), open_client_SSL(), PGRES_POLLING_FAILED, and pgtls_close().

Referenced by pqsecure_open_client().

◆ pgtls_read()

ssize_t pgtls_read ( PGconn conn,
void *  ptr,
size_t  len 
)

Definition at line 152 of file fe-secure-openssl.c.

153 {
154  ssize_t n;
155  int result_errno = 0;
156  char sebuf[PG_STRERROR_R_BUFLEN];
157  int err;
158  unsigned long ecode;
159 
160 rloop:
161 
162  /*
163  * Prepare to call SSL_get_error() by clearing thread's OpenSSL error
164  * queue. In general, the current thread's error queue must be empty
165  * before the TLS/SSL I/O operation is attempted, or SSL_get_error() will
166  * not work reliably. Since the possibility exists that other OpenSSL
167  * clients running in the same thread but not under our control will fail
168  * to call ERR_get_error() themselves (after their own I/O operations),
169  * pro-actively clear the per-thread error queue now.
170  */
171  SOCK_ERRNO_SET(0);
172  ERR_clear_error();
173  n = SSL_read(conn->ssl, ptr, len);
174  err = SSL_get_error(conn->ssl, n);
175 
176  /*
177  * Other clients of OpenSSL may fail to call ERR_get_error(), but we
178  * always do, so as to not cause problems for OpenSSL clients that don't
179  * call ERR_clear_error() defensively. Be sure that this happens by
180  * calling now. SSL_get_error() relies on the OpenSSL per-thread error
181  * queue being intact, so this is the earliest possible point
182  * ERR_get_error() may be called.
183  */
184  ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
185  switch (err)
186  {
187  case SSL_ERROR_NONE:
188  if (n < 0)
189  {
190  /* Not supposed to happen, so we don't translate the msg */
192  "SSL_read failed but did not provide error information\n");
193  /* assume the connection is broken */
194  result_errno = ECONNRESET;
195  }
196  break;
197  case SSL_ERROR_WANT_READ:
198  n = 0;
199  break;
200  case SSL_ERROR_WANT_WRITE:
201 
202  /*
203  * Returning 0 here would cause caller to wait for read-ready,
204  * which is not correct since what SSL wants is wait for
205  * write-ready. The former could get us stuck in an infinite
206  * wait, so don't risk it; busy-loop instead.
207  */
208  goto rloop;
209  case SSL_ERROR_SYSCALL:
210  if (n < 0)
211  {
212  result_errno = SOCK_ERRNO;
213  if (result_errno == EPIPE ||
214  result_errno == ECONNRESET)
215  libpq_append_conn_error(conn, "server closed the connection unexpectedly\n"
216  "\tThis probably means the server terminated abnormally\n"
217  "\tbefore or while processing the request.");
218  else
219  libpq_append_conn_error(conn, "SSL SYSCALL error: %s",
220  SOCK_STRERROR(result_errno,
221  sebuf, sizeof(sebuf)));
222  }
223  else
224  {
225  libpq_append_conn_error(conn, "SSL SYSCALL error: EOF detected");
226  /* assume the connection is broken */
227  result_errno = ECONNRESET;
228  n = -1;
229  }
230  break;
231  case SSL_ERROR_SSL:
232  {
233  char *errm = SSLerrmessage(ecode);
234 
235  libpq_append_conn_error(conn, "SSL error: %s", errm);
236  SSLerrfree(errm);
237  /* assume the connection is broken */
238  result_errno = ECONNRESET;
239  n = -1;
240  break;
241  }
242  case SSL_ERROR_ZERO_RETURN:
243 
244  /*
245  * Per OpenSSL documentation, this error code is only returned for
246  * a clean connection closure, so we should not report it as a
247  * server crash.
248  */
249  libpq_append_conn_error(conn, "SSL connection has been closed unexpectedly");
250  result_errno = ECONNRESET;
251  n = -1;
252  break;
253  default:
254  libpq_append_conn_error(conn, "unrecognized SSL error code: %d", err);
255  /* assume the connection is broken */
256  result_errno = ECONNRESET;
257  n = -1;
258  break;
259  }
260 
261  /* ensure we return the intended errno to caller */
262  SOCK_ERRNO_SET(result_errno);
263 
264  return n;
265 }
void err(int eval, const char *fmt,...)
Definition: err.c:43
void libpq_append_conn_error(PGconn *conn, const char *fmt,...)
Definition: fe-misc.c:1312
static void SSLerrfree(char *buf)
static char * SSLerrmessage(unsigned long ecode)
#define SOCK_STRERROR
Definition: libpq-int.h:917
#define SOCK_ERRNO
Definition: libpq-int.h:916
#define SOCK_ERRNO_SET(e)
Definition: libpq-int.h:918
const void size_t len
#define PG_STRERROR_R_BUFLEN
Definition: port.h:256
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:367
PQExpBufferData errorMessage
Definition: libpq-int.h:601
#define ECONNRESET
Definition: win32_port.h:386

References appendPQExpBufferStr(), conn, ECONNRESET, err(), pg_conn::errorMessage, len, libpq_append_conn_error(), PG_STRERROR_R_BUFLEN, SOCK_ERRNO, SOCK_ERRNO_SET, SOCK_STRERROR, SSLerrfree(), and SSLerrmessage().

Referenced by pqsecure_read().

◆ pgtls_read_pending()

bool pgtls_read_pending ( PGconn conn)

Definition at line 268 of file fe-secure-openssl.c.

269 {
270  return SSL_pending(conn->ssl) > 0;
271 }

References conn.

Referenced by pqSocketCheck().

◆ pgtls_verify_peer_name_matches_certificate_guts()

int pgtls_verify_peer_name_matches_certificate_guts ( PGconn conn,
int *  names_examined,
char **  first_name 
)

Definition at line 582 of file fe-secure-openssl.c.

585 {
586  STACK_OF(GENERAL_NAME) * peer_san;
587  int i;
588  int rc = 0;
589  char *host = conn->connhost[conn->whichhost].host;
590  int host_type;
591  bool check_cn = true;
592 
593  Assert(host && host[0]); /* should be guaranteed by caller */
594 
595  /*
596  * We try to match the NSS behavior here, which is a slight departure from
597  * the spec but seems to make more intuitive sense:
598  *
599  * If connhost contains a DNS name, and the certificate's SANs contain any
600  * dNSName entries, then we'll ignore the Subject Common Name entirely;
601  * otherwise, we fall back to checking the CN. (This behavior matches the
602  * RFC.)
603  *
604  * If connhost contains an IP address, and the SANs contain iPAddress
605  * entries, we again ignore the CN. Otherwise, we allow the CN to match,
606  * EVEN IF there is a dNSName in the SANs. (RFC 6125 prohibits this: "A
607  * client MUST NOT seek a match for a reference identifier of CN-ID if the
608  * presented identifiers include a DNS-ID, SRV-ID, URI-ID, or any
609  * application-specific identifier types supported by the client.")
610  *
611  * NOTE: Prior versions of libpq did not consider iPAddress entries at
612  * all, so this new behavior might break a certificate that has different
613  * IP addresses in the Subject CN and the SANs.
614  */
615  if (is_ip_address(host))
616  host_type = GEN_IPADD;
617  else
618  host_type = GEN_DNS;
619 
620  /*
621  * First, get the Subject Alternative Names (SANs) from the certificate,
622  * and compare them against the originally given hostname.
623  */
624  peer_san = (STACK_OF(GENERAL_NAME) *)
625  X509_get_ext_d2i(conn->peer, NID_subject_alt_name, NULL, NULL);
626 
627  if (peer_san)
628  {
629  int san_len = sk_GENERAL_NAME_num(peer_san);
630 
631  for (i = 0; i < san_len; i++)
632  {
633  const GENERAL_NAME *name = sk_GENERAL_NAME_value(peer_san, i);
634  char *alt_name = NULL;
635 
636  if (name->type == host_type)
637  {
638  /*
639  * This SAN is of the same type (IP or DNS) as our host name,
640  * so don't allow a fallback check of the CN.
641  */
642  check_cn = false;
643  }
644 
645  if (name->type == GEN_DNS)
646  {
647  (*names_examined)++;
649  name->d.dNSName,
650  &alt_name);
651  }
652  else if (name->type == GEN_IPADD)
653  {
654  (*names_examined)++;
656  name->d.iPAddress,
657  &alt_name);
658  }
659 
660  if (alt_name)
661  {
662  if (!*first_name)
663  *first_name = alt_name;
664  else
665  free(alt_name);
666  }
667 
668  if (rc != 0)
669  {
670  /*
671  * Either we hit an error or a match, and either way we should
672  * not fall back to the CN.
673  */
674  check_cn = false;
675  break;
676  }
677  }
678  sk_GENERAL_NAME_pop_free(peer_san, GENERAL_NAME_free);
679  }
680 
681  /*
682  * If there is no subjectAltName extension of the matching type, check the
683  * Common Name.
684  *
685  * (Per RFC 2818 and RFC 6125, if the subjectAltName extension of type
686  * dNSName is present, the CN must be ignored. We break this rule if host
687  * is an IP address; see the comment above.)
688  */
689  if (check_cn)
690  {
691  X509_NAME *subject_name;
692 
693  subject_name = X509_get_subject_name(conn->peer);
694  if (subject_name != NULL)
695  {
696  int cn_index;
697 
698  cn_index = X509_NAME_get_index_by_NID(subject_name,
699  NID_commonName, -1);
700  if (cn_index >= 0)
701  {
702  char *common_name = NULL;
703 
704  (*names_examined)++;
706  X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject_name, cn_index)),
707  &common_name);
708 
709  if (common_name)
710  {
711  if (!*first_name)
712  *first_name = common_name;
713  else
714  free(common_name);
715  }
716  }
717  }
718  }
719 
720  return rc;
721 }
const char * name
Definition: encode.c:571
static int openssl_verify_peer_name_matches_certificate_name(PGconn *conn, ASN1_STRING *name_entry, char **store_name)
static int openssl_verify_peer_name_matches_certificate_ip(PGconn *conn, ASN1_OCTET_STRING *addr_entry, char **store_name)
static bool is_ip_address(const char *host)
Assert(fmt[strlen(fmt) - 1] !='\n')
char * host
Definition: libpq-int.h:338
int whichhost
Definition: libpq-int.h:431
pg_conn_host * connhost
Definition: libpq-int.h:432

References Assert(), conn, pg_conn::connhost, free, pg_conn_host::host, i, is_ip_address(), name, openssl_verify_peer_name_matches_certificate_ip(), openssl_verify_peer_name_matches_certificate_name(), and pg_conn::whichhost.

Referenced by pq_verify_peer_name_matches_certificate().

◆ pgtls_write()

ssize_t pgtls_write ( PGconn conn,
const void *  ptr,
size_t  len 
)

Definition at line 274 of file fe-secure-openssl.c.

275 {
276  ssize_t n;
277  int result_errno = 0;
278  char sebuf[PG_STRERROR_R_BUFLEN];
279  int err;
280  unsigned long ecode;
281 
282  SOCK_ERRNO_SET(0);
283  ERR_clear_error();
284  n = SSL_write(conn->ssl, ptr, len);
285  err = SSL_get_error(conn->ssl, n);
286  ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
287  switch (err)
288  {
289  case SSL_ERROR_NONE:
290  if (n < 0)
291  {
292  /* Not supposed to happen, so we don't translate the msg */
294  "SSL_write failed but did not provide error information\n");
295  /* assume the connection is broken */
296  result_errno = ECONNRESET;
297  }
298  break;
299  case SSL_ERROR_WANT_READ:
300 
301  /*
302  * Returning 0 here causes caller to wait for write-ready, which
303  * is not really the right thing, but it's the best we can do.
304  */
305  n = 0;
306  break;
307  case SSL_ERROR_WANT_WRITE:
308  n = 0;
309  break;
310  case SSL_ERROR_SYSCALL:
311  if (n < 0)
312  {
313  result_errno = SOCK_ERRNO;
314  if (result_errno == EPIPE || result_errno == ECONNRESET)
315  libpq_append_conn_error(conn, "server closed the connection unexpectedly\n"
316  "\tThis probably means the server terminated abnormally\n"
317  "\tbefore or while processing the request.");
318  else
319  libpq_append_conn_error(conn, "SSL SYSCALL error: %s",
320  SOCK_STRERROR(result_errno,
321  sebuf, sizeof(sebuf)));
322  }
323  else
324  {
325  libpq_append_conn_error(conn, "SSL SYSCALL error: EOF detected");
326  /* assume the connection is broken */
327  result_errno = ECONNRESET;
328  n = -1;
329  }
330  break;
331  case SSL_ERROR_SSL:
332  {
333  char *errm = SSLerrmessage(ecode);
334 
335  libpq_append_conn_error(conn, "SSL error: %s", errm);
336  SSLerrfree(errm);
337  /* assume the connection is broken */
338  result_errno = ECONNRESET;
339  n = -1;
340  break;
341  }
342  case SSL_ERROR_ZERO_RETURN:
343 
344  /*
345  * Per OpenSSL documentation, this error code is only returned for
346  * a clean connection closure, so we should not report it as a
347  * server crash.
348  */
349  libpq_append_conn_error(conn, "SSL connection has been closed unexpectedly");
350  result_errno = ECONNRESET;
351  n = -1;
352  break;
353  default:
354  libpq_append_conn_error(conn, "unrecognized SSL error code: %d", err);
355  /* assume the connection is broken */
356  result_errno = ECONNRESET;
357  n = -1;
358  break;
359  }
360 
361  /* ensure we return the intended errno to caller */
362  SOCK_ERRNO_SET(result_errno);
363 
364  return n;
365 }

References appendPQExpBufferStr(), conn, ECONNRESET, err(), pg_conn::errorMessage, len, libpq_append_conn_error(), PG_STRERROR_R_BUFLEN, SOCK_ERRNO, SOCK_ERRNO_SET, SOCK_STRERROR, SSLerrfree(), and SSLerrmessage().

Referenced by pqsecure_write().

◆ pqBuildErrorMessage3()

void pqBuildErrorMessage3 ( PQExpBuffer  msg,
const PGresult res,
PGVerbosity  verbosity,
PGContextVisibility  show_context 
)

Definition at line 997 of file fe-protocol3.c.

999 {
1000  const char *val;
1001  const char *querytext = NULL;
1002  int querypos = 0;
1003 
1004  /* If we couldn't allocate a PGresult, just say "out of memory" */
1005  if (res == NULL)
1006  {
1007  appendPQExpBufferStr(msg, libpq_gettext("out of memory\n"));
1008  return;
1009  }
1010 
1011  /*
1012  * If we don't have any broken-down fields, just return the base message.
1013  * This mainly applies if we're given a libpq-generated error result.
1014  */
1015  if (res->errFields == NULL)
1016  {
1017  if (res->errMsg && res->errMsg[0])
1019  else
1020  appendPQExpBufferStr(msg, libpq_gettext("no error message available\n"));
1021  return;
1022  }
1023 
1024  /* Else build error message from relevant fields */
1026  if (val)
1027  appendPQExpBuffer(msg, "%s: ", val);
1028 
1029  if (verbosity == PQERRORS_SQLSTATE)
1030  {
1031  /*
1032  * If we have a SQLSTATE, print that and nothing else. If not (which
1033  * shouldn't happen for server-generated errors, but might possibly
1034  * happen for libpq-generated ones), fall back to TERSE format, as
1035  * that seems better than printing nothing at all.
1036  */
1038  if (val)
1039  {
1040  appendPQExpBuffer(msg, "%s\n", val);
1041  return;
1042  }
1043  verbosity = PQERRORS_TERSE;
1044  }
1045 
1046  if (verbosity == PQERRORS_VERBOSE)
1047  {
1049  if (val)
1050  appendPQExpBuffer(msg, "%s: ", val);
1051  }
1053  if (val)
1054  appendPQExpBufferStr(msg, val);
1056  if (val)
1057  {
1058  if (verbosity != PQERRORS_TERSE && res->errQuery != NULL)
1059  {
1060  /* emit position as a syntax cursor display */
1061  querytext = res->errQuery;
1062  querypos = atoi(val);
1063  }
1064  else
1065  {
1066  /* emit position as text addition to primary message */
1067  /* translator: %s represents a digit string */
1068  appendPQExpBuffer(msg, libpq_gettext(" at character %s"),
1069  val);
1070  }
1071  }
1072  else
1073  {
1075  if (val)
1076  {
1078  if (verbosity != PQERRORS_TERSE && querytext != NULL)
1079  {
1080  /* emit position as a syntax cursor display */
1081  querypos = atoi(val);
1082  }
1083  else
1084  {
1085  /* emit position as text addition to primary message */
1086  /* translator: %s represents a digit string */
1087  appendPQExpBuffer(msg, libpq_gettext(" at character %s"),
1088  val);
1089  }
1090  }
1091  }
1092  appendPQExpBufferChar(msg, '\n');
1093  if (verbosity != PQERRORS_TERSE)
1094  {
1095  if (querytext && querypos > 0)
1096  reportErrorPosition(msg, querytext, querypos,
1097  res->client_encoding);
1099  if (val)
1100  appendPQExpBuffer(msg, libpq_gettext("DETAIL: %s\n"), val);
1102  if (val)
1103  appendPQExpBuffer(msg, libpq_gettext("HINT: %s\n"), val);
1105  if (val)
1106  appendPQExpBuffer(msg, libpq_gettext("QUERY: %s\n"), val);
1107  if (show_context == PQSHOW_CONTEXT_ALWAYS ||
1108  (show_context == PQSHOW_CONTEXT_ERRORS &&
1110  {
1112  if (val)
1113  appendPQExpBuffer(msg, libpq_gettext("CONTEXT: %s\n"),
1114  val);
1115  }
1116  }
1117  if (verbosity == PQERRORS_VERBOSE)
1118  {
1120  if (val)
1121  appendPQExpBuffer(msg,
1122  libpq_gettext("SCHEMA NAME: %s\n"), val);
1124  if (val)
1125  appendPQExpBuffer(msg,
1126  libpq_gettext("TABLE NAME: %s\n"), val);
1128  if (val)
1129  appendPQExpBuffer(msg,
1130  libpq_gettext("COLUMN NAME: %s\n"), val);
1132  if (val)
1133  appendPQExpBuffer(msg,
1134  libpq_gettext("DATATYPE NAME: %s\n"), val);
1136  if (val)
1137  appendPQExpBuffer(msg,
1138  libpq_gettext("CONSTRAINT NAME: %s\n"), val);
1139  }
1140  if (verbosity == PQERRORS_VERBOSE)
1141  {
1142  const char *valf;
1143  const char *vall;
1144 
1148  if (val || valf || vall)
1149  {
1150  appendPQExpBufferStr(msg, libpq_gettext("LOCATION: "));
1151  if (val)
1152  appendPQExpBuffer(msg, libpq_gettext("%s, "), val);
1153  if (valf && vall) /* unlikely we'd have just one */
1154  appendPQExpBuffer(msg, libpq_gettext("%s:%s"),
1155  valf, vall);
1156  appendPQExpBufferChar(msg, '\n');
1157  }
1158  }
1159 }
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3299
static void reportErrorPosition(PQExpBuffer msg, const char *query, int loc, int encoding)
long val
Definition: informix.c:664
@ PGRES_FATAL_ERROR
Definition: libpq-fe.h:108
@ PQSHOW_CONTEXT_ALWAYS
Definition: libpq-fe.h:137
@ PQSHOW_CONTEXT_ERRORS
Definition: libpq-fe.h:136
@ PQERRORS_VERBOSE
Definition: libpq-fe.h:129
@ PQERRORS_TERSE
Definition: libpq-fe.h:127
@ PQERRORS_SQLSTATE
Definition: libpq-fe.h:130
#define libpq_gettext(x)
Definition: libpq-int.h:895
#define PG_DIAG_INTERNAL_QUERY
Definition: postgres_ext.h:62
#define PG_DIAG_SCHEMA_NAME
Definition: postgres_ext.h:64
#define PG_DIAG_CONSTRAINT_NAME
Definition: postgres_ext.h:68
#define PG_DIAG_DATATYPE_NAME
Definition: postgres_ext.h:67
#define PG_DIAG_SOURCE_LINE
Definition: postgres_ext.h:70
#define PG_DIAG_STATEMENT_POSITION
Definition: postgres_ext.h:60
#define PG_DIAG_SOURCE_FILE
Definition: postgres_ext.h:69
#define PG_DIAG_MESSAGE_HINT
Definition: postgres_ext.h:59
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:56
#define PG_DIAG_TABLE_NAME
Definition: postgres_ext.h:65
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:57
#define PG_DIAG_COLUMN_NAME
Definition: postgres_ext.h:66
#define PG_DIAG_MESSAGE_DETAIL
Definition: postgres_ext.h:58
#define PG_DIAG_CONTEXT
Definition: postgres_ext.h:63
#define PG_DIAG_SEVERITY
Definition: postgres_ext.h:54
#define PG_DIAG_SOURCE_FUNCTION
Definition: postgres_ext.h:71
#define PG_DIAG_INTERNAL_POSITION
Definition: postgres_ext.h:61
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:265
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:378
char * errMsg
Definition: libpq-int.h:198
PGMessageField * errFields
Definition: libpq-int.h:199
ExecStatusType resultStatus
Definition: libpq-int.h:179
char * errQuery
Definition: libpq-int.h:200
int client_encoding
Definition: libpq-int.h:191

References appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), pg_result::client_encoding, pg_result::errFields, pg_result::errMsg, pg_result::errQuery, libpq_gettext, PG_DIAG_COLUMN_NAME, PG_DIAG_CONSTRAINT_NAME, PG_DIAG_CONTEXT, PG_DIAG_DATATYPE_NAME, PG_DIAG_INTERNAL_POSITION, PG_DIAG_INTERNAL_QUERY, PG_DIAG_MESSAGE_DETAIL, PG_DIAG_MESSAGE_HINT, PG_DIAG_MESSAGE_PRIMARY, PG_DIAG_SCHEMA_NAME, PG_DIAG_SEVERITY, PG_DIAG_SOURCE_FILE, PG_DIAG_SOURCE_FUNCTION, PG_DIAG_SOURCE_LINE, PG_DIAG_SQLSTATE, PG_DIAG_STATEMENT_POSITION, PG_DIAG_TABLE_NAME, PGRES_FATAL_ERROR, PQERRORS_SQLSTATE, PQERRORS_TERSE, PQERRORS_VERBOSE, PQresultErrorField(), PQSHOW_CONTEXT_ALWAYS, PQSHOW_CONTEXT_ERRORS, reportErrorPosition(), res, pg_result::resultStatus, and val.

Referenced by pqGetErrorNotice3(), and PQresultVerboseErrorMessage().

◆ pqBuildStartupPacket3()

char* pqBuildStartupPacket3 ( PGconn conn,
int *  packetlen,
const PQEnvironmentOption options 
)

Definition at line 2219 of file fe-protocol3.c.

2221 {
2222  char *startpacket;
2223 
2224  *packetlen = build_startup_packet(conn, NULL, options);
2225  startpacket = (char *) malloc(*packetlen);
2226  if (!startpacket)
2227  return NULL;
2228  *packetlen = build_startup_packet(conn, startpacket, options);
2229  return startpacket;
2230 }
static int build_startup_packet(const PGconn *conn, char *packet, const PQEnvironmentOption *options)

References build_startup_packet(), conn, and malloc.

Referenced by PQconnectPoll().

◆ pqCheckInBufferSpace()

int pqCheckInBufferSpace ( size_t  bytes_needed,
PGconn conn 
)

Definition at line 352 of file fe-misc.c.

353 {
354  int newsize = conn->inBufSize;
355  char *newbuf;
356 
357  /* Quick exit if we have enough space */
358  if (bytes_needed <= (size_t) newsize)
359  return 0;
360 
361  /*
362  * Before concluding that we need to enlarge the buffer, left-justify
363  * whatever is in it and recheck. The caller's value of bytes_needed
364  * includes any data to the left of inStart, but we can delete that in
365  * preference to enlarging the buffer. It's slightly ugly to have this
366  * function do this, but it's better than making callers worry about it.
367  */
368  bytes_needed -= conn->inStart;
369 
370  if (conn->inStart < conn->inEnd)
371  {
372  if (conn->inStart > 0)
373  {
374  memmove(conn->inBuffer, conn->inBuffer + conn->inStart,
375  conn->inEnd - conn->inStart);
376  conn->inEnd -= conn->inStart;
377  conn->inCursor -= conn->inStart;
378  conn->inStart = 0;
379  }
380  }
381  else
382  {
383  /* buffer is logically empty, reset it */
384  conn->inStart = conn->inCursor = conn->inEnd = 0;
385  }
386 
387  /* Recheck whether we have enough space */
388  if (bytes_needed <= (size_t) newsize)
389  return 0;
390 
391  /*
392  * If we need to enlarge the buffer, we first try to double it in size; if
393  * that doesn't work, enlarge in multiples of 8K. This avoids thrashing
394  * the malloc pool by repeated small enlargements.
395  *
396  * Note: tests for newsize > 0 are to catch integer overflow.
397  */
398  do
399  {
400  newsize *= 2;
401  } while (newsize > 0 && bytes_needed > (size_t) newsize);
402 
403  if (newsize > 0 && bytes_needed <= (size_t) newsize)
404  {
405  newbuf = realloc(conn->inBuffer, newsize);
406  if (newbuf)
407  {
408  /* realloc succeeded */
409  conn->inBuffer = newbuf;
410  conn->inBufSize = newsize;
411  return 0;
412  }
413  }
414 
415  newsize = conn->inBufSize;
416  do
417  {
418  newsize += 8192;
419  } while (newsize > 0 && bytes_needed > (size_t) newsize);
420 
421  if (newsize > 0 && bytes_needed <= (size_t) newsize)
422  {
423  newbuf = realloc(conn->inBuffer, newsize);
424  if (newbuf)
425  {
426  /* realloc succeeded */
427  conn->inBuffer = newbuf;
428  conn->inBufSize = newsize;
429  return 0;
430  }
431  }
432 
433  /* realloc failed. Probably out of memory */
435  "cannot allocate memory for input buffer\n");
436  return EOF;
437 }
#define realloc(a, b)
Definition: header.h:60
char * inBuffer
Definition: libpq-int.h:492
int inCursor
Definition: libpq-int.h:495
int inEnd
Definition: libpq-int.h:496
int inBufSize
Definition: libpq-int.h:493
int inStart
Definition: libpq-int.h:494

References appendPQExpBufferStr(), conn, pg_conn::errorMessage, pg_conn::inBuffer, pg_conn::inBufSize, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, and realloc.

Referenced by getCopyDataMessage(), PQconnectPoll(), pqFunctionCall3(), pqParseInput3(), and pqReadData().

◆ pqCheckOutBufferSpace()

int pqCheckOutBufferSpace ( size_t  bytes_needed,
PGconn conn 
)

Definition at line 288 of file fe-misc.c.

289 {
290  int newsize = conn->outBufSize;
291  char *newbuf;
292 
293  /* Quick exit if we have enough space */
294  if (bytes_needed <= (size_t) newsize)
295  return 0;
296 
297  /*
298  * If we need to enlarge the buffer, we first try to double it in size; if
299  * that doesn't work, enlarge in multiples of 8K. This avoids thrashing
300  * the malloc pool by repeated small enlargements.
301  *
302  * Note: tests for newsize > 0 are to catch integer overflow.
303  */
304  do
305  {
306  newsize *= 2;
307  } while (newsize > 0 && bytes_needed > (size_t) newsize);
308 
309  if (newsize > 0 && bytes_needed <= (size_t) newsize)
310  {
311  newbuf = realloc(conn->outBuffer, newsize);
312  if (newbuf)
313  {
314  /* realloc succeeded */
315  conn->outBuffer = newbuf;
316  conn->outBufSize = newsize;
317  return 0;
318  }
319  }
320 
321  newsize = conn->outBufSize;
322  do
323  {
324  newsize += 8192;
325  } while (newsize > 0 && bytes_needed > (size_t) newsize);
326 
327  if (newsize > 0 && bytes_needed <= (size_t) newsize)
328  {
329  newbuf = realloc(conn->outBuffer, newsize);
330  if (newbuf)
331  {
332  /* realloc succeeded */
333  conn->outBuffer = newbuf;
334  conn->outBufSize = newsize;
335  return 0;
336  }
337  }
338 
339  /* realloc failed. Probably out of memory */
341  "cannot allocate memory for output buffer\n");
342  return EOF;
343 }
int outBufSize
Definition: libpq-int.h:500
char * outBuffer
Definition: libpq-int.h:499

References appendPQExpBufferStr(), conn, pg_conn::errorMessage, pg_conn::outBuffer, pg_conn::outBufSize, and realloc.

Referenced by PQputCopyData(), pqPutMsgBytes(), and pqPutMsgStart().

◆ pqClearAsyncResult()

void pqClearAsyncResult ( PGconn conn)

Definition at line 776 of file fe-exec.c.

777 {
778  PQclear(conn->result);
779  conn->result = NULL;
780  conn->error_result = false;
782  conn->next_result = NULL;
783 }
void PQclear(PGresult *res)
Definition: fe-exec.c:718
PGresult * next_result
Definition: libpq-int.h:523
PGresult * result
Definition: libpq-int.h:521
bool error_result
Definition: libpq-int.h:522

References conn, pg_conn::error_result, pg_conn::next_result, PQclear(), and pg_conn::result.

Referenced by closePGconn(), getAnotherTuple(), getParamDescriptions(), getRowDescriptions(), PQconnectPoll(), pqGetErrorNotice3(), pqPipelineProcessQueue(), pqSaveErrorResult(), and PQsendQueryStart().

◆ pqCommandQueueAdvance()

void pqCommandQueueAdvance ( PGconn conn)

Definition at line 3015 of file fe-exec.c.

3016 {
3017  PGcmdQueueEntry *prevquery;
3018 
3019  if (conn->cmd_queue_head == NULL)
3020  return;
3021 
3022  /* delink from queue */
3023  prevquery = conn->cmd_queue_head;
3025 
3026  /* If the queue is now empty, reset the tail too */
3027  if (conn->cmd_queue_head == NULL)
3028  conn->cmd_queue_tail = NULL;
3029 
3030  /* and make it recyclable */
3031  prevquery->next = NULL;
3032  pqRecycleCmdQueueEntry(conn, prevquery);
3033 }
static void pqRecycleCmdQueueEntry(PGconn *conn, PGcmdQueueEntry *entry)
Definition: fe-exec.c:1392
struct PGcmdQueueEntry * next
Definition: libpq-int.h:327
PGcmdQueueEntry * cmd_queue_tail
Definition: libpq-int.h:440
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:439

References pg_conn::cmd_queue_head, pg_conn::cmd_queue_tail, conn, PGcmdQueueEntry::next, and pqRecycleCmdQueueEntry().

Referenced by PQgetResult(), and pqParseInput3().

◆ pqDropConnection()

void pqDropConnection ( PGconn conn,
bool  flushInput 
)

Definition at line 456 of file fe-connect.c.

457 {
458  /* Drop any SSL state */
460 
461  /* Close the socket itself */
462  if (conn->sock != PGINVALID_SOCKET)
465 
466  /* Optionally discard any unread data */
467  if (flushInput)
468  conn->inStart = conn->inCursor = conn->inEnd = 0;
469 
470  /* Always discard any unsent data */
471  conn->outCount = 0;
472 
473  /* Likewise, discard any pending pipelined commands */
477  conn->cmd_queue_recycle = NULL;
478 
479  /* Free authentication/encryption state */
480 #ifdef ENABLE_GSS
481  {
482  OM_uint32 min_s;
483 
484  if (conn->gcred != GSS_C_NO_CREDENTIAL)
485  {
486  gss_release_cred(&min_s, &conn->gcred);
487  conn->gcred = GSS_C_NO_CREDENTIAL;
488  }
489  if (conn->gctx)
490  gss_delete_sec_context(&min_s, &conn->gctx, GSS_C_NO_BUFFER);
491  if (conn->gtarg_nam)
492  gss_release_name(&min_s, &conn->gtarg_nam);
493  if (conn->gss_SendBuffer)
494  {
495  free(conn->gss_SendBuffer);
496  conn->gss_SendBuffer = NULL;
497  }
498  if (conn->gss_RecvBuffer)
499  {
500  free(conn->gss_RecvBuffer);
501  conn->gss_RecvBuffer = NULL;
502  }
503  if (conn->gss_ResultBuffer)
504  {
505  free(conn->gss_ResultBuffer);
506  conn->gss_ResultBuffer = NULL;
507  }
508  conn->gssenc = false;
509  }
510 #endif
511 #ifdef ENABLE_SSPI
512  if (conn->sspitarget)
513  {
514  free(conn->sspitarget);
515  conn->sspitarget = NULL;
516  }
517  if (conn->sspicred)
518  {
519  FreeCredentialsHandle(conn->sspicred);
520  free(conn->sspicred);
521  conn->sspicred = NULL;
522  }
523  if (conn->sspictx)
524  {
525  DeleteSecurityContext(conn->sspictx);
526  free(conn->sspictx);
527  conn->sspictx = NULL;
528  }
529  conn->usesspi = 0;
530 #endif
531  if (conn->sasl_state)
532  {
534  conn->sasl_state = NULL;
535  }
536 }
static void pqFreeCommandQueue(PGcmdQueueEntry *queue)
Definition: fe-connect.c:543
void pqsecure_close(PGconn *conn)
Definition: fe-secure.c:189
#define PGINVALID_SOCKET
Definition: port.h:31
#define closesocket
Definition: port.h:349
pgsocket sock
Definition: libpq-int.h:449
const pg_fe_sasl_mech * sasl
Definition: libpq-int.h:526
PGcmdQueueEntry * cmd_queue_recycle
Definition: libpq-int.h:446
void * sasl_state
Definition: libpq-int.h:527
int outCount
Definition: libpq-int.h:501
void(* free)(void *state)
Definition: fe-auth-sasl.h:127

References closesocket, pg_conn::cmd_queue_head, pg_conn::cmd_queue_recycle, pg_conn::cmd_queue_tail, conn, free, pg_fe_sasl_mech::free, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, pg_conn::outCount, PGINVALID_SOCKET, pqFreeCommandQueue(), pqsecure_close(), pg_conn::sasl, pg_conn::sasl_state, and pg_conn::sock.

Referenced by closePGconn(), connectDBStart(), handleSyncLoss(), PQconnectPoll(), and pqReadData().

◆ pqEndcopy3()

int pqEndcopy3 ( PGconn conn)

Definition at line 1898 of file fe-protocol3.c.

1899 {
1900  PGresult *result;
1901 
1902  if (conn->asyncStatus != PGASYNC_COPY_IN &&
1905  {
1906  libpq_append_conn_error(conn, "no COPY in progress");
1907  return 1;
1908  }
1909 
1910  /* Send the CopyDone message if needed */
1911  if (conn->asyncStatus == PGASYNC_COPY_IN ||
1913  {
1914  if (pqPutMsgStart('c', conn) < 0 ||
1915  pqPutMsgEnd(conn) < 0)
1916  return 1;
1917 
1918  /*
1919  * If we sent the COPY command in extended-query mode, we must issue a
1920  * Sync as well.
1921  */
1922  if (conn->cmd_queue_head &&
1924  {
1925  if (pqPutMsgStart('S', conn) < 0 ||
1926  pqPutMsgEnd(conn) < 0)
1927  return 1;
1928  }
1929  }
1930 
1931  /*
1932  * make sure no data is waiting to be sent, abort if we are non-blocking
1933  * and the flush fails
1934  */
1935  if (pqFlush(conn) && pqIsnonblocking(conn))
1936  return 1;
1937 
1938  /* Return to active duty */
1940 
1941  /*
1942  * Non blocking connections may have to abort at this point. If everyone
1943  * played the game there should be no problem, but in error scenarios the
1944  * expected messages may not have arrived yet. (We are assuming that the
1945  * backend's packetizing will ensure that CommandComplete arrives along
1946  * with the CopyDone; are there corner cases where that doesn't happen?)
1947  */
1948  if (pqIsnonblocking(conn) && PQisBusy(conn))
1949  return 1;
1950 
1951  /* Wait for the completion response */
1952  result = PQgetResult(conn);
1953 
1954  /* Expecting a successful result */
1955  if (result && result->resultStatus == PGRES_COMMAND_OK)
1956  {
1957  PQclear(result);
1958  return 0;
1959  }
1960 
1961  /*
1962  * Trouble. For backwards-compatibility reasons, we issue the error
1963  * message as if it were a notice (would be nice to get rid of this
1964  * silliness, but too many apps probably don't handle errors from
1965  * PQendcopy reasonably). Note that the app can still obtain the error
1966  * status from the PGconn object.
1967  */
1968  if (conn->errorMessage.len > 0)
1969  {
1970  /* We have to strip the trailing newline ... pain in neck... */
1971  char svLast = conn->errorMessage.data[conn->errorMessage.len - 1];
1972 
1973  if (svLast == '\n')
1974  conn->errorMessage.data[conn->errorMessage.len - 1] = '\0';
1976  conn->errorMessage.data[conn->errorMessage.len - 1] = svLast;
1977  }
1978 
1979  PQclear(result);
1980 
1981  return 1;
1982 }
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:933
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2004
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2035
int pqFlush(PGconn *conn)
Definition: fe-misc.c:954
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:459
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:518
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:97
#define pqIsnonblocking(conn)
Definition: libpq-int.h:884
PGQueryClass queryclass
Definition: libpq-int.h:325
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:416
PGNoticeHooks noticeHooks
Definition: libpq-int.h:407

References pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, PQExpBufferData::data, pg_conn::errorMessage, PQExpBufferData::len, libpq_append_conn_error(), pg_conn::noticeHooks, PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGQUERY_SIMPLE, PGRES_COMMAND_OK, PQclear(), pqFlush(), PQgetResult(), pqInternalNotice(), PQisBusy(), pqIsnonblocking, pqPutMsgEnd(), pqPutMsgStart(), PGcmdQueueEntry::queryclass, and pg_result::resultStatus.

Referenced by PQendcopy().

◆ pqFlush()

int pqFlush ( PGconn conn)

Definition at line 954 of file fe-misc.c.

955 {
956  if (conn->outCount > 0)
957  {
958  if (conn->Pfdebug)
959  fflush(conn->Pfdebug);
960 
961  return pqSendSome(conn, conn->outCount);
962  }
963 
964  return 0;
965 }
static int pqSendSome(PGconn *conn, int len)
Definition: fe-misc.c:785
static void const char fflush(stdout)
FILE * Pfdebug
Definition: libpq-int.h:403

References conn, fflush(), pg_conn::outCount, pg_conn::Pfdebug, and pqSendSome().

Referenced by pg_SASL_init(), PQconnectPoll(), PQconsumeInput(), pqEndcopy3(), PQexitPipelineMode(), PQflush(), pqFunctionCall3(), PQgetResult(), pqPacketSend(), pqPipelineFlush(), PQputCopyData(), PQputCopyEnd(), PQsendQueryInternal(), PQsetnonblocking(), and sendTerminateConn().

◆ pqFunctionCall3()

PGresult* pqFunctionCall3 ( PGconn conn,
Oid  fnid,
int *  result_buf,
int *  actual_result_len,
int  result_is_int,
const PQArgBlock args,
int  nargs 
)

Definition at line 1991 of file fe-protocol3.c.

1995 {
1996  bool needInput = false;
1998  char id;
1999  int msgLength;
2000  int avail;
2001  int i;
2002 
2003  /* already validated by PQfn */
2005 
2006  /* PQfn already validated connection state */
2007 
2008  if (pqPutMsgStart('F', conn) < 0 || /* function call msg */
2009  pqPutInt(fnid, 4, conn) < 0 || /* function id */
2010  pqPutInt(1, 2, conn) < 0 || /* # of format codes */
2011  pqPutInt(1, 2, conn) < 0 || /* format code: BINARY */
2012  pqPutInt(nargs, 2, conn) < 0) /* # of args */
2013  {
2014  /* error message should be set up already */
2015  return NULL;
2016  }
2017 
2018  for (i = 0; i < nargs; ++i)
2019  { /* len.int4 + contents */
2020  if (pqPutInt(args[i].len, 4, conn))
2021  return NULL;
2022  if (args[i].len == -1)
2023  continue; /* it's NULL */
2024 
2025  if (args[i].isint)
2026  {
2027  if (pqPutInt(args[i].u.integer, args[i].len, conn))
2028  return NULL;
2029  }
2030  else
2031  {
2032  if (pqPutnchar((char *) args[i].u.ptr, args[i].len, conn))
2033  return NULL;
2034  }
2035  }
2036 
2037  if (pqPutInt(1, 2, conn) < 0) /* result format code: BINARY */
2038  return NULL;
2039 
2040  if (pqPutMsgEnd(conn) < 0 ||
2041  pqFlush(conn))
2042  return NULL;
2043 
2044  for (;;)
2045  {
2046  if (needInput)
2047  {
2048  /* Wait for some data to arrive (or for the channel to close) */
2049  if (pqWait(true, false, conn) ||
2050  pqReadData(conn) < 0)
2051  break;
2052  }
2053 
2054  /*
2055  * Scan the message. If we run out of data, loop around to try again.
2056  */
2057  needInput = true;
2058 
2059  conn->inCursor = conn->inStart;
2060  if (pqGetc(&id, conn))
2061  continue;
2062  if (pqGetInt(&msgLength, 4, conn))
2063  continue;
2064 
2065  /*
2066  * Try to validate message type/length here. A length less than 4 is
2067  * definitely broken. Large lengths should only be believed for a few
2068  * message types.
2069  */
2070  if (msgLength < 4)
2071  {
2072  handleSyncLoss(conn, id, msgLength);
2073  break;
2074  }
2075  if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
2076  {
2077  handleSyncLoss(conn, id, msgLength);
2078  break;
2079  }
2080 
2081  /*
2082  * Can't process if message body isn't all here yet.
2083  */
2084  msgLength -= 4;
2085  avail = conn->inEnd - conn->inCursor;
2086  if (avail < msgLength)
2087  {
2088  /*
2089  * Before looping, enlarge the input buffer if needed to hold the
2090  * whole message. See notes in parseInput.
2091  */
2092  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
2093  conn))
2094  {
2095  /*
2096  * XXX add some better recovery code... plan is to skip over
2097  * the message using its length, then report an error. For the
2098  * moment, just treat this like loss of sync (which indeed it
2099  * might be!)
2100  */
2101  handleSyncLoss(conn, id, msgLength);
2102  break;
2103  }
2104  continue;
2105  }
2106 
2107  /*
2108  * We should see V or E response to the command, but might get N
2109  * and/or A notices first. We also need to swallow the final Z before
2110  * returning.
2111  */
2112  switch (id)
2113  {
2114  case 'V': /* function result */
2115  if (pqGetInt(actual_result_len, 4, conn))
2116  continue;
2117  if (*actual_result_len != -1)
2118  {
2119  if (result_is_int)
2120  {
2121  if (pqGetInt(result_buf, *actual_result_len, conn))
2122  continue;
2123  }
2124  else
2125  {
2126  if (pqGetnchar((char *) result_buf,
2127  *actual_result_len,
2128  conn))
2129  continue;
2130  }
2131  }
2132  /* correctly finished function result message */
2134  break;
2135  case 'E': /* error return */
2136  if (pqGetErrorNotice3(conn, true))
2137  continue;
2139  break;
2140  case 'A': /* notify message */
2141  /* handle notify and go back to processing return values */
2142  if (getNotify(conn))
2143  continue;
2144  break;
2145  case 'N': /* notice */
2146  /* handle notice and go back to processing return values */
2147  if (pqGetErrorNotice3(conn, false))
2148  continue;
2149  break;
2150  case 'Z': /* backend is ready for new query */
2151  if (getReadyForQuery(conn))
2152  continue;
2153  /* consume the message and exit */
2154  conn->inStart += 5 + msgLength;
2155 
2156  /*
2157  * If we already have a result object (probably an error), use
2158  * that. Otherwise, if we saw a function result message,
2159  * report COMMAND_OK. Otherwise, the backend violated the
2160  * protocol, so complain.
2161  */
2162  if (!pgHavePendingResult(conn))
2163  {
2164  if (status == PGRES_COMMAND_OK)
2165  {
2167  if (!conn->result)
2168  {
2169  libpq_append_conn_error(conn, "out of memory");
2171  }
2172  }
2173  else
2174  {
2175  libpq_append_conn_error(conn, "protocol error: no function result");
2177  }
2178  }
2179  return pqPrepareAsyncResult(conn);
2180  case 'S': /* parameter status */
2181  if (getParameterStatus(conn))
2182  continue;
2183  break;
2184  default:
2185  /* The backend violates the protocol. */
2186  libpq_append_conn_error(conn, "protocol error: id=0x%x", id);
2188  /* trust the specified message length as what to skip */
2189  conn->inStart += 5 + msgLength;
2190  return pqPrepareAsyncResult(conn);
2191  }
2192 
2193  /* trace server-to-client message */
2194  if (conn->Pfdebug)
2196 
2197  /* Completed this message, keep going */
2198  /* trust the specified message length as what to skip */
2199  conn->inStart += 5 + msgLength;
2200  needInput = false;
2201  }
2202 
2203  /*
2204  * We fall out of the loop only upon failing to read data.
2205  * conn->errorMessage has been set by pqWait or pqReadData. We want to
2206  * append it to any already-received error message.
2207  */
2209  return pqPrepareAsyncResult(conn);
2210 }
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:800
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:157
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:846
int pqReadData(PGconn *conn)
Definition: fe-misc.c:566
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:254
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:78
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:217
int pqGetnchar(char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:166
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:979
int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:352
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:203
static int getNotify(PGconn *conn)
static int getParameterStatus(PGconn *conn)
#define VALID_LONG_MESSAGE_TYPE(id)
Definition: fe-protocol3.c:36
static void handleSyncLoss(PGconn *conn, char id, int msgLength)
Definition: fe-protocol3.c:466
static int getReadyForQuery(PGconn *conn)
int pqGetErrorNotice3(PGconn *conn, bool isError)
Definition: fe-protocol3.c:865
void pqTraceOutputMessage(PGconn *conn, const char *message, bool toServer)
Definition: fe-trace.c:529
ExecStatusType
Definition: libpq-fe.h:95
@ PQ_PIPELINE_OFF
Definition: libpq-fe.h:158
#define pgHavePendingResult(conn)
Definition: libpq-int.h:877
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:224
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:422

References generate_unaccent_rules::args, Assert(), conn, getNotify(), getParameterStatus(), getReadyForQuery(), handleSyncLoss(), i, pg_conn::inBuffer, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, len, libpq_append_conn_error(), pg_conn::Pfdebug, pgHavePendingResult, PGRES_COMMAND_OK, PGRES_FATAL_ERROR, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqCheckInBufferSpace(), pqFlush(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), pqGetnchar(), PQmakeEmptyPGresult(), pqPrepareAsyncResult(), pqPutInt(), pqPutMsgEnd(), pqPutMsgStart(), pqPutnchar(), pqReadData(), pqSaveErrorResult(), pqTraceOutputMessage(), pqWait(), pg_conn::result, status(), and VALID_LONG_MESSAGE_TYPE.

Referenced by PQfn().

◆ pqGetc()

int pqGetc ( char *  result,
PGconn conn 
)

Definition at line 78 of file fe-misc.c.

79 {
80  if (conn->inCursor >= conn->inEnd)
81  return EOF;
82 
83  *result = conn->inBuffer[conn->inCursor++];
84 
85  return 0;
86 }

References conn, pg_conn::inBuffer, pg_conn::inCursor, and pg_conn::inEnd.

Referenced by getCopyDataMessage(), getCopyStart(), getReadyForQuery(), PQconnectPoll(), pqFunctionCall3(), pqGetErrorNotice3(), and pqParseInput3().

◆ pqGetCopyData3()

int pqGetCopyData3 ( PGconn conn,
char **  buffer,
int  async 
)

Definition at line 1733 of file fe-protocol3.c.

1734 {
1735  int msgLength;
1736 
1737  for (;;)
1738  {
1739  /*
1740  * Collect the next input message. To make life simpler for async
1741  * callers, we keep returning 0 until the next message is fully
1742  * available, even if it is not Copy Data.
1743  */
1744  msgLength = getCopyDataMessage(conn);
1745  if (msgLength < 0)
1746  return msgLength; /* end-of-copy or error */
1747  if (msgLength == 0)
1748  {
1749  /* Don't block if async read requested */
1750  if (async)
1751  return 0;
1752  /* Need to load more data */
1753  if (pqWait(true, false, conn) ||
1754  pqReadData(conn) < 0)
1755  return -2;
1756  continue;
1757  }
1758 
1759  /*
1760  * Drop zero-length messages (shouldn't happen anyway). Otherwise
1761  * pass the data back to the caller.
1762  */
1763  msgLength -= 4;
1764  if (msgLength > 0)
1765  {
1766  *buffer = (char *) malloc(msgLength + 1);
1767  if (*buffer == NULL)
1768  {
1769  libpq_append_conn_error(conn, "out of memory");
1770  return -2;
1771  }
1772  memcpy(*buffer, &conn->inBuffer[conn->inCursor], msgLength);
1773  (*buffer)[msgLength] = '\0'; /* Add terminating null */
1774 
1775  /* Mark message consumed */
1776  conn->inStart = conn->inCursor + msgLength;
1777 
1778  return msgLength;
1779  }
1780 
1781  /* Empty, so drop it and loop around for another */
1782  conn->inStart = conn->inCursor;
1783  }
1784 }
static int getCopyDataMessage(PGconn *conn)

References conn, getCopyDataMessage(), pg_conn::inBuffer, pg_conn::inCursor, pg_conn::inStart, libpq_append_conn_error(), malloc, pqReadData(), and pqWait().

Referenced by PQgetCopyData().

◆ pqGetErrorNotice3()

int pqGetErrorNotice3 ( PGconn conn,
bool  isError 
)

Definition at line 865 of file fe-protocol3.c.

866 {
867  PGresult *res = NULL;
868  bool have_position = false;
869  PQExpBufferData workBuf;
870  char id;
871 
872  /* If in pipeline mode, set error indicator for it */
873  if (isError && conn->pipelineStatus != PQ_PIPELINE_OFF)
875 
876  /*
877  * If this is an error message, pre-emptively clear any incomplete query
878  * result we may have. We'd just throw it away below anyway, and
879  * releasing it before collecting the error might avoid out-of-memory.
880  */
881  if (isError)
883 
884  /*
885  * Since the fields might be pretty long, we create a temporary
886  * PQExpBuffer rather than using conn->workBuffer. workBuffer is intended
887  * for stuff that is expected to be short. We shouldn't use
888  * conn->errorMessage either, since this might be only a notice.
889  */
890  initPQExpBuffer(&workBuf);
891 
892  /*
893  * Make a PGresult to hold the accumulated fields. We temporarily lie
894  * about the result status, so that PQmakeEmptyPGresult doesn't uselessly
895  * copy conn->errorMessage.
896  *
897  * NB: This allocation can fail, if you run out of memory. The rest of the
898  * function handles that gracefully, and we still try to set the error
899  * message as the connection's error message.
900  */
902  if (res)
904 
905  /*
906  * Read the fields and save into res.
907  *
908  * While at it, save the SQLSTATE in conn->last_sqlstate, and note whether
909  * we saw a PG_DIAG_STATEMENT_POSITION field.
910  */
911  for (;;)
912  {
913  if (pqGetc(&id, conn))
914  goto fail;
915  if (id == '\0')
916  break; /* terminator found */
917  if (pqGets(&workBuf, conn))
918  goto fail;
919  pqSaveMessageField(res, id, workBuf.data);
920  if (id == PG_DIAG_SQLSTATE)
921  strlcpy(conn->last_sqlstate, workBuf.data,
922  sizeof(conn->last_sqlstate));
923  else if (id == PG_DIAG_STATEMENT_POSITION)
924  have_position = true;
925  }
926 
927  /*
928  * Save the active query text, if any, into res as well; but only if we
929  * might need it for an error cursor display, which is only true if there
930  * is a PG_DIAG_STATEMENT_POSITION field.
931  */
932  if (have_position && res && conn->cmd_queue_head && conn->cmd_queue_head->query)
934 
935  /*
936  * Now build the "overall" error message for PQresultErrorMessage.
937  */
938  resetPQExpBuffer(&workBuf);
940 
941  /*
942  * Either save error as current async result, or just emit the notice.
943  */
944  if (isError)
945  {
946  pqClearAsyncResult(conn); /* redundant, but be safe */
947  if (res)
948  {
949  pqSetResultError(res, &workBuf, 0);
950  conn->result = res;
951  }
952  else
953  {
954  /* Fall back to using the internal-error processing paths */
955  conn->error_result = true;
956  }
957 
958  if (PQExpBufferDataBroken(workBuf))
959  libpq_append_conn_error(conn, "out of memory");
960  else
962  }
963  else
964  {
965  /* if we couldn't allocate the result set, just discard the NOTICE */
966  if (res)
967  {
968  /*
969  * We can cheat a little here and not copy the message. But if we
970  * were unlucky enough to run out of memory while filling workBuf,
971  * insert "out of memory", as in pqSetResultError.
972  */
973  if (PQExpBufferDataBroken(workBuf))
974  res->errMsg = libpq_gettext("out of memory\n");
975  else
976  res->errMsg = workBuf.data;
977  if (res->noticeHooks.noticeRec != NULL)
979  PQclear(res);
980  }
981  }
982 
983  termPQExpBuffer(&workBuf);
984  return 0;
985 
986 fail:
987  PQclear(res);
988  termPQExpBuffer(&workBuf);
989  return EOF;
990 }
void pqSaveMessageField(PGresult *res, char code, const char *value)
Definition: fe-exec.c:1055
void pqSetResultError(PGresult *res, PQExpBuffer errorMessage, int offset)
Definition: fe-exec.c:689
char * pqResultStrdup(PGresult *res, const char *str)
Definition: fe-exec.c:672
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:776
int pqGets(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:137
void pqBuildErrorMessage3(PQExpBuffer msg, const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
Definition: fe-protocol3.c:997
@ PGRES_EMPTY_QUERY
Definition: libpq-fe.h:96
@ PGRES_NONFATAL_ERROR
Definition: libpq-fe.h:107
@ PQ_PIPELINE_ABORTED
Definition: libpq-fe.h:160
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
PQnoticeReceiver noticeRec
Definition: libpq-int.h:154
void * noticeRecArg
Definition: libpq-int.h:155
PGVerbosity verbosity
Definition: libpq-int.h:487
char last_sqlstate[6]
Definition: libpq-int.h:418
PGContextVisibility show_context
Definition: libpq-int.h:488
PGNoticeHooks noticeHooks
Definition: libpq-int.h:188

References appendPQExpBufferStr(), pg_conn::cmd_queue_head, conn, PQExpBufferData::data, pg_result::errMsg, pg_conn::error_result, pg_conn::errorMessage, pg_result::errQuery, initPQExpBuffer(), pg_conn::last_sqlstate, libpq_append_conn_error(), libpq_gettext, pg_result::noticeHooks, PGNoticeHooks::noticeRec, PGNoticeHooks::noticeRecArg, PG_DIAG_SQLSTATE, PG_DIAG_STATEMENT_POSITION, PGRES_EMPTY_QUERY, PGRES_FATAL_ERROR, PGRES_NONFATAL_ERROR, pg_conn::pipelineStatus, PQ_PIPELINE_ABORTED, PQ_PIPELINE_OFF, pqBuildErrorMessage3(), PQclear(), pqClearAsyncResult(), PQExpBufferDataBroken, pqGetc(), pqGets(), PQmakeEmptyPGresult(), pqResultStrdup(), pqSaveMessageField(), pqSetResultError(), PGcmdQueueEntry::query, res, resetPQExpBuffer(), pg_conn::result, pg_result::resultStatus, pg_conn::show_context, strlcpy(), termPQExpBuffer(), and pg_conn::verbosity.

Referenced by getCopyDataMessage(), PQconnectPoll(), pqFunctionCall3(), and pqParseInput3().

◆ pqGetHomeDirectory()

bool pqGetHomeDirectory ( char *  buf,
int  bufsize 
)

Definition at line 7517 of file fe-connect.c.

7518 {
7519 #ifndef WIN32
7520  const char *home;
7521 
7522  home = getenv("HOME");
7523  if (home == NULL || home[0] == '\0')
7524  return pg_get_user_home_dir(geteuid(), buf, bufsize);
7525  strlcpy(buf, home, bufsize);
7526  return true;
7527 #else
7528  char tmppath[MAX_PATH];
7529 
7530  ZeroMemory(tmppath, sizeof(tmppath));
7531  if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
7532  return false;
7533  snprintf(buf, bufsize, "%s/postgresql", tmppath);
7534  return true;
7535 #endif
7536 }
#define bufsize
Definition: indent_globs.h:36
static char * buf
Definition: pg_test_fsync.c:67
bool pg_get_user_home_dir(uid_t user_id, char *buffer, size_t buflen)
Definition: thread.c:71
#define snprintf
Definition: port.h:238

References buf, bufsize, pg_get_user_home_dir(), snprintf, and strlcpy().

Referenced by connectOptions2(), initialize_SSL(), and parseServiceInfo().

◆ pqGetInt()

int pqGetInt ( int *  result,
size_t  bytes,
PGconn conn 
)

Definition at line 217 of file fe-misc.c.

218 {
219  uint16 tmp2;
220  uint32 tmp4;
221 
222  switch (bytes)
223  {
224  case 2:
225  if (conn->inCursor + 2 > conn->inEnd)
226  return EOF;
227  memcpy(&tmp2, conn->inBuffer + conn->inCursor, 2);
228  conn->inCursor += 2;
229  *result = (int) pg_ntoh16(tmp2);
230  break;
231  case 4:
232  if (conn->inCursor + 4 > conn->inEnd)
233  return EOF;
234  memcpy(&tmp4, conn->inBuffer + conn->inCursor, 4);
235  conn->inCursor += 4;
236  *result = (int) pg_ntoh32(tmp4);
237  break;
238  default:
240  "integer of size %lu not supported by pqGetInt",
241  (unsigned long) bytes);
242  return EOF;
243  }
244 
245  return 0;
246 }
unsigned short uint16
Definition: c.h:489
unsigned int uint32
Definition: c.h:490
#define pg_ntoh32(x)
Definition: pg_bswap.h:125
#define pg_ntoh16(x)
Definition: pg_bswap.h:124

References conn, pg_conn::inBuffer, pg_conn::inCursor, pg_conn::inEnd, pg_conn::noticeHooks, pg_ntoh16, pg_ntoh32, and pqInternalNotice().

Referenced by getAnotherTuple(), getCopyDataMessage(), getCopyStart(), getNotify(), getParamDescriptions(), getRowDescriptions(), PQconnectPoll(), pqFunctionCall3(), pqGetNegotiateProtocolVersion3(), and pqParseInput3().

◆ pqGetline3()

int pqGetline3 ( PGconn conn,
char *  s,
int  maxlen 
)

Definition at line 1792 of file fe-protocol3.c.

1793 {
1794  int status;
1795 
1796  if (conn->sock == PGINVALID_SOCKET ||
1800  {
1801  libpq_append_conn_error(conn, "PQgetline: not doing text COPY OUT");
1802  *s = '\0';
1803  return EOF;
1804  }
1805 
1806  while ((status = PQgetlineAsync(conn, s, maxlen - 1)) == 0)
1807  {
1808  /* need to load more data */
1809  if (pqWait(true, false, conn) ||
1810  pqReadData(conn) < 0)
1811  {
1812  *s = '\0';
1813  return EOF;
1814  }
1815  }
1816 
1817  if (status < 0)
1818  {
1819  /* End of copy detected; gin up old-style terminator */
1820  strcpy(s, "\\.");
1821  return 0;
1822  }
1823 
1824  /* Add null terminator, and strip trailing \n if present */
1825  if (s[status - 1] == '\n')
1826  {
1827  s[status - 1] = '\0';
1828  return 0;
1829  }
1830  else
1831  {
1832  s[status] = '\0';
1833  return 1;
1834  }
1835 }
int PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
Definition: fe-exec.c:2787
char copy_is_binary
Definition: libpq-int.h:424

References pg_conn::asyncStatus, conn, pg_conn::copy_is_binary, libpq_append_conn_error(), PGASYNC_COPY_BOTH, PGASYNC_COPY_OUT, PGINVALID_SOCKET, PQgetlineAsync(), pqReadData(), pqWait(), pg_conn::sock, and status().

Referenced by PQgetline().

◆ pqGetlineAsync3()

int pqGetlineAsync3 ( PGconn conn,
char *  buffer,
int  bufsize 
)

Definition at line 1843 of file fe-protocol3.c.

1844 {
1845  int msgLength;
1846  int avail;
1847 
1850  return -1; /* we are not doing a copy... */
1851 
1852  /*
1853  * Recognize the next input message. To make life simpler for async
1854  * callers, we keep returning 0 until the next message is fully available
1855  * even if it is not Copy Data. This should keep PQendcopy from blocking.
1856  * (Note: unlike pqGetCopyData3, we do not change asyncStatus here.)
1857  */
1858  msgLength = getCopyDataMessage(conn);
1859  if (msgLength < 0)
1860  return -1; /* end-of-copy or error */
1861  if (msgLength == 0)
1862  return 0; /* no data yet */
1863 
1864  /*
1865  * Move data from libpq's buffer to the caller's. In the case where a
1866  * prior call found the caller's buffer too small, we use
1867  * conn->copy_already_done to remember how much of the row was already
1868  * returned to the caller.
1869  */
1871  avail = msgLength - 4 - conn->copy_already_done;
1872  if (avail <= bufsize)
1873  {
1874  /* Able to consume the whole message */
1875  memcpy(buffer, &conn->inBuffer[conn->inCursor], avail);
1876  /* Mark message consumed */
1877  conn->inStart = conn->inCursor + avail;
1878  /* Reset state for next time */
1879  conn->copy_already_done = 0;
1880  return avail;
1881  }
1882  else
1883  {
1884  /* We must return a partial message */
1885  memcpy(buffer, &conn->inBuffer[conn->inCursor], bufsize);
1886  /* The message is NOT consumed from libpq's buffer */
1888  return bufsize;
1889  }
1890 }
int copy_already_done
Definition: libpq-int.h:425

References pg_conn::asyncStatus, bufsize, conn, pg_conn::copy_already_done, getCopyDataMessage(), pg_conn::inBuffer, pg_conn::inCursor, pg_conn::inStart, PGASYNC_COPY_BOTH, and PGASYNC_COPY_OUT.

Referenced by PQgetlineAsync().

◆ pqGetnchar()

int pqGetnchar ( char *  s,
size_t  len,
PGconn conn 
)

Definition at line 166 of file fe-misc.c.

167 {
168  if (len > (size_t) (conn->inEnd - conn->inCursor))
169  return EOF;
170 
171  memcpy(s, conn->inBuffer + conn->inCursor, len);
172  /* no terminating null */
173 
174  conn->inCursor += len;
175 
176  return 0;
177 }

References conn, pg_conn::inBuffer, pg_conn::inCursor, pg_conn::inEnd, and len.

Referenced by pg_password_sendauth(), pg_SASL_continue(), and pqFunctionCall3().

◆ pqGetNegotiateProtocolVersion3()

int pqGetNegotiateProtocolVersion3 ( PGconn conn)

Definition at line 1395 of file fe-protocol3.c.

1396 {
1397  int tmp;
1398  ProtocolVersion their_version;
1399  int num;
1401 
1402  if (pqGetInt(&tmp, 4, conn) != 0)
1403  return EOF;
1404  their_version = tmp;
1405 
1406  if (pqGetInt(&num, 4, conn) != 0)
1407  return EOF;
1408 
1409  initPQExpBuffer(&buf);
1410  for (int i = 0; i < num; i++)
1411  {
1412  if (pqGets(&conn->workBuffer, conn))
1413  {
1414  termPQExpBuffer(&buf);
1415  return EOF;
1416  }
1417  if (buf.len > 0)
1418  appendPQExpBufferChar(&buf, ' ');
1420  }
1421 
1422  if (their_version < conn->pversion)
1424  libpq_gettext("protocol version not supported by server: client uses %u.%u, server supports up to %u.%u\n"),
1426  PG_PROTOCOL_MAJOR(their_version), PG_PROTOCOL_MINOR(their_version));
1427  if (num > 0)
1429  libpq_ngettext("protocol extension not supported by server: %s\n",
1430  "protocol extensions not supported by server: %s\n", num),
1431  buf.data);
1432 
1433  /* neither -- server shouldn't have sent it */
1434  if (!(their_version < conn->pversion) && !(num > 0))
1436  libpq_gettext("invalid %s message"), "NegotiateProtocolVersion");
1437 
1438  termPQExpBuffer(&buf);
1439  return 0;
1440 }
#define libpq_ngettext(s, p, n)
Definition: libpq-int.h:896
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:75
uint32 ProtocolVersion
Definition: pqcomm.h:87
#define PG_PROTOCOL_MINOR(v)
Definition: pqcomm.h:76
ProtocolVersion pversion
Definition: libpq-int.h:453
PQExpBufferData workBuffer
Definition: libpq-int.h:605

References appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), buf, conn, PQExpBufferData::data, pg_conn::errorMessage, i, initPQExpBuffer(), libpq_gettext, libpq_ngettext, PG_PROTOCOL_MAJOR, PG_PROTOCOL_MINOR, pqGetInt(), pqGets(), pg_conn::pversion, termPQExpBuffer(), and pg_conn::workBuffer.

Referenced by PQconnectPoll().

◆ pqGets()

int pqGets ( PQExpBuffer  buf,
PGconn conn 
)

Definition at line 137 of file fe-misc.c.

138 {
139  return pqGets_internal(buf, conn, true);
140 }
static int pqGets_internal(PQExpBuffer buf, PGconn *conn, bool resetbuffer)
Definition: fe-misc.c:110

References buf, conn, and pqGets_internal().

Referenced by getNotify(), getParameterStatus(), getRowDescriptions(), pg_SASL_init(), pqGetErrorNotice3(), pqGetNegotiateProtocolVersion3(), and pqParseInput3().

◆ pqGets_append()

int pqGets_append ( PQExpBuffer  buf,
PGconn conn 
)

Definition at line 143 of file fe-misc.c.

144 {
145  return pqGets_internal(buf, conn, false);
146 }

References buf, conn, and pqGets_internal().

Referenced by PQconnectPoll().

◆ pqInternalNotice()

void pqInternalNotice ( const PGNoticeHooks hooks,
const char *  fmt,
  ... 
)

◆ pqPacketSend()

int pqPacketSend ( PGconn conn,
char  pack_type,
const void *  buf,
size_t  buf_len 
)

Definition at line 4882 of file fe-connect.c.

4884 {
4885  /* Start the message. */
4886  if (pqPutMsgStart(pack_type, conn))
4887  return STATUS_ERROR;
4888 
4889  /* Send the message body. */
4890  if (pqPutnchar(buf, buf_len, conn))
4891  return STATUS_ERROR;
4892 
4893  /* Finish the message. */
4894  if (pqPutMsgEnd(conn))
4895  return STATUS_ERROR;
4896 
4897  /* Flush to ensure backend gets it. */
4898  if (pqFlush(conn))
4899  return STATUS_ERROR;
4900 
4901  return STATUS_OK;
4902 }
#define STATUS_OK
Definition: c.h:1159
#define STATUS_ERROR
Definition: c.h:1160

References buf, conn, pqFlush(), pqPutMsgEnd(), pqPutMsgStart(), pqPutnchar(), STATUS_ERROR, and STATUS_OK.

Referenced by pg_password_sendauth(), pg_SASL_continue(), and PQconnectPoll().

◆ pqParseInput3()

void pqParseInput3 ( PGconn conn)

Definition at line 61 of file fe-protocol3.c.

62 {
63  char id;
64  int msgLength;
65  int avail;
66 
67  /*
68  * Loop to parse successive complete messages available in the buffer.
69  */
70  for (;;)
71  {
72  /*
73  * Try to read a message. First get the type code and length. Return
74  * if not enough data.
75  */
77  if (pqGetc(&id, conn))
78  return;
79  if (pqGetInt(&msgLength, 4, conn))
80  return;
81 
82  /*
83  * Try to validate message type/length here. A length less than 4 is
84  * definitely broken. Large lengths should only be believed for a few
85  * message types.
86  */
87  if (msgLength < 4)
88  {
89  handleSyncLoss(conn, id, msgLength);
90  return;
91  }
92  if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
93  {
94  handleSyncLoss(conn, id, msgLength);
95  return;
96  }
97 
98  /*
99  * Can't process if message body isn't all here yet.
100  */
101  msgLength -= 4;
102  avail = conn->inEnd - conn->inCursor;
103  if (avail < msgLength)
104  {
105  /*
106  * Before returning, enlarge the input buffer if needed to hold
107  * the whole message. This is better than leaving it to
108  * pqReadData because we can avoid multiple cycles of realloc()
109  * when the message is large; also, we can implement a reasonable
110  * recovery strategy if we are unable to make the buffer big
111  * enough.
112  */
113  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
114  conn))
115  {
116  /*
117  * XXX add some better recovery code... plan is to skip over
118  * the message using its length, then report an error. For the
119  * moment, just treat this like loss of sync (which indeed it
120  * might be!)
121  */
122  handleSyncLoss(conn, id, msgLength);
123  }
124  return;
125  }
126 
127  /*
128  * NOTIFY and NOTICE messages can happen in any state; always process
129  * them right away.
130  *
131  * Most other messages should only be processed while in BUSY state.
132  * (In particular, in READY state we hold off further parsing until
133  * the application collects the current PGresult.)
134  *
135  * However, if the state is IDLE then we got trouble; we need to deal
136  * with the unexpected message somehow.
137  *
138  * ParameterStatus ('S') messages are a special case: in IDLE state we
139  * must process 'em (this case could happen if a new value was adopted
140  * from config file due to SIGHUP), but otherwise we hold off until
141  * BUSY state.
142  */
143  if (id == 'A')
144  {
145  if (getNotify(conn))
146  return;
147  }
148  else if (id == 'N')
149  {
150  if (pqGetErrorNotice3(conn, false))
151  return;
152  }
153  else if (conn->asyncStatus != PGASYNC_BUSY)
154  {
155  /* If not IDLE state, just wait ... */
156  if (conn->asyncStatus != PGASYNC_IDLE)
157  return;
158 
159  /*
160  * Unexpected message in IDLE state; need to recover somehow.
161  * ERROR messages are handled using the notice processor;
162  * ParameterStatus is handled normally; anything else is just
163  * dropped on the floor after displaying a suitable warning
164  * notice. (An ERROR is very possibly the backend telling us why
165  * it is about to close the connection, so we don't want to just
166  * discard it...)
167  */
168  if (id == 'E')
169  {
170  if (pqGetErrorNotice3(conn, false /* treat as notice */ ))
171  return;
172  }
173  else if (id == 'S')
174  {
176  return;
177  }
178  else
179  {
180  /* Any other case is unexpected and we summarily skip it */
182  "message type 0x%02x arrived from server while idle",
183  id);
184  /* Discard the unexpected message */
185  conn->inCursor += msgLength;
186  }
187  }
188  else
189  {
190  /*
191  * In BUSY state, we can process everything.
192  */
193  switch (id)
194  {
195  case 'C': /* command complete */
196  if (pqGets(&conn->workBuffer, conn))
197  return;
199  {
202  if (!conn->result)
203  {
204  libpq_append_conn_error(conn, "out of memory");
206  }
207  }
208  if (conn->result)
210  CMDSTATUS_LEN);
212  break;
213  case 'E': /* error return */
214  if (pqGetErrorNotice3(conn, true))
215  return;
217  break;
218  case 'Z': /* sync response, backend is ready for new
219  * query */
220  if (getReadyForQuery(conn))
221  return;
223  {
226  if (!conn->result)
227  {
228  libpq_append_conn_error(conn, "out of memory");
230  }
231  else
232  {
235  }
236  }
237  else
238  {
239  /*
240  * In simple query protocol, advance the command queue
241  * (see PQgetResult).
242  */
243  if (conn->cmd_queue_head &&
247  }
248  break;
249  case 'I': /* empty query */
251  {
254  if (!conn->result)
255  {
256  libpq_append_conn_error(conn, "out of memory");
258  }
259  }
261  break;
262  case '1': /* Parse Complete */
263  /* If we're doing PQprepare, we're done; else ignore */
264  if (conn->cmd_queue_head &&
266  {
268  {
271  if (!conn->result)
272  {
273  libpq_append_conn_error(conn, "out of memory");
275  }
276  }
278  }
279  break;
280  case '2': /* Bind Complete */
281  case '3': /* Close Complete */
282  /* Nothing to do for these message types */
283  break;
284  case 'S': /* parameter status */
286  return;
287  break;
288  case 'K': /* secret key data from the backend */
289 
290  /*
291  * This is expected only during backend startup, but it's
292  * just as easy to handle it as part of the main loop.
293  * Save the data and continue processing.
294  */
295  if (pqGetInt(&(conn->be_pid), 4, conn))
296  return;
297  if (pqGetInt(&(conn->be_key), 4, conn))
298  return;
299  break;
300  case 'T': /* Row Description */
301  if (conn->error_result ||
302  (conn->result != NULL &&
304  {
305  /*
306  * We've already choked for some reason. Just discard
307  * the data till we get to the end of the query.
308  */
309  conn->inCursor += msgLength;
310  }
311  else if (conn->result == NULL ||
312  (conn->cmd_queue_head &&
314  {
315  /* First 'T' in a query sequence */
316  if (getRowDescriptions(conn, msgLength))
317  return;
318  }
319  else
320  {
321  /*
322  * A new 'T' message is treated as the start of
323  * another PGresult. (It is not clear that this is
324  * really possible with the current backend.) We stop
325  * parsing until the application accepts the current
326  * result.
327  */
329  return;
330  }
331  break;
332  case 'n': /* No Data */
333 
334  /*
335  * NoData indicates that we will not be seeing a
336  * RowDescription message because the statement or portal
337  * inquired about doesn't return rows.
338  *
339  * If we're doing a Describe, we have to pass something
340  * back to the client, so set up a COMMAND_OK result,
341  * instead of PGRES_TUPLES_OK. Otherwise we can just
342  * ignore this message.
343  */
344  if (conn->cmd_queue_head &&
346  {
348  {
351  if (!conn->result)
352  {
353  libpq_append_conn_error(conn, "out of memory");
355  }
356  }
358  }
359  break;
360  case 't': /* Parameter Description */
361  if (getParamDescriptions(conn, msgLength))
362  return;
363  break;
364  case 'D': /* Data Row */
365  if (conn->result != NULL &&
367  {
368  /* Read another tuple of a normal query response */
369  if (getAnotherTuple(conn, msgLength))
370  return;
371  }
372  else if (conn->error_result ||
373  (conn->result != NULL &&
375  {
376  /*
377  * We've already choked for some reason. Just discard
378  * tuples till we get to the end of the query.
379  */
380  conn->inCursor += msgLength;
381  }
382  else
383  {
384  /* Set up to report error at end of query */
385  libpq_append_conn_error(conn, "server sent data (\"D\" message) without prior row description (\"T\" message)");
387  /* Discard the unexpected message */
388  conn->inCursor += msgLength;
389  }
390  break;
391  case 'G': /* Start Copy In */
393  return;
395  break;
396  case 'H': /* Start Copy Out */
398  return;
400  conn->copy_already_done = 0;
401  break;
402  case 'W': /* Start Copy Both */
404  return;
406  conn->copy_already_done = 0;
407  break;
408  case 'd': /* Copy Data */
409 
410  /*
411  * If we see Copy Data, just silently drop it. This would
412  * only occur if application exits COPY OUT mode too
413  * early.
414  */
415  conn->inCursor += msgLength;
416  break;
417  case 'c': /* Copy Done */
418 
419  /*
420  * If we see Copy Done, just silently drop it. This is
421  * the normal case during PQendcopy. We will keep
422  * swallowing data, expecting to see command-complete for
423  * the COPY command.
424  */
425  break;
426  default:
427  libpq_append_conn_error(conn, "unexpected response from server; first received character was \"%c\"", id);
428  /* build an error result holding the error message */
430  /* not sure if we will see more, so go to ready state */
432  /* Discard the unexpected message */
433  conn->inCursor += msgLength;
434  break;
435  } /* switch on protocol character */
436  }
437  /* Successfully consumed this message */
438  if (conn->inCursor == conn->inStart + 5 + msgLength)
439  {
440  /* trace server-to-client message */
441  if (conn->Pfdebug)
443 
444  /* Normal case: parsing agrees with specified length */
446  }
447  else
448  {
449  /* Trouble --- report it */
450  libpq_append_conn_error(conn, "message contents do not agree with length in message type \"%c\"", id);
451  /* build an error result holding the error message */
454  /* trust the specified message length as what to skip */
455  conn->inStart += 5 + msgLength;
456  }
457  }
458 }
void pqCommandQueueAdvance(PGconn *conn)
Definition: fe-exec.c:3015
static int getAnotherTuple(PGconn *conn, int msgLength)
Definition: fe-protocol3.c:745
static int getRowDescriptions(PGconn *conn, int msgLength)
Definition: fe-protocol3.c:486
static int getCopyStart(PGconn *conn, ExecStatusType copytype)
static int getParamDescriptions(PGconn *conn, int msgLength)
Definition: fe-protocol3.c:657
@ PGRES_COPY_IN
Definition: libpq-fe.h:104
@ PGRES_COPY_BOTH
Definition: libpq-fe.h:109
@ PGRES_COPY_OUT
Definition: libpq-fe.h:103
@ PGRES_PIPELINE_SYNC
Definition: libpq-fe.h:111
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:100
@ PQ_PIPELINE_ON
Definition: libpq-fe.h:159
#define CMDSTATUS_LEN
Definition: libpq-int.h:88
int be_pid
Definition: libpq-int.h:480
int be_key
Definition: libpq-int.h:481
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:180

References pg_conn::asyncStatus, pg_conn::be_key, pg_conn::be_pid, pg_conn::cmd_queue_head, pg_result::cmdStatus, CMDSTATUS_LEN, conn, pg_conn::copy_already_done, PQExpBufferData::data, pg_conn::error_result, getAnotherTuple(), getCopyStart(), getNotify(), getParamDescriptions(), getParameterStatus(), getReadyForQuery(), getRowDescriptions(), handleSyncLoss(), pg_conn::inBuffer, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, libpq_append_conn_error(), pg_conn::noticeHooks, pg_conn::Pfdebug, PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGASYNC_IDLE, PGASYNC_READY, pgHavePendingResult, PGQUERY_DESCRIBE, PGQUERY_PREPARE, PGQUERY_SIMPLE, PGRES_COMMAND_OK, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PGRES_EMPTY_QUERY, PGRES_FATAL_ERROR, PGRES_PIPELINE_SYNC, PGRES_TUPLES_OK, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, PQ_PIPELINE_ON, pqCheckInBufferSpace(), pqCommandQueueAdvance(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), pqGets(), pqInternalNotice(), PQmakeEmptyPGresult(), pqSaveErrorResult(), pqTraceOutputMessage(), PGcmdQueueEntry::queryclass, pg_conn::result, pg_result::resultStatus, strlcpy(), VALID_LONG_MESSAGE_TYPE, and pg_conn::workBuffer.

Referenced by parseInput().

◆ pqPrepareAsyncResult()

PGresult* pqPrepareAsyncResult ( PGconn conn)

Definition at line 846 of file fe-exec.c.

847 {
848  PGresult *res;
849 
850  res = conn->result;
851  if (res)
852  {
853  /*
854  * If the pre-existing result is an ERROR (presumably something
855  * received from the server), assume that it represents whatever is in
856  * conn->errorMessage, and advance errorReported.
857  */
860  }
861  else
862  {
863  /*
864  * We get here after internal-to-libpq errors. We should probably
865  * always have error_result = true, but if we don't, gin up some error
866  * text.
867  */
868  if (!conn->error_result)
869  libpq_append_conn_error(conn, "no error text available");
870 
871  /* Paranoia: be sure errorReported offset is sane */
872  if (conn->errorReported < 0 ||
874  conn->errorReported = 0;
875 
876  /*
877  * Make a PGresult struct for the error. We temporarily lie about the
878  * result status, so that PQmakeEmptyPGresult doesn't uselessly copy
879  * all of conn->errorMessage.
880  */
882  if (res)
883  {
884  /*
885  * Report whatever new error text we have, and advance
886  * errorReported.
887  */
891  }
892  else
893  {
894  /*
895  * Ouch, not enough memory for a PGresult. Fortunately, we have a
896  * card up our sleeve: we can use the static OOM_result. Casting
897  * away const here is a bit ugly, but it seems best to declare
898  * OOM_result as const, in hopes it will be allocated in read-only
899  * storage.
900  */
902 
903  /*
904  * Don't advance errorReported. Perhaps we'll be able to report
905  * the text later.
906  */
907  }
908  }
909 
910  /*
911  * Replace conn->result with next_result, if any. In the normal case
912  * there isn't a next result and we're just dropping ownership of the
913  * current result. In single-row mode this restores the situation to what
914  * it was before we created the current single-row result.
915  */
917  conn->error_result = false; /* next_result is never an error */
918  conn->next_result = NULL;
919 
920  return res;
921 }
#define unconstify(underlying_type, expr)
Definition: c.h:1232
static const PGresult OOM_result
Definition: fe-exec.c:48
int errorReported
Definition: libpq-int.h:602

References conn, pg_conn::error_result, pg_conn::errorMessage, pg_conn::errorReported, PQExpBufferData::len, libpq_append_conn_error(), pg_conn::next_result, OOM_result, PGRES_EMPTY_QUERY, PGRES_FATAL_ERROR, PQmakeEmptyPGresult(), pqSetResultError(), res, pg_conn::result, pg_result::resultStatus, and unconstify.

Referenced by getCopyResult(), pqFunctionCall3(), and PQgetResult().

◆ pqPutc()

int pqPutc ( char  c,
PGconn conn 
)

Definition at line 93 of file fe-misc.c.

94 {
95  if (pqPutMsgBytes(&c, 1, conn))
96  return EOF;
97 
98  return 0;
99 }
static int pqPutMsgBytes(const void *buf, size_t len, PGconn *conn)
Definition: fe-misc.c:495
char * c

References conn, and pqPutMsgBytes().

Referenced by PQsendDescribe(), and PQsendQueryGuts().

◆ pqPutInt()

int pqPutInt ( int  value,
size_t  bytes,
PGconn conn 
)

Definition at line 254 of file fe-misc.c.

255 {
256  uint16 tmp2;
257  uint32 tmp4;
258 
259  switch (bytes)
260  {
261  case 2:
262  tmp2 = pg_hton16((uint16) value);
263  if (pqPutMsgBytes((const char *) &tmp2, 2, conn))
264  return EOF;
265  break;
266  case 4:
267  tmp4 = pg_hton32((uint32) value);
268  if (pqPutMsgBytes((const char *) &tmp4, 4, conn))
269  return EOF;
270  break;
271  default:
273  "integer of size %lu not supported by pqPutInt",
274  (unsigned long) bytes);
275  return EOF;
276  }
277 
278  return 0;
279 }
static struct @145 value
#define pg_hton32(x)
Definition: pg_bswap.h:121
#define pg_hton16(x)
Definition: pg_bswap.h:120

References conn, pg_conn::noticeHooks, pg_hton16, pg_hton32, pqInternalNotice(), pqPutMsgBytes(), and value.

Referenced by pg_SASL_init(), pqFunctionCall3(), PQsendPrepare(), and PQsendQueryGuts().

◆ pqPutMsgEnd()

int pqPutMsgEnd ( PGconn conn)

Definition at line 518 of file fe-misc.c.

519 {
520  /* Fill in length word if needed */
521  if (conn->outMsgStart >= 0)
522  {
523  uint32 msgLen = conn->outMsgEnd - conn->outMsgStart;
524 
525  msgLen = pg_hton32(msgLen);
526  memcpy(conn->outBuffer + conn->outMsgStart, &msgLen, 4);
527  }
528 
529  /* trace client-to-server message */
530  if (conn->Pfdebug)
531  {
532  if (conn->outCount < conn->outMsgStart)
534  else
537  }
538 
539  /* Make message eligible to send */
541 
542  if (conn->outCount >= 8192)
543  {
544  int toSend = conn->outCount - (conn->outCount % 8192);
545 
546  if (pqSendSome(conn, toSend) < 0)
547  return EOF;
548  /* in nonblock mode, don't complain if unable to send it all */
549  }
550 
551  return 0;
552 }
void pqTraceOutputNoTypeByteMessage(PGconn *conn, const char *message)
Definition: fe-trace.c:694
int outMsgStart
Definition: libpq-int.h:504
int outMsgEnd
Definition: libpq-int.h:506

References conn, pg_conn::outBuffer, pg_conn::outCount, pg_conn::outMsgEnd, pg_conn::outMsgStart, pg_conn::Pfdebug, pg_hton32, pqSendSome(), pqTraceOutputMessage(), and pqTraceOutputNoTypeByteMessage().

Referenced by pg_SASL_init(), pqEndcopy3(), pqFunctionCall3(), pqPacketSend(), PQpipelineSync(), PQputCopyData(), PQputCopyEnd(), PQsendDescribe(), PQsendFlushRequest(), PQsendPrepare(), PQsendQueryGuts(), PQsendQueryInternal(), and sendTerminateConn().

◆ pqPutMsgStart()

int pqPutMsgStart ( char  msg_type,
PGconn conn 
)

Definition at line 459 of file fe-misc.c.

460 {
461  int lenPos;
462  int endPos;
463 
464  /* allow room for message type byte */
465  if (msg_type)
466  endPos = conn->outCount + 1;
467  else
468  endPos = conn->outCount;
469 
470  /* do we want a length word? */
471  lenPos = endPos;
472  /* allow room for message length */
473  endPos += 4;
474 
475  /* make sure there is room for message header */
476  if (pqCheckOutBufferSpace(endPos, conn))
477  return EOF;
478  /* okay, save the message type byte if any */
479  if (msg_type)
480  conn->outBuffer[conn->outCount] = msg_type;
481  /* set up the message pointers */
482  conn->outMsgStart = lenPos;
483  conn->outMsgEnd = endPos;
484  /* length word, if needed, will be filled in by pqPutMsgEnd */
485 
486  return 0;
487 }
int pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:288

References conn, pg_conn::outBuffer, pg_conn::outCount, pg_conn::outMsgEnd, pg_conn::outMsgStart, and pqCheckOutBufferSpace().

Referenced by pg_SASL_init(), pqEndcopy3(), pqFunctionCall3(), pqPacketSend(), PQpipelineSync(), PQputCopyData(), PQputCopyEnd(), PQsendDescribe(), PQsendFlushRequest(), PQsendPrepare(), PQsendQueryGuts(), PQsendQueryInternal(), and sendTerminateConn().

◆ pqPutnchar()

int pqPutnchar ( const char *  s,
size_t  len,
PGconn conn 
)

Definition at line 203 of file fe-misc.c.

204 {
205  if (pqPutMsgBytes(s, len, conn))
206  return EOF;
207 
208  return 0;
209 }

References conn, len, and pqPutMsgBytes().

Referenced by pg_SASL_init(), pqFunctionCall3(), pqPacketSend(), PQputCopyData(), and PQsendQueryGuts().

◆ pqPuts()

int pqPuts ( const char *  s,
PGconn conn 
)

Definition at line 153 of file fe-misc.c.

154 {
155  if (pqPutMsgBytes(s, strlen(s) + 1, conn))
156  return EOF;
157 
158  return 0;
159 }

References conn, and pqPutMsgBytes().

Referenced by pg_SASL_init(), PQputCopyEnd(), PQsendDescribe(), PQsendPrepare(), PQsendQueryGuts(), and PQsendQueryInternal().

◆ pqReadData()

int pqReadData ( PGconn conn)

Definition at line 566 of file fe-misc.c.

567 {
568  int someread = 0;
569  int nread;
570 
571  if (conn->sock == PGINVALID_SOCKET)
572  {
573  libpq_append_conn_error(conn, "connection not open");
574  return -1;
575  }
576 
577  /* Left-justify any data in the buffer to make room */
578  if (conn->inStart < conn->inEnd)
579  {
580  if (conn->inStart > 0)
581  {
582  memmove(conn->inBuffer, conn->inBuffer + conn->inStart,
583  conn->inEnd - conn->inStart);
584  conn->inEnd -= conn->inStart;
585  conn->inCursor -= conn->inStart;
586  conn->inStart = 0;
587  }
588  }
589  else
590  {
591  /* buffer is logically empty, reset it */
592  conn->inStart = conn->inCursor = conn->inEnd = 0;
593  }
594 
595  /*
596  * If the buffer is fairly full, enlarge it. We need to be able to enlarge
597  * the buffer in case a single message exceeds the initial buffer size. We
598  * enlarge before filling the buffer entirely so as to avoid asking the
599  * kernel for a partial packet. The magic constant here should be large
600  * enough for a TCP packet or Unix pipe bufferload. 8K is the usual pipe
601  * buffer size, so...
602  */
603  if (conn->inBufSize - conn->inEnd < 8192)
604  {
605  if (pqCheckInBufferSpace(conn->inEnd + (size_t) 8192, conn))
606  {
607  /*
608  * We don't insist that the enlarge worked, but we need some room
609  */
610  if (conn->inBufSize - conn->inEnd < 100)
611  return -1; /* errorMessage already set */
612  }
613  }
614 
615  /* OK, try to read some data */
616 retry3:
617  nread = pqsecure_read(conn, conn->inBuffer + conn->inEnd,
618  conn->inBufSize - conn->inEnd);
619  if (nread < 0)
620  {
621  switch (SOCK_ERRNO)
622  {
623  case EINTR:
624  goto retry3;
625 
626  /* Some systems return EAGAIN/EWOULDBLOCK for no data */
627 #ifdef EAGAIN
628  case EAGAIN:
629  return someread;
630 #endif
631 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
632  case EWOULDBLOCK:
633  return someread;
634 #endif
635 
636  /* We might get ECONNRESET etc here if connection failed */
638  goto definitelyFailed;
639 
640  default:
641  /* pqsecure_read set the error message for us */
642  return -1;
643  }
644  }
645  if (nread > 0)
646  {
647  conn->inEnd += nread;
648 
649  /*
650  * Hack to deal with the fact that some kernels will only give us back
651  * 1 packet per recv() call, even if we asked for more and there is
652  * more available. If it looks like we are reading a long message,
653  * loop back to recv() again immediately, until we run out of data or
654  * buffer space. Without this, the block-and-restart behavior of
655  * libpq's higher levels leads to O(N^2) performance on long messages.
656  *
657  * Since we left-justified the data above, conn->inEnd gives the
658  * amount of data already read in the current message. We consider
659  * the message "long" once we have acquired 32k ...
660  */
661  if (conn->inEnd > 32768 &&
662  (conn->inBufSize - conn->inEnd) >= 8192)
663  {
664  someread = 1;
665  goto retry3;
666  }
667  return 1;
668  }
669 
670  if (someread)
671  return 1; /* got a zero read after successful tries */
672 
673  /*
674  * A return value of 0 could mean just that no data is now available, or
675  * it could mean EOF --- that is, the server has closed the connection.
676  * Since we have the socket in nonblock mode, the only way to tell the
677  * difference is to see if select() is saying that the file is ready.
678  * Grumble. Fortunately, we don't expect this path to be taken much,
679  * since in normal practice we should not be trying to read data unless
680  * the file selected for reading already.
681  *
682  * In SSL mode it's even worse: SSL_read() could say WANT_READ and then
683  * data could arrive before we make the pqReadReady() test, but the second
684  * SSL_read() could still say WANT_READ because the data received was not
685  * a complete SSL record. So we must play dumb and assume there is more
686  * data, relying on the SSL layer to detect true EOF.
687  */
688 
689 #ifdef USE_SSL
690  if (conn->ssl_in_use)
691  return 0;
692 #endif
693 
694  switch (pqReadReady(conn))
695  {
696  case 0:
697  /* definitely no data available */
698  return 0;
699  case 1:
700  /* ready for read */
701  break;
702  default:
703  /* we override pqReadReady's message with something more useful */
704  goto definitelyEOF;
705  }
706 
707  /*
708  * Still not sure that it's EOF, because some data could have just
709  * arrived.
710  */
711 retry4:
712  nread = pqsecure_read(conn, conn->inBuffer + conn->inEnd,
713  conn->inBufSize - conn->inEnd);
714  if (nread < 0)
715  {
716  switch (SOCK_ERRNO)
717  {
718  case EINTR:
719  goto retry4;
720 
721  /* Some systems return EAGAIN/EWOULDBLOCK for no data */
722 #ifdef EAGAIN
723  case EAGAIN:
724  return 0;
725 #endif
726 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
727  case EWOULDBLOCK:
728  return 0;
729 #endif
730 
731  /* We might get ECONNRESET etc here if connection failed */
733  goto definitelyFailed;
734 
735  default:
736  /* pqsecure_read set the error message for us */
737  return -1;
738  }
739  }
740  if (nread > 0)
741  {
742  conn->inEnd += nread;
743  return 1;
744  }
745 
746  /*
747  * OK, we are getting a zero read even though select() says ready. This
748  * means the connection has been closed. Cope.
749  */
750 definitelyEOF:
751  libpq_append_conn_error(conn, "server closed the connection unexpectedly\n"
752  "\tThis probably means the server terminated abnormally\n"
753  "\tbefore or while processing the request.");
754 
755  /* Come here if lower-level code already set a suitable errorMessage */
756 definitelyFailed:
757  /* Do *not* drop any already-read data; caller still wants it */
758  pqDropConnection(conn, false);
759  conn->status = CONNECTION_BAD; /* No more connection to backend */
760  return -1;
761 }
void pqDropConnection(PGconn *conn, bool flushInput)
Definition: fe-connect.c:456
int pqReadReady(PGconn *conn)
Definition: fe-misc.c:1015
ssize_t pqsecure_read(PGconn *conn, void *ptr, size_t len)
Definition: fe-secure.c:204
@ CONNECTION_BAD
Definition: libpq-fe.h:61
#define ALL_CONNECTION_FAILURE_ERRNOS
Definition: port.h:121
ConnStatusType status
Definition: libpq-int.h:415
#define EINTR
Definition: win32_port.h:376
#define EWOULDBLOCK
Definition: win32_port.h:382
#define EAGAIN
Definition: win32_port.h:374

References ALL_CONNECTION_FAILURE_ERRNOS, conn, CONNECTION_BAD, EAGAIN, EINTR, EWOULDBLOCK, pg_conn::inBuffer, pg_conn::inBufSize, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, libpq_append_conn_error(), PGINVALID_SOCKET, pqCheckInBufferSpace(), pqDropConnection(), pqReadReady(), pqsecure_read(), pg_conn::sock, SOCK_ERRNO, pg_conn::ssl_in_use, and pg_conn::status.

Referenced by PQconnectPoll(), PQconsumeInput(), pqFunctionCall3(), pqGetCopyData3(), pqGetline3(), PQgetResult(), and pqSendSome().

◆ pqReadReady()

int pqReadReady ( PGconn conn)

Definition at line 1015 of file fe-misc.c.

1016 {
1017  return pqSocketCheck(conn, 1, 0, (time_t) 0);
1018 }
static int pqSocketCheck(PGconn *conn, int forRead, int forWrite, time_t end_time)
Definition: fe-misc.c:1039

References conn, and pqSocketCheck().

Referenced by gss_read(), and pqReadData().

◆ pqResultAlloc()

void* pqResultAlloc ( PGresult res,
size_t  nBytes,
bool  isBinary 
)

Definition at line 560 of file fe-exec.c.

561 {
562  char *space;
563  PGresult_data *block;
564 
565  if (!res)
566  return NULL;
567 
568  if (nBytes <= 0)
569  return res->null_field;
570 
571  /*
572  * If alignment is needed, round up the current position to an alignment
573  * boundary.
574  */
575  if (isBinary)
576  {
577  int offset = res->curOffset % PGRESULT_ALIGN_BOUNDARY;
578 
579  if (offset)
580  {
583  }
584  }
585 
586  /* If there's enough space in the current block, no problem. */
587  if (nBytes <= (size_t) res->spaceLeft)
588  {
589  space = res->curBlock->space + res->curOffset;
590  res->curOffset += nBytes;
591  res->spaceLeft -= nBytes;
592  return space;
593  }
594 
595  /*
596  * If the requested object is very large, give it its own block; this
597  * avoids wasting what might be most of the current block to start a new
598  * block. (We'd have to special-case requests bigger than the block size
599  * anyway.) The object is always given binary alignment in this case.
600  */
601  if (nBytes >= PGRESULT_SEP_ALLOC_THRESHOLD)
602  {
603  size_t alloc_size = nBytes + PGRESULT_BLOCK_OVERHEAD;
604 
605  block = (PGresult_data *) malloc(alloc_size);
606  if (!block)
607  return NULL;
608  res->memorySize += alloc_size;
609  space = block->space + PGRESULT_BLOCK_OVERHEAD;
610  if (res->curBlock)
611  {
612  /*
613  * Tuck special block below the active block, so that we don't
614  * have to waste the free space in the active block.
615  */
616  block->next = res->curBlock->next;
617  res->curBlock->next = block;
618  }
619  else
620  {
621  /* Must set up the new block as the first active block. */
622  block->next = NULL;
623  res->curBlock = block;
624  res->spaceLeft = 0; /* be sure it's marked full */
625  }
626  return space;
627  }
628 
629  /* Otherwise, start a new block. */
631  if (!block)
632  return NULL;
634  block->next = res->curBlock;
635  res->curBlock = block;
636  if (isBinary)
637  {
638  /* object needs full alignment */
641  }
642  else
643  {
644  /* we can cram it right after the overhead pointer */
645  res->curOffset = sizeof(PGresult_data);
647  }
648 
649  space = block->space + res->curOffset;
650  res->curOffset += nBytes;
651  res->spaceLeft -= nBytes;
652  return space;
653 }
#define PGRESULT_DATA_BLOCKSIZE
Definition: fe-exec.c:140
#define PGRESULT_BLOCK_OVERHEAD
Definition: fe-exec.c:142
#define PGRESULT_SEP_ALLOC_THRESHOLD
Definition: fe-exec.c:143
#define PGRESULT_ALIGN_BOUNDARY
Definition: fe-exec.c:141
union pgresult_data PGresult_data
Definition: libpq-int.h:103
size_t memorySize
Definition: libpq-int.h:214
int curOffset
Definition: libpq-int.h:211
char null_field[1]
Definition: libpq-int.h:203
int spaceLeft
Definition: libpq-int.h:212
PGresult_data * curBlock
Definition: libpq-int.h:210
PGresult_data * next
Definition: libpq-int.h:107
char space[1]
Definition: libpq-int.h:108

References pg_result::curBlock, pg_result::curOffset, malloc, pg_result::memorySize, pgresult_data::next, pg_result::null_field, PGRESULT_ALIGN_BOUNDARY, PGRESULT_BLOCK_OVERHEAD, PGRESULT_DATA_BLOCKSIZE, PGRESULT_SEP_ALLOC_THRESHOLD, res, pgresult_data::space, and pg_result::spaceLeft.

Referenced by getCopyStart(), getParamDescriptions(), getRowDescriptions(), pqInternalNotice(), PQresultAlloc(), pqResultStrdup(), pqRowProcessor(), pqSaveMessageField(), and PQsetvalue().

◆ pqResultStrdup()

char* pqResultStrdup ( PGresult res,
const char *  str 
)

Definition at line 672 of file fe-exec.c.

673 {
674  char *space = (char *) pqResultAlloc(res, strlen(str) + 1, false);
675 
676  if (space)
677  strcpy(space, str);
678  return space;
679 }
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:560

References pqResultAlloc(), res, and generate_unaccent_rules::str.

Referenced by getRowDescriptions(), pqGetErrorNotice3(), PQsetResultAttrs(), and pqSetResultError().

◆ pqRowProcessor()

int pqRowProcessor ( PGconn conn,
const char **  errmsgp 
)

Definition at line 1206 of file fe-exec.c.

1207 {
1208  PGresult *res = conn->result;
1209  int nfields = res->numAttributes;
1210  const PGdataValue *columns = conn->rowBuf;
1211  PGresAttValue *tup;
1212  int i;
1213 
1214  /*
1215  * In single-row mode, make a new PGresult that will hold just this one
1216  * row; the original conn->result is left unchanged so that it can be used
1217  * again as the template for future rows.
1218  */
1219  if (conn->singleRowMode)
1220  {
1221  /* Copy everything that should be in the result at this point */
1222  res = PQcopyResult(res,
1225  if (!res)
1226  return 0;
1227  }
1228 
1229  /*
1230  * Basically we just allocate space in the PGresult for each field and
1231  * copy the data over.
1232  *
1233  * Note: on malloc failure, we return 0 leaving *errmsgp still NULL, which
1234  * caller will take to mean "out of memory". This is preferable to trying
1235  * to set up such a message here, because evidently there's not enough
1236  * memory for gettext() to do anything.
1237  */
1238  tup = (PGresAttValue *)
1239  pqResultAlloc(res, nfields * sizeof(PGresAttValue), true);
1240  if (tup == NULL)
1241  goto fail;
1242 
1243  for (i = 0; i < nfields; i++)
1244  {
1245  int clen = columns[i].len;
1246 
1247  if (clen < 0)
1248  {
1249  /* null field */
1250  tup[i].len = NULL_LEN;
1251  tup[i].value = res->null_field;
1252  }
1253  else
1254  {
1255  bool isbinary = (res->attDescs[i].format != 0);
1256  char *val;
1257 
1258  val = (char *) pqResultAlloc(res, clen + 1, isbinary);
1259  if (val == NULL)
1260  goto fail;
1261 
1262  /* copy and zero-terminate the data (even if it's binary) */
1263  memcpy(val, columns[i].value, clen);
1264  val[clen] = '\0';
1265 
1266  tup[i].len = clen;
1267  tup[i].value = val;
1268  }
1269  }
1270 
1271  /* And add the tuple to the PGresult's tuple array */
1272  if (!pqAddTuple(res, tup, errmsgp))
1273  goto fail;
1274 
1275  /*
1276  * Success. In single-row mode, make the result available to the client
1277  * immediately.
1278  */
1279  if (conn->singleRowMode)
1280  {
1281  /* Change result status to special single-row value */
1283  /* Stash old result for re-use later */
1285  conn->result = res;
1286  /* And mark the result ready to return */
1288  }
1289 
1290  return 1;
1291 
1292 fail:
1293  /* release locally allocated PGresult, if we made one */
1294  if (res != conn->result)
1295  PQclear(res);
1296  return 0;
1297 }
PGresult * PQcopyResult(const PGresult *src, int flags)
Definition: fe-exec.c:315
static bool pqAddTuple(PGresult *res, PGresAttValue *tup, const char **errmsgp)
Definition: fe-exec.c:988
@ PGRES_SINGLE_TUPLE
Definition: libpq-fe.h:110
#define PG_COPYRES_ATTRS
Definition: libpq-fe.h:45
#define PG_COPYRES_EVENTS
Definition: libpq-fe.h:47
#define PG_COPYRES_NOTICEHOOKS
Definition: libpq-fe.h:48
#define NULL_LEN
Definition: libpq-int.h:135
PGdataValue * rowBuf
Definition: libpq-int.h:509
bool singleRowMode
Definition: libpq-int.h:423
PGresAttDesc * attDescs
Definition: libpq-int.h:173
int numAttributes
Definition: libpq-int.h:172
char * value
Definition: libpq-int.h:140

References pg_conn::asyncStatus, pg_result::attDescs, conn, pgresAttDesc::format, i, pgresAttValue::len, pgDataValue::len, pg_conn::next_result, pg_result::null_field, NULL_LEN, pg_result::numAttributes, PG_COPYRES_ATTRS, PG_COPYRES_EVENTS, PG_COPYRES_NOTICEHOOKS, PGASYNC_READY_MORE, PGRES_SINGLE_TUPLE, pqAddTuple(), PQclear(), PQcopyResult(), pqResultAlloc(), res, pg_conn::result, pg_result::resultStatus, pg_conn::rowBuf, pg_conn::singleRowMode, val, value, and pgresAttValue::value.

Referenced by getAnotherTuple().

◆ pqSaveErrorResult()

void pqSaveErrorResult ( PGconn conn)

Definition at line 800 of file fe-exec.c.

801 {
802  /* Drop any pending result ... */
804  /* ... and set flag to remember to make an error result later */
805  conn->error_result = true;
806 }

References conn, pg_conn::error_result, and pqClearAsyncResult().

Referenced by getAnotherTuple(), getCopyResult(), getParamDescriptions(), getRowDescriptions(), handleSyncLoss(), pqFunctionCall3(), PQgetResult(), pqParseInput3(), pqPipelineProcessQueue(), and pqSaveWriteError().

◆ pqSaveMessageField()

void void pqSaveMessageField ( PGresult res,
char  code,
const char *  value 
)

Definition at line 1055 of file fe-exec.c.

1056 {
1057  PGMessageField *pfield;
1058 
1059  pfield = (PGMessageField *)
1061  offsetof(PGMessageField, contents) +
1062  strlen(value) + 1,
1063  true);
1064  if (!pfield)
1065  return; /* out of memory? */
1066  pfield->code = code;
1067  strcpy(pfield->contents, value);
1068  pfield->next = res->errFields;
1069  res->errFields = pfield;
1070 }
struct pgMessageField * next
Definition: libpq-int.h:146
char contents[FLEXIBLE_ARRAY_MEMBER]
Definition: libpq-int.h:148

References pgMessageField::code, pgMessageField::contents, pg_result::errFields, pgMessageField::next, pqResultAlloc(), res, and value.

Referenced by pqGetErrorNotice3(), and pqInternalNotice().

◆ pqSaveParameterStatus()

void pqSaveParameterStatus ( PGconn conn,
const char *  name,
const char *  value 
)

Definition at line 1076 of file fe-exec.c.

1077 {
1078  pgParameterStatus *pstatus;
1079  pgParameterStatus *prev;
1080 
1081  /*
1082  * Forget any old information about the parameter
1083  */
1084  for (pstatus = conn->pstatus, prev = NULL;
1085  pstatus != NULL;
1086  prev = pstatus, pstatus = pstatus->next)
1087  {
1088  if (strcmp(pstatus->name, name) == 0)
1089  {
1090  if (prev)
1091  prev->next = pstatus->next;
1092  else
1093  conn->pstatus = pstatus->next;
1094  free(pstatus); /* frees name and value strings too */
1095  break;
1096  }
1097  }
1098 
1099  /*
1100  * Store new info as a single malloc block
1101  */
1102  pstatus = (pgParameterStatus *) malloc(sizeof(pgParameterStatus) +
1103  strlen(name) + strlen(value) + 2);
1104  if (pstatus)
1105  {
1106  char *ptr;
1107 
1108  ptr = ((char *) pstatus) + sizeof(pgParameterStatus);
1109  pstatus->name = ptr;
1110  strcpy(ptr, name);
1111  ptr += strlen(name) + 1;
1112  pstatus->value = ptr;
1113  strcpy(ptr, value);
1114  pstatus->next = conn->pstatus;
1115  conn->pstatus = pstatus;
1116  }
1117 
1118  /*
1119  * Save values of settings that are of interest to libpq in fields of the
1120  * PGconn object. We keep client_encoding and standard_conforming_strings
1121  * in static variables as well, so that PQescapeString and PQescapeBytea
1122  * can behave somewhat sanely (at least in single-connection-using
1123  * programs).
1124  */
1125  if (strcmp(name, "client_encoding") == 0)
1126  {
1128  /* if we don't recognize the encoding name, fall back to SQL_ASCII */
1129  if (conn->client_encoding < 0)
1132  }
1133  else if (strcmp(name, "standard_conforming_strings") == 0)
1134  {
1135  conn->std_strings = (strcmp(value, "on") == 0);
1137  }
1138  else if (strcmp(name, "server_version") == 0)
1139  {
1140  /* We convert the server version to numeric form. */
1141  int cnt;
1142  int vmaj,
1143  vmin,
1144  vrev;
1145 
1146  cnt = sscanf(value, "%d.%d.%d", &vmaj, &vmin, &vrev);
1147 
1148  if (cnt == 3)
1149  {
1150  /* old style, e.g. 9.6.1 */
1151  conn->sversion = (100 * vmaj + vmin) * 100 + vrev;
1152  }
1153  else if (cnt == 2)
1154  {
1155  if (vmaj >= 10)
1156  {
1157  /* new style, e.g. 10.1 */
1158  conn->sversion = 100 * 100 * vmaj + vmin;
1159  }
1160  else
1161  {
1162  /* old style without minor version, e.g. 9.6devel */
1163  conn->sversion = (100 * vmaj + vmin) * 100;
1164  }
1165  }
1166  else if (cnt == 1)
1167  {
1168  /* new style without minor version, e.g. 10devel */
1169  conn->sversion = 100 * 100 * vmaj;
1170  }
1171  else
1172  conn->sversion = 0; /* unknown */
1173  }
1174  else if (strcmp(name, "default_transaction_read_only") == 0)
1175  {
1177  (strcmp(value, "on") == 0) ? PG_BOOL_YES : PG_BOOL_NO;
1178  }
1179  else if (strcmp(name, "in_hot_standby") == 0)
1180  {
1181  conn->in_hot_standby =
1182  (strcmp(value, "on") == 0) ? PG_BOOL_YES : PG_BOOL_NO;
1183  }
1184  else if (strcmp(name, "scram_iterations") == 0)
1185  {
1187  }
1188 }
int pg_char_to_encoding(const char *name)
Definition: encnames.c:550
static bool static_std_strings
Definition: fe-exec.c:59
static int static_client_encoding
Definition: fe-exec.c:58
struct pgParameterStatus pgParameterStatus
@ PG_SQL_ASCII
Definition: pg_wchar.h:226
struct pgParameterStatus * next
Definition: libpq-int.h:263
bool std_strings
Definition: libpq-int.h:484
PGTernaryBool in_hot_standby
Definition: libpq-int.h:486
int client_encoding
Definition: libpq-int.h:483
int sversion
Definition: libpq-int.h:454
PGTernaryBool default_transaction_read_only
Definition: libpq-int.h:485
pgParameterStatus * pstatus
Definition: libpq-int.h:482
int scram_sha_256_iterations
Definition: libpq-int.h:528

References pg_conn::client_encoding, conn, pg_conn::default_transaction_read_only, free, pg_conn::in_hot_standby, malloc, name, pgParameterStatus::name, pgParameterStatus::next, PG_BOOL_NO, PG_BOOL_YES, pg_char_to_encoding(), PG_SQL_ASCII, pg_conn::pstatus, pg_conn::scram_sha_256_iterations, static_client_encoding, static_std_strings, pg_conn::std_strings, pg_conn::sversion, value, and pgParameterStatus::value.

Referenced by getParameterStatus().

◆ pqsecure_close()

void pqsecure_close ( PGconn conn)

Definition at line 189 of file fe-secure.c.

190 {
191 #ifdef USE_SSL
192  pgtls_close(conn);
193 #endif
194 }

References conn, and pgtls_close().

Referenced by pqDropConnection().

◆ pqsecure_initialize()

int pqsecure_initialize ( PGconn conn,
bool  do_ssl,
bool  do_crypto 
)

Definition at line 160 of file fe-secure.c.

161 {
162  int r = 0;
163 
164 #ifdef USE_SSL
165  r = pgtls_init(conn, do_ssl, do_crypto);
166 #endif
167 
168  return r;
169 }
int pgtls_init(PGconn *conn, bool do_ssl, bool do_crypto)

References conn, and pgtls_init().

Referenced by PQconnectPoll().

◆ pqsecure_open_client()

PostgresPollingStatusType pqsecure_open_client ( PGconn conn)

Definition at line 175 of file fe-secure.c.

176 {
177 #ifdef USE_SSL
178  return pgtls_open_client(conn);
179 #else
180  /* shouldn't get here */
181  return PGRES_POLLING_FAILED;
182 #endif
183 }
PostgresPollingStatusType pgtls_open_client(PGconn *conn)

References conn, PGRES_POLLING_FAILED, and pgtls_open_client().

Referenced by PQconnectPoll().

◆ pqsecure_raw_read()

ssize_t pqsecure_raw_read ( PGconn conn,
void *  ptr,
size_t  len 
)

Definition at line 230 of file fe-secure.c.

231 {
232  ssize_t n;
233  int result_errno = 0;
234  char sebuf[PG_STRERROR_R_BUFLEN];
235 
236  n = recv(conn->sock, ptr, len, 0);
237 
238  if (n < 0)
239  {
240  result_errno = SOCK_ERRNO;
241 
242  /* Set error message if appropriate */
243  switch (result_errno)
244  {
245 #ifdef EAGAIN
246  case EAGAIN:
247 #endif
248 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
249  case EWOULDBLOCK:
250 #endif
251  case EINTR:
252  /* no error message, caller is expected to retry */
253  break;
254 
255  case EPIPE:
256  case ECONNRESET:
257  libpq_append_conn_error(conn, "server closed the connection unexpectedly\n"
258  "\tThis probably means the server terminated abnormally\n"
259  "\tbefore or while processing the request.");
260  break;
261 
262  default:
263  libpq_append_conn_error(conn, "could not receive data from server: %s",
264  SOCK_STRERROR(result_errno,
265  sebuf, sizeof(sebuf)));
266  break;
267  }
268  }
269 
270  /* ensure we return the intended errno to caller */
271  SOCK_ERRNO_SET(result_errno);
272 
273  return n;
274 }
#define recv(s, buf, len, flags)
Definition: win32_port.h:500

References conn, EAGAIN, ECONNRESET, EINTR, EWOULDBLOCK, len, libpq_append_conn_error(), PG_STRERROR_R_BUFLEN, recv, pg_conn::sock, SOCK_ERRNO, SOCK_ERRNO_SET, and SOCK_STRERROR.

Referenced by gss_read(), my_sock_read(), pg_GSS_read(), and pqsecure_read().

◆ pqsecure_raw_write()

ssize_t pqsecure_raw_write ( PGconn conn,
const void *  ptr,
size_t  len 
)

Definition at line 346 of file fe-secure.c.

347 {
348  ssize_t n;
349  int flags = 0;
350  int result_errno = 0;
351  char msgbuf[1024];
352  char sebuf[PG_STRERROR_R_BUFLEN];
353 
354  DECLARE_SIGPIPE_INFO(spinfo);
355 
356  /*
357  * If we already had a write failure, we will never again try to send data
358  * on that connection. Even if the kernel would let us, we've probably
359  * lost message boundary sync with the server. conn->write_failed
360  * therefore persists until the connection is reset, and we just discard
361  * all data presented to be written.
362  */
363  if (conn->write_failed)
364  return len;
365 
366 #ifdef MSG_NOSIGNAL
367  if (conn->sigpipe_flag)
368  flags |= MSG_NOSIGNAL;
369 
370 retry_masked:
371 #endif /* MSG_NOSIGNAL */
372 
373  DISABLE_SIGPIPE(conn, spinfo, return -1);
374 
375  n = send(conn->sock, ptr, len, flags);
376 
377  if (n < 0)
378  {
379  result_errno = SOCK_ERRNO;
380 
381  /*
382  * If we see an EINVAL, it may be because MSG_NOSIGNAL isn't available
383  * on this machine. So, clear sigpipe_flag so we don't try the flag
384  * again, and retry the send().
385  */
386 #ifdef MSG_NOSIGNAL
387  if (flags != 0 && result_errno == EINVAL)
388  {
389  conn->sigpipe_flag = false;
390  flags = 0;
391  goto retry_masked;
392  }
393 #endif /* MSG_NOSIGNAL */
394 
395  /* Set error message if appropriate */
396  switch (result_errno)
397  {
398 #ifdef EAGAIN
399  case EAGAIN:
400 #endif
401 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
402  case EWOULDBLOCK:
403 #endif
404  case EINTR:
405  /* no error message, caller is expected to retry */
406  break;
407 
408  case EPIPE:
409  /* Set flag for EPIPE */
410  REMEMBER_EPIPE(spinfo, true);
411 
412  /* FALL THRU */
413 
414  case ECONNRESET:
415  conn->write_failed = true;
416  /* Store error message in conn->write_err_msg, if possible */
417  /* (strdup failure is OK, we'll cope later) */
418  snprintf(msgbuf, sizeof(msgbuf),
419  libpq_gettext("server closed the connection unexpectedly\n"
420  "\tThis probably means the server terminated abnormally\n"
421  "\tbefore or while processing the request."));
422  /* keep newline out of translated string */
423  strlcat(msgbuf, "\n", sizeof(msgbuf));
424  conn->write_err_msg = strdup(msgbuf);
425  /* Now claim the write succeeded */
426  n = len;
427  break;
428 
429  default:
430  conn->write_failed = true;
431  /* Store error message in conn->write_err_msg, if possible */
432  /* (strdup failure is OK, we'll cope later) */
433  snprintf(msgbuf, sizeof(msgbuf),
434  libpq_gettext("could not send data to server: %s"),
435  SOCK_STRERROR(result_errno,
436  sebuf, sizeof(sebuf)));
437  /* keep newline out of translated string */
438  strlcat(msgbuf, "\n", sizeof(msgbuf));
439  conn->write_err_msg = strdup(msgbuf);
440  /* Now claim the write succeeded */
441  n = len;
442  break;
443  }
444  }
445 
446  RESTORE_SIGPIPE(conn, spinfo);
447 
448  /* ensure we return the intended errno to caller */
449  SOCK_ERRNO_SET(result_errno);
450 
451  return n;
452 }
#define REMEMBER_EPIPE(spinfo, cond)
Definition: fe-secure.c:103
#define DISABLE_SIGPIPE(conn, spinfo, failaction)
Definition: fe-secure.c:97
#define DECLARE_SIGPIPE_INFO(spinfo)
Definition: fe-secure.c:95
#define RESTORE_SIGPIPE(conn, spinfo)
Definition: fe-secure.c:105
size_t strlcat(char *dst, const char *src, size_t siz)
Definition: strlcat.c:33
char * write_err_msg
Definition: libpq-int.h:460
bool sigpipe_flag
Definition: libpq-int.h:458
bool write_failed
Definition: libpq-int.h:459
#define send(s, buf, len, flags)
Definition: win32_port.h:501

References conn, DECLARE_SIGPIPE_INFO, DISABLE_SIGPIPE, EAGAIN, ECONNRESET, EINTR, EWOULDBLOCK, len, libpq_gettext, PG_STRERROR_R_BUFLEN, REMEMBER_EPIPE, RESTORE_SIGPIPE, send, pg_conn::sigpipe_flag, snprintf, pg_conn::sock, SOCK_ERRNO, SOCK_ERRNO_SET, SOCK_STRERROR, strlcat(), pg_conn::write_err_msg, and pg_conn::write_failed.

Referenced by my_sock_write(), pg_GSS_write(), pqsecure_open_gss(), and pqsecure_write().

◆ pqsecure_read()

ssize_t pqsecure_read ( PGconn conn,
void *  ptr,
size_t  len 
)

Definition at line 204 of file fe-secure.c.

205 {
206  ssize_t n;
207 
208 #ifdef USE_SSL
209  if (conn->ssl_in_use)
210  {
211  n = pgtls_read(conn, ptr, len);
212  }
213  else
214 #endif
215 #ifdef ENABLE_GSS
216  if (conn->gssenc)
217  {
218  n = pg_GSS_read(conn, ptr, len);
219  }
220  else
221 #endif
222  {
223  n = pqsecure_raw_read(conn, ptr, len);
224  }
225 
226  return n;
227 }
ssize_t pg_GSS_read(PGconn *conn, void *ptr, size_t len)
ssize_t pgtls_read(PGconn *conn, void *ptr, size_t len)
ssize_t pqsecure_raw_read(PGconn *conn, void *ptr, size_t len)
Definition: fe-secure.c:230

References conn, len, pg_GSS_read(), pgtls_read(), pqsecure_raw_read(), and pg_conn::ssl_in_use.

Referenced by pqReadData().

◆ pqsecure_write()

ssize_t pqsecure_write ( PGconn conn,
const void *  ptr,
size_t  len 
)

Definition at line 297 of file fe-secure.c.

298 {
299  ssize_t n;
300 
301 #ifdef USE_SSL
302  if (conn->ssl_in_use)
303  {
304  n = pgtls_write(conn, ptr, len);
305  }
306  else
307 #endif
308 #ifdef ENABLE_GSS
309  if (conn->gssenc)
310  {
311  n = pg_GSS_write(conn, ptr, len);
312  }
313  else
314 #endif
315  {
316  n = pqsecure_raw_write(conn, ptr, len);
317  }
318 
319  return n;
320 }
ssize_t pg_GSS_write(PGconn *conn, const void *ptr, size_t len)
ssize_t pgtls_write(PGconn *conn, const void *ptr, size_t len)
ssize_t pqsecure_raw_write(PGconn *conn, const void *ptr, size_t len)
Definition: fe-secure.c:346

References conn, len, pg_GSS_write(), pgtls_write(), pqsecure_raw_write(), and pg_conn::ssl_in_use.

Referenced by pqSendSome().

◆ PQsendQueryContinue()

int PQsendQueryContinue ( PGconn conn,
const char *  query 
)

Definition at line 1428 of file fe-exec.c.

1429 {
1430  return PQsendQueryInternal(conn, query, false);
1431 }
static int PQsendQueryInternal(PGconn *conn, const char *query, bool newQuery)
Definition: fe-exec.c:1434

References conn, and PQsendQueryInternal().

Referenced by PQconnectPoll().

◆ pqSetResultError()

void pqSetResultError ( PGresult res,
PQExpBuffer  errorMessage,
int  offset 
)

Definition at line 689 of file fe-exec.c.

690 {
691  char *msg;
692 
693  if (!res)
694  return;
695 
696  /*
697  * We handle two OOM scenarios here. The errorMessage buffer might be
698  * marked "broken" due to having previously failed to allocate enough
699  * memory for the message, or it might be fine but pqResultStrdup fails
700  * and returns NULL. In either case, just make res->errMsg point directly
701  * at a constant "out of memory" string.
702  */
703  if (!PQExpBufferBroken(errorMessage))
704  msg = pqResultStrdup(res, errorMessage->data + offset);
705  else
706  msg = NULL;
707  if (msg)
708  res->errMsg = msg;
709  else
710  res->errMsg = libpq_gettext("out of memory\n");
711 }
#define PQExpBufferBroken(str)
Definition: pqexpbuffer.h:59

References PQExpBufferData::data, pg_result::errMsg, libpq_gettext, PQExpBufferBroken, pqResultStrdup(), and res.

Referenced by pqGetErrorNotice3(), PQmakeEmptyPGresult(), and pqPrepareAsyncResult().

◆ pqSkipnchar()

int pqSkipnchar ( size_t  len,
PGconn conn 
)

Definition at line 188 of file fe-misc.c.

189 {
190  if (len > (size_t) (conn->inEnd - conn->inCursor))
191  return EOF;
192 
193  conn->inCursor += len;
194 
195  return 0;
196 }

References conn, pg_conn::inCursor, pg_conn::inEnd, and len.

Referenced by getAnotherTuple().

◆ pqTraceOutputMessage()

void pqTraceOutputMessage ( PGconn conn,
const char *  message,
bool  toServer 
)

Definition at line 529 of file fe-trace.c.

530 {
531  char id;
532  int length;
533  char *prefix = toServer ? "F" : "B";
534  int logCursor = 0;
535  bool regress;
536 
538  {
539  char timestr[128];
540 
541  pqTraceFormatTimestamp(timestr, sizeof(timestr));
542  fprintf(conn->Pfdebug, "%s\t", timestr);
543  }
544  regress = (conn->traceFlags & PQTRACE_REGRESS_MODE) != 0;
545 
546  id = message[logCursor++];
547 
548  memcpy(&length, message + logCursor, 4);
549  length = (int) pg_ntoh32(length);
550  logCursor += 4;
551 
552  /*
553  * In regress mode, suppress the length of ErrorResponse and
554  * NoticeResponse. The F (file name), L (line number) and R (routine
555  * name) fields can change as server code is modified, and if their
556  * lengths differ from the originals, that would break tests.
557  */
558  if (regress && !toServer && (id == 'E' || id == 'N'))
559  fprintf(conn->Pfdebug, "%s\tNN\t", prefix);
560  else
561  fprintf(conn->Pfdebug, "%s\t%d\t", prefix, length);
562 
563  switch (id)
564  {
565  case '1':
566  fprintf(conn->Pfdebug, "ParseComplete");
567  /* No message content */
568  break;
569  case '2':
570  fprintf(conn->Pfdebug, "BindComplete");
571  /* No message content */
572  break;
573  case '3':
574  fprintf(conn->Pfdebug, "CloseComplete");
575  /* No message content */
576  break;
577  case 'A': /* Notification Response */
578  pqTraceOutputA(conn->Pfdebug, message, &logCursor, regress);
579  break;
580  case 'B': /* Bind */
581  pqTraceOutputB(conn->Pfdebug, message, &logCursor);
582  break;
583  case 'c':
584  fprintf(conn->Pfdebug, "CopyDone");
585  /* No message content */
586  break;
587  case 'C': /* Close(F) or Command Complete(B) */
588  pqTraceOutputC(conn->Pfdebug, toServer, message, &logCursor);
589  break;
590  case 'd': /* Copy Data */
591  /* Drop COPY data to reduce the overhead of logging. */
592  break;
593  case 'D': /* Describe(F) or Data Row(B) */
594  pqTraceOutputD(conn->Pfdebug, toServer, message, &logCursor);
595  break;
596  case 'E': /* Execute(F) or Error Response(B) */
597  pqTraceOutputE(conn->Pfdebug, toServer, message, &logCursor,
598  regress);
599  break;
600  case 'f': /* Copy Fail */
601  pqTraceOutputf(conn->Pfdebug, message, &logCursor);
602  break;
603  case 'F': /* Function Call */
604  pqTraceOutputF(conn->Pfdebug, message, &logCursor, regress);
605  break;
606  case 'G': /* Start Copy In */
607  pqTraceOutputG(conn->Pfdebug, message, &logCursor);
608  break;
609  case 'H': /* Flush(F) or Start Copy Out(B) */
610  if (!toServer)
611  pqTraceOutputH(conn->Pfdebug, message, &logCursor);
612  else
613  fprintf(conn->Pfdebug, "Flush"); /* no message content */
614  break;
615  case 'I':
616  fprintf(conn->Pfdebug, "EmptyQueryResponse");
617  /* No message content */
618  break;
619  case 'K': /* secret key data from the backend */
620  pqTraceOutputK(conn->Pfdebug, message, &logCursor, regress);
621  break;
622  case 'n':
623  fprintf(conn->Pfdebug, "NoData");
624  /* No message content */
625  break;
626  case 'N':
627  pqTraceOutputNR(conn->Pfdebug, "NoticeResponse", message,
628  &logCursor, regress);
629  break;
630  case 'P': /* Parse */
631  pqTraceOutputP(conn->Pfdebug, message, &logCursor, regress);
632  break;
633  case 'Q': /* Query */
634  pqTraceOutputQ(conn->Pfdebug, message, &logCursor);
635  break;
636  case 'R': /* Authentication */
637  pqTraceOutputR(conn->Pfdebug, message, &logCursor);
638  break;
639  case 's':
640  fprintf(conn->Pfdebug, "PortalSuspended");
641  /* No message content */
642  break;
643  case 'S': /* Parameter Status(B) or Sync(F) */
644  if (!toServer)
645  pqTraceOutputS(conn->Pfdebug, message, &logCursor);
646  else
647  fprintf(conn->Pfdebug, "Sync"); /* no message content */
648  break;
649  case 't': /* Parameter Description */
650  pqTraceOutputt(conn->Pfdebug, message, &logCursor, regress);
651  break;
652  case 'T': /* Row Description */
653  pqTraceOutputT(conn->Pfdebug, message, &logCursor, regress);
654  break;
655  case 'v': /* Negotiate Protocol Version */
656  pqTraceOutputv(conn->Pfdebug, message, &logCursor);
657  break;
658  case 'V': /* Function Call response */
659  pqTraceOutputV(conn->Pfdebug, message, &logCursor);
660  break;
661  case 'W': /* Start Copy Both */
662  pqTraceOutputW(conn->Pfdebug, message, &logCursor, length);
663  break;
664  case 'X':
665  fprintf(conn->Pfdebug, "Terminate");
666  /* No message content */
667  break;
668  case 'Z': /* Ready For Query */
669  pqTraceOutputZ(conn->Pfdebug, message, &logCursor);
670  break;
671  default:
672  fprintf(conn->Pfdebug, "Unknown message: %02x", id);
673  break;
674  }
675 
676  fputc('\n', conn->Pfdebug);
677 
678  /*
679  * Verify the printing routine did it right. Note that the one-byte
680  * message identifier is not included in the length, but our cursor does
681  * include it.
682  */
683  if (logCursor - 1 != length)
685  "mismatched message length: consumed %d, expected %d\n",
686  logCursor - 1, length);
687 }
static void pqTraceOutputQ(FILE *f, const char *message, int *cursor)
Definition: fe-trace.c:428
static void pqTraceOutputS(FILE *f, const char *message, int *cursor)
Definition: fe-trace.c:444
static void pqTraceOutputH(FILE *f, const char *message, int *cursor)
Definition: fe-trace.c:390
static void pqTraceOutputZ(FILE *f, const char *message, int *cursor)
Definition: fe-trace.c:519
static void pqTraceOutputW(FILE *f, const char *message, int *cursor, int length)
Definition: fe-trace.c:508
static void pqTraceOutputE(FILE *f, bool toServer, const char *message, int *cursor, bool regress)
Definition: fe-trace.c:327
static void pqTraceOutputV(FILE *f, const char *message, int *cursor)
Definition: fe-trace.c:496
static void pqTraceOutputK(FILE *f, const char *message, int *cursor, bool regress)
Definition: fe-trace.c:404
static void pqTraceOutputF(FILE *f, const char *message, int *cursor, bool regress)
Definition: fe-trace.c:349
static void pqTraceOutputP(FILE *f, const char *message, int *cursor, bool regress)
Definition: fe-trace.c:413
static void pqTraceOutputT(FILE *f, const char *message, int *cursor, bool regress)
Definition: fe-trace.c:466
static void pqTraceOutputA(FILE *f, const char *message, int *cursor, bool regress)
Definition: fe-trace.c:220
static void pqTraceOutputD(FILE *f, bool toServer, const char *message, int *cursor)
Definition: fe-trace.c:278
static void pqTraceOutputG(FILE *f, const char *message, int *cursor)
Definition: fe-trace.c:376
static void pqTraceOutputf(FILE *f, const char *message, int *cursor)
Definition: fe-trace.c:341
static void pqTraceOutputNR(FILE *f, const char *type, const char *message, int *cursor, bool regress)
Definition: fe-trace.c:306
static void pqTraceOutputR(FILE *f, const char *message, int *cursor)
Definition: fe-trace.c:436
static void pqTraceOutputt(FILE *f, const char *message, int *cursor, bool regress)
Definition: fe-trace.c:453
static void pqTraceOutputB(FILE *f, const char *message, int *cursor)
Definition: fe-trace.c:230
static void pqTraceOutputv(FILE *f, const char *message, int *cursor)
Definition: fe-trace.c:487
static void pqTraceOutputC(FILE *f, bool toServer, const char *message, int *cursor)
Definition: fe-trace.c:261
static void pqTraceFormatTimestamp(char *timestr, size_t ts_len)
Definition: fe-trace.c:80
#define PQTRACE_SUPPRESS_TIMESTAMPS
Definition: libpq-fe.h:414
#define PQTRACE_REGRESS_MODE
Definition: libpq-fe.h:416
#define fprintf
Definition: port.h:242
int traceFlags
Definition: libpq-int.h:404

References conn, fprintf, pg_conn::Pfdebug, pg_ntoh32, PQTRACE_REGRESS_MODE, PQTRACE_SUPPRESS_TIMESTAMPS, pqTraceFormatTimestamp(), pqTraceOutputA(), pqTraceOutputB(), pqTraceOutputC(), pqTraceOutputD(), pqTraceOutputE(), pqTraceOutputf(), pqTraceOutputF(), pqTraceOutputG(), pqTraceOutputH(), pqTraceOutputK(), pqTraceOutputNR(), pqTraceOutputP(), pqTraceOutputQ(), pqTraceOutputR(), pqTraceOutputS(), pqTraceOutputt(), pqTraceOutputT(), pqTraceOutputv(), pqTraceOutputV(), pqTraceOutputW(), pqTraceOutputZ(), and pg_conn::traceFlags.

Referenced by getCopyDataMessage(), pqFunctionCall3(), pqParseInput3(), and pqPutMsgEnd().

◆ pqTraceOutputNoTypeByteMessage()

void pqTraceOutputNoTypeByteMessage ( PGconn conn,
const char *  message 
)

Definition at line 694 of file fe-trace.c.

695 {
696  int length;
697  int logCursor = 0;
698 
700  {
701  char timestr[128];
702 
703  pqTraceFormatTimestamp(timestr, sizeof(timestr));
704  fprintf(conn->Pfdebug, "%s\t", timestr);
705  }
706 
707  memcpy(&length, message + logCursor, 4);
708  length = (int) pg_ntoh32(length);
709  logCursor += 4;
710 
711  fprintf(conn->Pfdebug, "F\t%d\t", length);
712 
713  switch (length)
714  {
715  case 16: /* CancelRequest */
716  fprintf(conn->Pfdebug, "CancelRequest\t");
717  pqTraceOutputInt32(conn->Pfdebug, message, &logCursor, false);
718  pqTraceOutputInt32(conn->Pfdebug, message, &logCursor, false);
719  pqTraceOutputInt32(conn->Pfdebug, message, &logCursor, false);
720  break;
721  case 8: /* GSSENCRequest or SSLRequest */
722  /* These messages do not reach here. */
723  default:
724  fprintf(conn->Pfdebug, "Unknown message: length is %d", length);
725  break;
726  }
727 
728  fputc('\n', conn->Pfdebug);
729 }
static int pqTraceOutputInt32(FILE *pfdebug, const char *data, int *cursor, bool suppress)
Definition: fe-trace.c:144

References conn, fprintf, pg_conn::Pfdebug, pg_ntoh32, PQTRACE_SUPPRESS_TIMESTAMPS, pqTraceFormatTimestamp(), pqTraceOutputInt32(), and pg_conn::traceFlags.

Referenced by pqPutMsgEnd().

◆ pqWait()

int pqWait ( int  forRead,
int  forWrite,
PGconn conn 
)

Definition at line 979 of file fe-misc.c.

980 {
981  return pqWaitTimed(forRead, forWrite, conn, (time_t) -1);
982 }
int pqWaitTimed(int forRead, int forWrite, PGconn *conn, time_t finish_time)
Definition: fe-misc.c:992

References conn, and pqWaitTimed().

Referenced by pqFunctionCall3(), pqGetCopyData3(), pqGetline3(), PQgetResult(), and pqSendSome().

◆ pqWaitTimed()

int pqWaitTimed ( int  forRead,
int  forWrite,
PGconn conn,
time_t  finish_time 
)

Definition at line 992 of file fe-misc.c.

993 {
994  int result;
995 
996  result = pqSocketCheck(conn, forRead, forWrite, finish_time);
997 
998  if (result < 0)
999  return -1; /* errorMessage is already set */
1000 
1001  if (result == 0)
1002  {
1003  libpq_append_conn_error(conn, "timeout expired");
1004  return 1;
1005  }
1006 
1007  return 0;
1008 }

References conn, libpq_append_conn_error(), and pqSocketCheck().

Referenced by connectDBComplete(), and pqWait().

◆ pqWriteReady()

int pqWriteReady ( PGconn conn)

Definition at line 1025 of file fe-misc.c.

1026 {
1027  return pqSocketCheck(conn, 0, 1, (time_t) 0);
1028 }

References conn, and pqSocketCheck().

Variable Documentation

◆ pgresStatus

char* const pgresStatus[]
extern

Definition at line 32 of file fe-exec.c.

Referenced by PQresStatus().