PostgreSQL Source Code  git master
libpq-fe.h File Reference
#include <stdio.h>
#include "postgres_ext.h"
Include dependency graph for libpq-fe.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  pgNotify
 
struct  _PQprintOpt
 
struct  _PQconninfoOption
 
struct  PQArgBlock
 
struct  pgresAttDesc
 

Macros

#define LIBPQ_HAS_PIPELINING   1
 
#define LIBPQ_HAS_TRACE_FLAGS   1
 
#define LIBPQ_HAS_SSL_LIBRARY_DETECTION   1
 
#define PG_COPYRES_ATTRS   0x01
 
#define PG_COPYRES_TUPLES   0x02 /* Implies PG_COPYRES_ATTRS */
 
#define PG_COPYRES_EVENTS   0x04
 
#define PG_COPYRES_NOTICEHOOKS   0x08
 
#define PQsetdb(M_PGHOST, M_PGPORT, M_PGOPT, M_PGTTY, M_DBNAME)    PQsetdbLogin(M_PGHOST, M_PGPORT, M_PGOPT, M_PGTTY, M_DBNAME, NULL, NULL)
 
#define PQTRACE_SUPPRESS_TIMESTAMPS   (1<<0)
 
#define PQTRACE_REGRESS_MODE   (1<<1)
 
#define PQ_QUERY_PARAM_MAX_LIMIT   65535
 
#define PQfreeNotify(ptr)   PQfreemem(ptr)
 
#define PQnoPasswordSupplied   "fe_sendauth: no password supplied\n"
 

Typedefs

typedef struct pg_conn PGconn
 
typedef struct pg_result PGresult
 
typedef struct pg_cancel PGcancel
 
typedef struct pgNotify PGnotify
 
typedef void(* PQnoticeReceiver) (void *arg, const PGresult *res)
 
typedef void(* PQnoticeProcessor) (void *arg, const char *message)
 
typedef char pqbool
 
typedef struct _PQprintOpt PQprintOpt
 
typedef struct _PQconninfoOption PQconninfoOption
 
typedef struct pgresAttDesc PGresAttDesc
 
typedef void(* pgthreadlock_t) (int acquire)
 
typedef int(* PQsslKeyPassHook_OpenSSL_type) (char *buf, int size, PGconn *conn)
 

Enumerations

enum  ConnStatusType {
  CONNECTION_OK , CONNECTION_BAD , CONNECTION_STARTED , CONNECTION_MADE ,
  CONNECTION_AWAITING_RESPONSE , CONNECTION_AUTH_OK , CONNECTION_SETENV , CONNECTION_SSL_STARTUP ,
  CONNECTION_NEEDED , CONNECTION_CHECK_WRITABLE , CONNECTION_CONSUME , CONNECTION_GSS_STARTUP ,
  CONNECTION_CHECK_TARGET , CONNECTION_CHECK_STANDBY
}
 
enum  PostgresPollingStatusType {
  PGRES_POLLING_FAILED = 0 , PGRES_POLLING_READING , PGRES_POLLING_WRITING , PGRES_POLLING_OK ,
  PGRES_POLLING_ACTIVE
}
 
enum  ExecStatusType {
  PGRES_EMPTY_QUERY = 0 , PGRES_COMMAND_OK , PGRES_TUPLES_OK , PGRES_COPY_OUT ,
  PGRES_COPY_IN , PGRES_BAD_RESPONSE , PGRES_NONFATAL_ERROR , PGRES_FATAL_ERROR ,
  PGRES_COPY_BOTH , PGRES_SINGLE_TUPLE , PGRES_PIPELINE_SYNC , PGRES_PIPELINE_ABORTED
}
 
enum  PGTransactionStatusType {
  PQTRANS_IDLE , PQTRANS_ACTIVE , PQTRANS_INTRANS , PQTRANS_INERROR ,
  PQTRANS_UNKNOWN
}
 
enum  PGVerbosity { PQERRORS_TERSE , PQERRORS_DEFAULT , PQERRORS_VERBOSE , PQERRORS_SQLSTATE }
 
enum  PGContextVisibility { PQSHOW_CONTEXT_NEVER , PQSHOW_CONTEXT_ERRORS , PQSHOW_CONTEXT_ALWAYS }
 
enum  PGPing { PQPING_OK , PQPING_REJECT , PQPING_NO_RESPONSE , PQPING_NO_ATTEMPT }
 
enum  PGpipelineStatus { PQ_PIPELINE_OFF , PQ_PIPELINE_ON , PQ_PIPELINE_ABORTED }
 

Functions

PGconnPQconnectStart (const char *conninfo)
 
PGconnPQconnectStartParams (const char *const *keywords, const char *const *values, int expand_dbname)
 
PostgresPollingStatusType PQconnectPoll (PGconn *conn)
 
PGconnPQconnectdb (const char *conninfo)
 
PGconnPQconnectdbParams (const char *const *keywords, const char *const *values, int expand_dbname)
 
PGconnPQsetdbLogin (const char *pghost, const char *pgport, const char *pgoptions, const char *pgtty, const char *dbName, const char *login, const char *pwd)
 
void PQfinish (PGconn *conn)
 
PQconninfoOptionPQconndefaults (void)
 
PQconninfoOptionPQconninfoParse (const char *conninfo, char **errmsg)
 
PQconninfoOptionPQconninfo (PGconn *conn)
 
void PQconninfoFree (PQconninfoOption *connOptions)
 
int PQresetStart (PGconn *conn)
 
PostgresPollingStatusType PQresetPoll (PGconn *conn)
 
void PQreset (PGconn *conn)
 
PGcancelPQgetCancel (PGconn *conn)
 
void PQfreeCancel (PGcancel *cancel)
 
int PQcancel (PGcancel *cancel, char *errbuf, int errbufsize)
 
int PQrequestCancel (PGconn *conn)
 
char * PQdb (const PGconn *conn)
 
char * PQuser (const PGconn *conn)
 
char * PQpass (const PGconn *conn)
 
char * PQhost (const PGconn *conn)
 
char * PQhostaddr (const PGconn *conn)
 
char * PQport (const PGconn *conn)
 
char * PQtty (const PGconn *conn)
 
char * PQoptions (const PGconn *conn)
 
ConnStatusType PQstatus (const PGconn *conn)
 
PGTransactionStatusType PQtransactionStatus (const PGconn *conn)
 
const char * PQparameterStatus (const PGconn *conn, const char *paramName)
 
int PQprotocolVersion (const PGconn *conn)
 
int PQserverVersion (const PGconn *conn)
 
char * PQerrorMessage (const PGconn *conn)
 
int PQsocket (const PGconn *conn)
 
int PQbackendPID (const PGconn *conn)
 
PGpipelineStatus PQpipelineStatus (const PGconn *conn)
 
int PQconnectionNeedsPassword (const PGconn *conn)
 
int PQconnectionUsedPassword (const PGconn *conn)
 
int PQclientEncoding (const PGconn *conn)
 
int PQsetClientEncoding (PGconn *conn, const char *encoding)
 
int PQsslInUse (PGconn *conn)
 
void * PQsslStruct (PGconn *conn, const char *struct_name)
 
const char * PQsslAttribute (PGconn *conn, const char *attribute_name)
 
const char *const * PQsslAttributeNames (PGconn *conn)
 
void * PQgetssl (PGconn *conn)
 
void PQinitSSL (int do_init)
 
void PQinitOpenSSL (int do_ssl, int do_crypto)
 
int PQgssEncInUse (PGconn *conn)
 
void * PQgetgssctx (PGconn *conn)
 
PGVerbosity PQsetErrorVerbosity (PGconn *conn, PGVerbosity verbosity)
 
PGContextVisibility PQsetErrorContextVisibility (PGconn *conn, PGContextVisibility show_context)
 
PQnoticeReceiver PQsetNoticeReceiver (PGconn *conn, PQnoticeReceiver proc, void *arg)
 
PQnoticeProcessor PQsetNoticeProcessor (PGconn *conn, PQnoticeProcessor proc, void *arg)
 
pgthreadlock_t PQregisterThreadLock (pgthreadlock_t newhandler)
 
void PQtrace (PGconn *conn, FILE *debug_port)
 
void PQuntrace (PGconn *conn)
 
void PQsetTraceFlags (PGconn *conn, int flags)
 
PGresultPQexec (PGconn *conn, const char *query)
 
PGresultPQexecParams (PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
PGresultPQprepare (PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
 
PGresultPQexecPrepared (PGconn *conn, const char *stmtName, int nParams, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
int PQsendQuery (PGconn *conn, const char *query)
 
int PQsendQueryParams (PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
int PQsendPrepare (PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
 
int PQsendQueryPrepared (PGconn *conn, const char *stmtName, int nParams, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
int PQsetSingleRowMode (PGconn *conn)
 
PGresultPQgetResult (PGconn *conn)
 
int PQisBusy (PGconn *conn)
 
int PQconsumeInput (PGconn *conn)
 
int PQenterPipelineMode (PGconn *conn)
 
int PQexitPipelineMode (PGconn *conn)
 
int PQpipelineSync (PGconn *conn)
 
int PQsendFlushRequest (PGconn *conn)
 
PGnotifyPQnotifies (PGconn *conn)
 
int PQputCopyData (PGconn *conn, const char *buffer, int nbytes)
 
int PQputCopyEnd (PGconn *conn, const char *errormsg)
 
int PQgetCopyData (PGconn *conn, char **buffer, int async)
 
int PQgetline (PGconn *conn, char *buffer, int length)
 
int PQputline (PGconn *conn, const char *string)
 
int PQgetlineAsync (PGconn *conn, char *buffer, int bufsize)
 
int PQputnbytes (PGconn *conn, const char *buffer, int nbytes)
 
int PQendcopy (PGconn *conn)
 
int PQsetnonblocking (PGconn *conn, int arg)
 
int PQisnonblocking (const PGconn *conn)
 
int PQisthreadsafe (void)
 
PGPing PQping (const char *conninfo)
 
PGPing PQpingParams (const char *const *keywords, const char *const *values, int expand_dbname)
 
int PQflush (PGconn *conn)
 
PGresultPQfn (PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
 
ExecStatusType PQresultStatus (const PGresult *res)
 
char * PQresStatus (ExecStatusType status)
 
char * PQresultErrorMessage (const PGresult *res)
 
char * PQresultVerboseErrorMessage (const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
 
char * PQresultErrorField (const PGresult *res, int fieldcode)
 
int PQntuples (const PGresult *res)
 
int PQnfields (const PGresult *res)
 
int PQbinaryTuples (const PGresult *res)
 
char * PQfname (const PGresult *res, int field_num)
 
int PQfnumber (const PGresult *res, const char *field_name)
 
Oid PQftable (const PGresult *res, int field_num)
 
int PQftablecol (const PGresult *res, int field_num)
 
int PQfformat (const PGresult *res, int field_num)
 
Oid PQftype (const PGresult *res, int field_num)
 
int PQfsize (const PGresult *res, int field_num)
 
int PQfmod (const PGresult *res, int field_num)
 
char * PQcmdStatus (PGresult *res)
 
char * PQoidStatus (const PGresult *res)
 
Oid PQoidValue (const PGresult *res)
 
char * PQcmdTuples (PGresult *res)
 
char * PQgetvalue (const PGresult *res, int tup_num, int field_num)
 
int PQgetlength (const PGresult *res, int tup_num, int field_num)
 
int PQgetisnull (const PGresult *res, int tup_num, int field_num)
 
int PQnparams (const PGresult *res)
 
Oid PQparamtype (const PGresult *res, int param_num)
 
PGresultPQdescribePrepared (PGconn *conn, const char *stmt)
 
PGresultPQdescribePortal (PGconn *conn, const char *portal)
 
int PQsendDescribePrepared (PGconn *conn, const char *stmt)
 
int PQsendDescribePortal (PGconn *conn, const char *portal)
 
void PQclear (PGresult *res)
 
void PQfreemem (void *ptr)
 
PGresultPQmakeEmptyPGresult (PGconn *conn, ExecStatusType status)
 
PGresultPQcopyResult (const PGresult *src, int flags)
 
int PQsetResultAttrs (PGresult *res, int numAttributes, PGresAttDesc *attDescs)
 
void * PQresultAlloc (PGresult *res, size_t nBytes)
 
size_t PQresultMemorySize (const PGresult *res)
 
int PQsetvalue (PGresult *res, int tup_num, int field_num, char *value, int len)
 
size_t PQescapeStringConn (PGconn *conn, char *to, const char *from, size_t length, int *error)
 
char * PQescapeLiteral (PGconn *conn, const char *str, size_t len)
 
char * PQescapeIdentifier (PGconn *conn, const char *str, size_t len)
 
unsigned char * PQescapeByteaConn (PGconn *conn, const unsigned char *from, size_t from_length, size_t *to_length)
 
unsigned char * PQunescapeBytea (const unsigned char *strtext, size_t *retbuflen)
 
size_t PQescapeString (char *to, const char *from, size_t length)
 
unsigned char * PQescapeBytea (const unsigned char *from, size_t from_length, size_t *to_length)
 
void PQprint (FILE *fout, const PGresult *res, const PQprintOpt *po)
 
void PQdisplayTuples (const PGresult *res, FILE *fp, int fillAlign, const char *fieldSep, int printHeader, int quiet)
 
void PQprintTuples (const PGresult *res, FILE *fout, int PrintAttNames, int TerseOutput, int colWidth)
 
int lo_open (PGconn *conn, Oid lobjId, int mode)
 
int lo_close (PGconn *conn, int fd)
 
int lo_read (PGconn *conn, int fd, char *buf, size_t len)
 
int lo_write (PGconn *conn, int fd, const char *buf, size_t len)
 
int lo_lseek (PGconn *conn, int fd, int offset, int whence)
 
pg_int64 lo_lseek64 (PGconn *conn, int fd, pg_int64 offset, int whence)
 
Oid lo_creat (PGconn *conn, int mode)
 
Oid lo_create (PGconn *conn, Oid lobjId)
 
int lo_tell (PGconn *conn, int fd)
 
pg_int64 lo_tell64 (PGconn *conn, int fd)
 
int lo_truncate (PGconn *conn, int fd, size_t len)
 
int lo_truncate64 (PGconn *conn, int fd, pg_int64 len)
 
int lo_unlink (PGconn *conn, Oid lobjId)
 
Oid lo_import (PGconn *conn, const char *filename)
 
Oid lo_import_with_oid (PGconn *conn, const char *filename, Oid lobjId)
 
int lo_export (PGconn *conn, Oid lobjId, const char *filename)
 
int PQlibVersion (void)
 
int PQmblen (const char *s, int encoding)
 
int PQmblenBounded (const char *s, int encoding)
 
int PQdsplen (const char *s, int encoding)
 
int PQenv2encoding (void)
 
char * PQencryptPassword (const char *passwd, const char *user)
 
char * PQencryptPasswordConn (PGconn *conn, const char *passwd, const char *user, const char *algorithm)
 
int pg_char_to_encoding (const char *name)
 
const char * pg_encoding_to_char (int encoding)
 
int pg_valid_server_encoding_id (int encoding)
 
PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL (void)
 
void PQsetSSLKeyPassHook_OpenSSL (PQsslKeyPassHook_OpenSSL_type hook)
 
int PQdefaultSSLKeyPassHook_OpenSSL (char *buf, int size, PGconn *conn)
 

Macro Definition Documentation

◆ LIBPQ_HAS_PIPELINING

#define LIBPQ_HAS_PIPELINING   1

Definition at line 36 of file libpq-fe.h.

◆ LIBPQ_HAS_SSL_LIBRARY_DETECTION

#define LIBPQ_HAS_SSL_LIBRARY_DETECTION   1

Definition at line 40 of file libpq-fe.h.

◆ LIBPQ_HAS_TRACE_FLAGS

#define LIBPQ_HAS_TRACE_FLAGS   1

Definition at line 38 of file libpq-fe.h.

◆ PG_COPYRES_ATTRS

#define PG_COPYRES_ATTRS   0x01

Definition at line 45 of file libpq-fe.h.

◆ PG_COPYRES_EVENTS

#define PG_COPYRES_EVENTS   0x04

Definition at line 47 of file libpq-fe.h.

◆ PG_COPYRES_NOTICEHOOKS

#define PG_COPYRES_NOTICEHOOKS   0x08

Definition at line 48 of file libpq-fe.h.

◆ PG_COPYRES_TUPLES

#define PG_COPYRES_TUPLES   0x02 /* Implies PG_COPYRES_ATTRS */

Definition at line 46 of file libpq-fe.h.

◆ PQ_QUERY_PARAM_MAX_LIMIT

#define PQ_QUERY_PARAM_MAX_LIMIT   65535

Definition at line 443 of file libpq-fe.h.

◆ PQfreeNotify

#define PQfreeNotify (   ptr)    PQfreemem(ptr)

Definition at line 557 of file libpq-fe.h.

◆ PQnoPasswordSupplied

#define PQnoPasswordSupplied   "fe_sendauth: no password supplied\n"

Definition at line 561 of file libpq-fe.h.

◆ PQsetdb

#define PQsetdb (   M_PGHOST,
  M_PGPORT,
  M_PGOPT,
  M_PGTTY,
  M_DBNAME 
)     PQsetdbLogin(M_PGHOST, M_PGPORT, M_PGOPT, M_PGTTY, M_DBNAME, NULL, NULL)

Definition at line 295 of file libpq-fe.h.

◆ PQTRACE_REGRESS_MODE

#define PQTRACE_REGRESS_MODE   (1<<1)

Definition at line 416 of file libpq-fe.h.

◆ PQTRACE_SUPPRESS_TIMESTAMPS

#define PQTRACE_SUPPRESS_TIMESTAMPS   (1<<0)

Definition at line 414 of file libpq-fe.h.

Typedef Documentation

◆ PGcancel

typedef struct pg_cancel PGcancel

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

◆ PGconn

typedef struct pg_conn PGconn

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

◆ PGnotify

typedef struct pgNotify PGnotify

◆ PGresAttDesc

typedef struct pgresAttDesc PGresAttDesc

◆ PGresult

typedef struct pg_result PGresult

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

◆ pgthreadlock_t

typedef void(* pgthreadlock_t) (int acquire)

Definition at line 404 of file libpq-fe.h.

◆ pqbool

typedef char pqbool

Definition at line 201 of file libpq-fe.h.

◆ PQconninfoOption

◆ PQnoticeProcessor

typedef void(* PQnoticeProcessor) (void *arg, const char *message)

Definition at line 198 of file libpq-fe.h.

◆ PQnoticeReceiver

typedef void(* PQnoticeReceiver) (void *arg, const PGresult *res)

Definition at line 197 of file libpq-fe.h.

◆ PQprintOpt

typedef struct _PQprintOpt PQprintOpt

◆ PQsslKeyPassHook_OpenSSL_type

typedef int(* PQsslKeyPassHook_OpenSSL_type) (char *buf, int size, PGconn *conn)

Definition at line 665 of file libpq-fe.h.

Enumeration Type Documentation

◆ ConnStatusType

Enumerator
CONNECTION_OK 
CONNECTION_BAD 
CONNECTION_STARTED 
CONNECTION_MADE 
CONNECTION_AWAITING_RESPONSE 
CONNECTION_AUTH_OK 
CONNECTION_SETENV 
CONNECTION_SSL_STARTUP 
CONNECTION_NEEDED 
CONNECTION_CHECK_WRITABLE 
CONNECTION_CONSUME 
CONNECTION_GSS_STARTUP 
CONNECTION_CHECK_TARGET 
CONNECTION_CHECK_STANDBY 

Definition at line 58 of file libpq-fe.h.

59 {
62  /* Non-blocking mode only below here */
63 
64  /*
65  * The existence of these should never be relied upon - they should only
66  * be used for user feedback or similar purposes.
67  */
68  CONNECTION_STARTED, /* Waiting for connection to be made. */
69  CONNECTION_MADE, /* Connection OK; waiting to send. */
70  CONNECTION_AWAITING_RESPONSE, /* Waiting for a response from the
71  * postmaster. */
72  CONNECTION_AUTH_OK, /* Received authentication; waiting for
73  * backend startup. */
74  CONNECTION_SETENV, /* This state is no longer used. */
75  CONNECTION_SSL_STARTUP, /* Negotiating SSL. */
76  CONNECTION_NEEDED, /* Internal state: connect() needed */
77  CONNECTION_CHECK_WRITABLE, /* Checking if session is read-write. */
78  CONNECTION_CONSUME, /* Consuming any extra messages. */
79  CONNECTION_GSS_STARTUP, /* Negotiating GSSAPI. */
80  CONNECTION_CHECK_TARGET, /* Checking target server properties. */
81  CONNECTION_CHECK_STANDBY /* Checking if server is in standby mode. */
ConnStatusType
Definition: libpq-fe.h:59
@ CONNECTION_CONSUME
Definition: libpq-fe.h:78
@ CONNECTION_CHECK_STANDBY
Definition: libpq-fe.h:81
@ CONNECTION_STARTED
Definition: libpq-fe.h:68
@ CONNECTION_AWAITING_RESPONSE
Definition: libpq-fe.h:70
@ CONNECTION_MADE
Definition: libpq-fe.h:69
@ CONNECTION_CHECK_WRITABLE
Definition: libpq-fe.h:77
@ CONNECTION_BAD
Definition: libpq-fe.h:61
@ CONNECTION_OK
Definition: libpq-fe.h:60
@ CONNECTION_GSS_STARTUP
Definition: libpq-fe.h:79
@ CONNECTION_SSL_STARTUP
Definition: libpq-fe.h:75
@ CONNECTION_AUTH_OK
Definition: libpq-fe.h:72
@ CONNECTION_CHECK_TARGET
Definition: libpq-fe.h:80
@ CONNECTION_NEEDED
Definition: libpq-fe.h:76
@ CONNECTION_SETENV
Definition: libpq-fe.h:74

◆ ExecStatusType

Enumerator
PGRES_EMPTY_QUERY 
PGRES_COMMAND_OK 
PGRES_TUPLES_OK 
PGRES_COPY_OUT 
PGRES_COPY_IN 
PGRES_BAD_RESPONSE 
PGRES_NONFATAL_ERROR 
PGRES_FATAL_ERROR 
PGRES_COPY_BOTH 
PGRES_SINGLE_TUPLE 
PGRES_PIPELINE_SYNC 
PGRES_PIPELINE_ABORTED 

Definition at line 94 of file libpq-fe.h.

95 {
96  PGRES_EMPTY_QUERY = 0, /* empty query string was executed */
97  PGRES_COMMAND_OK, /* a query command that doesn't return
98  * anything was executed properly by the
99  * backend */
100  PGRES_TUPLES_OK, /* a query command that returns tuples was
101  * executed properly by the backend, PGresult
102  * contains the result tuples */
103  PGRES_COPY_OUT, /* Copy Out data transfer in progress */
104  PGRES_COPY_IN, /* Copy In data transfer in progress */
105  PGRES_BAD_RESPONSE, /* an unexpected response was recv'd from the
106  * backend */
107  PGRES_NONFATAL_ERROR, /* notice or warning message */
108  PGRES_FATAL_ERROR, /* query failed */
109  PGRES_COPY_BOTH, /* Copy In/Out data transfer in progress */
110  PGRES_SINGLE_TUPLE, /* single tuple from larger resultset */
111  PGRES_PIPELINE_SYNC, /* pipeline synchronization point */
112  PGRES_PIPELINE_ABORTED /* Command didn't run because of an abort
113  * earlier in a pipeline */
ExecStatusType
Definition: libpq-fe.h:95
@ PGRES_COPY_IN
Definition: libpq-fe.h:104
@ PGRES_COPY_BOTH
Definition: libpq-fe.h:109
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:97
@ PGRES_FATAL_ERROR
Definition: libpq-fe.h:108
@ PGRES_SINGLE_TUPLE
Definition: libpq-fe.h:110
@ PGRES_COPY_OUT
Definition: libpq-fe.h:103
@ PGRES_EMPTY_QUERY
Definition: libpq-fe.h:96
@ PGRES_PIPELINE_SYNC
Definition: libpq-fe.h:111
@ PGRES_BAD_RESPONSE
Definition: libpq-fe.h:105
@ PGRES_PIPELINE_ABORTED
Definition: libpq-fe.h:112
@ PGRES_NONFATAL_ERROR
Definition: libpq-fe.h:107
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:100

◆ PGContextVisibility

Enumerator
PQSHOW_CONTEXT_NEVER 
PQSHOW_CONTEXT_ERRORS 
PQSHOW_CONTEXT_ALWAYS 

Definition at line 133 of file libpq-fe.h.

134 {
135  PQSHOW_CONTEXT_NEVER, /* never show CONTEXT field */
136  PQSHOW_CONTEXT_ERRORS, /* show CONTEXT for errors only (default) */
137  PQSHOW_CONTEXT_ALWAYS /* always show CONTEXT field */
PGContextVisibility
Definition: libpq-fe.h:134
@ PQSHOW_CONTEXT_NEVER
Definition: libpq-fe.h:135
@ PQSHOW_CONTEXT_ALWAYS
Definition: libpq-fe.h:137
@ PQSHOW_CONTEXT_ERRORS
Definition: libpq-fe.h:136

◆ PGPing

enum PGPing
Enumerator
PQPING_OK 
PQPING_REJECT 
PQPING_NO_RESPONSE 
PQPING_NO_ATTEMPT 

Definition at line 145 of file libpq-fe.h.

146 {
147  PQPING_OK, /* server is accepting connections */
148  PQPING_REJECT, /* server is alive but rejecting connections */
149  PQPING_NO_RESPONSE, /* could not establish connection */
150  PQPING_NO_ATTEMPT /* connection not attempted (bad params) */
151 } PGPing;
PGPing
Definition: libpq-fe.h:146
@ PQPING_OK
Definition: libpq-fe.h:147
@ PQPING_REJECT
Definition: libpq-fe.h:148
@ PQPING_NO_RESPONSE
Definition: libpq-fe.h:149
@ PQPING_NO_ATTEMPT
Definition: libpq-fe.h:150

◆ PGpipelineStatus

Enumerator
PQ_PIPELINE_OFF 
PQ_PIPELINE_ON 
PQ_PIPELINE_ABORTED 

Definition at line 156 of file libpq-fe.h.

157 {
PGpipelineStatus
Definition: libpq-fe.h:157
@ PQ_PIPELINE_OFF
Definition: libpq-fe.h:158
@ PQ_PIPELINE_ABORTED
Definition: libpq-fe.h:160
@ PQ_PIPELINE_ON
Definition: libpq-fe.h:159

◆ PGTransactionStatusType

Enumerator
PQTRANS_IDLE 
PQTRANS_ACTIVE 
PQTRANS_INTRANS 
PQTRANS_INERROR 
PQTRANS_UNKNOWN 

Definition at line 116 of file libpq-fe.h.

117 {
118  PQTRANS_IDLE, /* connection idle */
119  PQTRANS_ACTIVE, /* command in progress */
120  PQTRANS_INTRANS, /* idle, within transaction block */
121  PQTRANS_INERROR, /* idle, within failed transaction */
122  PQTRANS_UNKNOWN /* cannot determine status */
PGTransactionStatusType
Definition: libpq-fe.h:117
@ PQTRANS_INTRANS
Definition: libpq-fe.h:120
@ PQTRANS_IDLE
Definition: libpq-fe.h:118
@ PQTRANS_ACTIVE
Definition: libpq-fe.h:119
@ PQTRANS_UNKNOWN
Definition: libpq-fe.h:122
@ PQTRANS_INERROR
Definition: libpq-fe.h:121

◆ PGVerbosity

Enumerator
PQERRORS_TERSE 
PQERRORS_DEFAULT 
PQERRORS_VERBOSE 
PQERRORS_SQLSTATE 

Definition at line 125 of file libpq-fe.h.

126 {
127  PQERRORS_TERSE, /* single-line error messages */
128  PQERRORS_DEFAULT, /* recommended style */
129  PQERRORS_VERBOSE, /* all the facts, ma'am */
130  PQERRORS_SQLSTATE /* only error severity and SQLSTATE code */
131 } PGVerbosity;
PGVerbosity
Definition: libpq-fe.h:126
@ PQERRORS_VERBOSE
Definition: libpq-fe.h:129
@ PQERRORS_DEFAULT
Definition: libpq-fe.h:128
@ PQERRORS_TERSE
Definition: libpq-fe.h:127
@ PQERRORS_SQLSTATE
Definition: libpq-fe.h:130

◆ PostgresPollingStatusType

Enumerator
PGRES_POLLING_FAILED 
PGRES_POLLING_READING 
PGRES_POLLING_WRITING 
PGRES_POLLING_OK 
PGRES_POLLING_ACTIVE 

Definition at line 84 of file libpq-fe.h.

85 {
87  PGRES_POLLING_READING, /* These two indicate that one may */
88  PGRES_POLLING_WRITING, /* use select before polling again. */
90  PGRES_POLLING_ACTIVE /* unused; keep for awhile for backwards
91  * compatibility */
PostgresPollingStatusType
Definition: libpq-fe.h:85
@ PGRES_POLLING_ACTIVE
Definition: libpq-fe.h:90
@ PGRES_POLLING_OK
Definition: libpq-fe.h:89
@ PGRES_POLLING_READING
Definition: libpq-fe.h:87
@ PGRES_POLLING_WRITING
Definition: libpq-fe.h:88
@ PGRES_POLLING_FAILED
Definition: libpq-fe.h:86

Function Documentation

◆ lo_close()

int lo_close ( PGconn conn,
int  fd 
)

Definition at line 96 of file fe-lobj.c.

97 {
98  PQArgBlock argv[1];
99  PGresult *res;
100  int retval;
101  int result_len;
102 
103  if (lo_initialize(conn) < 0)
104  return -1;
105 
106  argv[0].isint = 1;
107  argv[0].len = 4;
108  argv[0].u.integer = fd;
110  &retval, &result_len, 1, argv, 1);
112  {
113  PQclear(res);
114  return retval;
115  }
116  else
117  {
118  PQclear(res);
119  return -1;
120  }
121 }
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2862
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3240
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:843
static int fd(const char *x, int i)
Definition: preproc-init.c:105
PGconn * conn
Definition: streamutil.c:54
int isint
Definition: libpq-fe.h:249
int integer
Definition: libpq-fe.h:253
union PQArgBlock::@162 u
Oid fn_lo_close
Definition: libpq-int.h:273
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:479

References conn, fd(), pgLobjfuncs::fn_lo_close, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

Referenced by dumpBlobs(), EndRestoreBlob(), exportFile(), importFile(), lo_export(), lo_import_internal(), my_truncate(), overwrite(), and pickout().

◆ lo_creat()

Oid lo_creat ( PGconn conn,
int  mode 
)

Definition at line 438 of file fe-lobj.c.

439 {
440  PQArgBlock argv[1];
441  PGresult *res;
442  int retval;
443  int result_len;
444 
445  if (lo_initialize(conn) < 0)
446  return InvalidOid;
447 
448  argv[0].isint = 1;
449  argv[0].len = 4;
450  argv[0].u.integer = mode;
452  &retval, &result_len, 1, argv, 1);
454  {
455  PQclear(res);
456  return (Oid) retval;
457  }
458  else
459  {
460  PQclear(res);
461  return InvalidOid;
462  }
463 }
static PgChecksumMode mode
Definition: pg_checksums.c:65
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
Oid fn_lo_creat
Definition: libpq-int.h:274

References conn, pgLobjfuncs::fn_lo_creat, PQArgBlock::integer, InvalidOid, PQArgBlock::isint, PQArgBlock::len, lo_initialize(), pg_conn::lobjfuncs, mode, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

Referenced by importFile(), and lo_import_internal().

◆ lo_create()

Oid lo_create ( PGconn conn,
Oid  lobjId 
)

Definition at line 474 of file fe-lobj.c.

475 {
476  PQArgBlock argv[1];
477  PGresult *res;
478  int retval;
479  int result_len;
480 
481  if (lo_initialize(conn) < 0)
482  return InvalidOid;
483 
484  /* Must check this on-the-fly because it's not there pre-8.1 */
485  if (conn->lobjfuncs->fn_lo_create == 0)
486  {
487  libpq_append_conn_error(conn, "cannot determine OID of function %s",
488  "lo_create");
489  return InvalidOid;
490  }
491 
492  argv[0].isint = 1;
493  argv[0].len = 4;
494  argv[0].u.integer = lobjId;
496  &retval, &result_len, 1, argv, 1);
498  {
499  PQclear(res);
500  return (Oid) retval;
501  }
502  else
503  {
504  PQclear(res);
505  return InvalidOid;
506  }
507 }
void libpq_append_conn_error(PGconn *conn, const char *fmt,...)
Definition: fe-misc.c:1312
Oid fn_lo_create
Definition: libpq-int.h:275

References conn, pgLobjfuncs::fn_lo_create, PQArgBlock::integer, InvalidOid, PQArgBlock::isint, PQArgBlock::len, libpq_append_conn_error(), lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

Referenced by lo_import_internal(), and StartRestoreBlob().

◆ lo_export()

int lo_export ( PGconn conn,
Oid  lobjId,
const char *  filename 
)

Definition at line 748 of file fe-lobj.c.

749 {
750  int result = 1;
751  int fd;
752  int nbytes,
753  tmp;
754  char buf[LO_BUFSIZE];
755  int lobj;
756  char sebuf[PG_STRERROR_R_BUFLEN];
757 
758  /*
759  * open the large object.
760  */
761  lobj = lo_open(conn, lobjId, INV_READ);
762  if (lobj == -1)
763  {
764  /* we assume lo_open() already set a suitable error message */
765  return -1;
766  }
767 
768  /*
769  * create the file to be written to
770  */
771  fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC | PG_BINARY, 0666);
772  if (fd < 0)
773  {
774  /* We must do lo_close before setting the errorMessage */
775  int save_errno = errno;
776 
777  (void) lo_close(conn, lobj);
778  /* deliberately overwrite any error from lo_close */
780  libpq_append_conn_error(conn, "could not open file \"%s\": %s",
781  filename,
782  strerror_r(save_errno, sebuf, sizeof(sebuf)));
783  return -1;
784  }
785 
786  /*
787  * read in from the large object and write to the file
788  */
789  while ((nbytes = lo_read(conn, lobj, buf, LO_BUFSIZE)) > 0)
790  {
791  tmp = write(fd, buf, nbytes);
792  if (tmp != nbytes)
793  {
794  /* We must do lo_close before setting the errorMessage */
795  int save_errno = errno;
796 
797  (void) lo_close(conn, lobj);
798  (void) close(fd);
799  /* deliberately overwrite any error from lo_close */
801  libpq_append_conn_error(conn, "could not write to file \"%s\": %s",
802  filename,
803  strerror_r(save_errno, sebuf, sizeof(sebuf)));
804  return -1;
805  }
806  }
807 
808  /*
809  * If lo_read() failed, we are now in an aborted transaction so there's no
810  * need for lo_close(); furthermore, if we tried it we'd overwrite the
811  * useful error result with a useless one. So skip lo_close() if we got a
812  * failure result.
813  */
814  if (nbytes < 0 ||
815  lo_close(conn, lobj) != 0)
816  {
817  /* assume lo_read() or lo_close() left a suitable error message */
818  result = -1;
819  }
820 
821  /* if we already failed, don't overwrite that msg with a close error */
822  if (close(fd) != 0 && result >= 0)
823  {
824  libpq_append_conn_error(conn, "could not write to file \"%s\": %s",
825  filename, strerror_r(errno, sebuf, sizeof(sebuf)));
826  result = -1;
827  }
828 
829  return result;
830 }
#define PG_BINARY
Definition: c.h:1209
int lo_close(PGconn *conn, int fd)
Definition: fe-lobj.c:96
#define LO_BUFSIZE
Definition: fe-lobj.c:42
int lo_read(PGconn *conn, int fd, char *buf, size_t len)
Definition: fe-lobj.c:245
int lo_open(PGconn *conn, Oid lobjId, int mode)
Definition: fe-lobj.c:57
#define close(a)
Definition: win32.h:12
#define write(a, b, c)
Definition: win32.h:14
#define INV_READ
Definition: libpq-fs.h:22
#define pqClearConnErrorState(conn)
Definition: libpq-int.h:855
static char * filename
Definition: pg_dumpall.c:119
static char * buf
Definition: pg_test_fsync.c:67
#define PG_STRERROR_R_BUFLEN
Definition: port.h:256
#define strerror_r
Definition: port.h:255

References buf, close, conn, fd(), filename, INV_READ, libpq_append_conn_error(), LO_BUFSIZE, lo_close(), lo_open(), lo_read(), PG_BINARY, PG_STRERROR_R_BUFLEN, pqClearConnErrorState, strerror_r, and write.

Referenced by do_lo_export(), and main().

◆ lo_import()

Oid lo_import ( PGconn conn,
const char *  filename 
)

Definition at line 626 of file fe-lobj.c.

627 {
629 }
static Oid lo_import_internal(PGconn *conn, const char *filename, Oid oid)
Definition: fe-lobj.c:647

References conn, filename, InvalidOid, and lo_import_internal().

Referenced by do_lo_import(), and main().

◆ lo_import_with_oid()

Oid lo_import_with_oid ( PGconn conn,
const char *  filename,
Oid  lobjId 
)

Definition at line 641 of file fe-lobj.c.

642 {
643  return lo_import_internal(conn, filename, lobjId);
644 }

References conn, filename, and lo_import_internal().

◆ lo_lseek()

int lo_lseek ( PGconn conn,
int  fd,
int  offset,
int  whence 
)

Definition at line 344 of file fe-lobj.c.

345 {
346  PQArgBlock argv[3];
347  PGresult *res;
348  int retval;
349  int result_len;
350 
351  if (lo_initialize(conn) < 0)
352  return -1;
353 
354  argv[0].isint = 1;
355  argv[0].len = 4;
356  argv[0].u.integer = fd;
357 
358  argv[1].isint = 1;
359  argv[1].len = 4;
360  argv[1].u.integer = offset;
361 
362  argv[2].isint = 1;
363  argv[2].len = 4;
364  argv[2].u.integer = whence;
365 
367  &retval, &result_len, 1, argv, 3);
369  {
370  PQclear(res);
371  return retval;
372  }
373  else
374  {
375  PQclear(res);
376  return -1;
377  }
378 }
Oid fn_lo_lseek
Definition: libpq-int.h:277

References conn, fd(), pgLobjfuncs::fn_lo_lseek, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

Referenced by overwrite(), and pickout().

◆ lo_lseek64()

pg_int64 lo_lseek64 ( PGconn conn,
int  fd,
pg_int64  offset,
int  whence 
)

Definition at line 385 of file fe-lobj.c.

386 {
387  PQArgBlock argv[3];
388  PGresult *res;
389  pg_int64 retval;
390  int result_len;
391 
392  if (lo_initialize(conn) < 0)
393  return -1;
394 
395  if (conn->lobjfuncs->fn_lo_lseek64 == 0)
396  {
397  libpq_append_conn_error(conn, "cannot determine OID of function %s",
398  "lo_lseek64");
399  return -1;
400  }
401 
402  argv[0].isint = 1;
403  argv[0].len = 4;
404  argv[0].u.integer = fd;
405 
406  offset = lo_hton64(offset);
407  argv[1].isint = 0;
408  argv[1].len = 8;
409  argv[1].u.ptr = (int *) &offset;
410 
411  argv[2].isint = 1;
412  argv[2].len = 4;
413  argv[2].u.integer = whence;
414 
416  (void *) &retval, &result_len, 0, argv, 3);
417  if (PQresultStatus(res) == PGRES_COMMAND_OK && result_len == 8)
418  {
419  PQclear(res);
420  return lo_ntoh64(retval);
421  }
422  else
423  {
424  PQclear(res);
425  return -1;
426  }
427 }
static pg_int64 lo_ntoh64(pg_int64 net64)
Definition: fe-lobj.c:1048
static pg_int64 lo_hton64(pg_int64 host64)
Definition: fe-lobj.c:1023
PG_INT64_TYPE pg_int64
Definition: postgres_ext.h:47
int * ptr
Definition: libpq-fe.h:252
Oid fn_lo_lseek64
Definition: libpq-int.h:278

References conn, fd(), pgLobjfuncs::fn_lo_lseek64, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, libpq_append_conn_error(), lo_hton64(), lo_initialize(), lo_ntoh64(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), PQArgBlock::ptr, res, and PQArgBlock::u.

Referenced by overwrite(), and pickout().

◆ lo_open()

int lo_open ( PGconn conn,
Oid  lobjId,
int  mode 
)

Definition at line 57 of file fe-lobj.c.

58 {
59  int fd;
60  int result_len;
61  PQArgBlock argv[2];
62  PGresult *res;
63 
64  if (lo_initialize(conn) < 0)
65  return -1;
66 
67  argv[0].isint = 1;
68  argv[0].len = 4;
69  argv[0].u.integer = lobjId;
70 
71  argv[1].isint = 1;
72  argv[1].len = 4;
73  argv[1].u.integer = mode;
74 
75  res = PQfn(conn, conn->lobjfuncs->fn_lo_open, &fd, &result_len, 1, argv, 2);
77  {
78  PQclear(res);
79  return fd;
80  }
81  else
82  {
83  PQclear(res);
84  return -1;
85  }
86 }
Oid fn_lo_open
Definition: libpq-int.h:272

References conn, fd(), pgLobjfuncs::fn_lo_open, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, lo_initialize(), pg_conn::lobjfuncs, mode, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

Referenced by dumpBlobs(), exportFile(), importFile(), lo_export(), lo_import_internal(), my_truncate(), overwrite(), pickout(), and StartRestoreBlob().

◆ lo_read()

int lo_read ( PGconn conn,
int  fd,
char *  buf,
size_t  len 
)

Definition at line 245 of file fe-lobj.c.

246 {
247  PQArgBlock argv[2];
248  PGresult *res;
249  int result_len;
250 
251  if (lo_initialize(conn) < 0)
252  return -1;
253 
254  /*
255  * Long ago, somebody thought it'd be a good idea to declare this function
256  * as taking size_t ... but the underlying backend function only accepts a
257  * signed int32 length. So throw error if the given value overflows
258  * int32.
259  */
260  if (len > (size_t) INT_MAX)
261  {
262  libpq_append_conn_error(conn, "argument of lo_read exceeds integer range");
263  return -1;
264  }
265 
266  argv[0].isint = 1;
267  argv[0].len = 4;
268  argv[0].u.integer = fd;
269 
270  argv[1].isint = 1;
271  argv[1].len = 4;
272  argv[1].u.integer = (int) len;
273 
275  (void *) buf, &result_len, 0, argv, 2);
277  {
278  PQclear(res);
279  return result_len;
280  }
281  else
282  {
283  PQclear(res);
284  return -1;
285  }
286 }
const void size_t len
Oid fn_lo_read
Definition: libpq-int.h:283

References buf, conn, fd(), pgLobjfuncs::fn_lo_read, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, len, libpq_append_conn_error(), lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

Referenced by lo_export().

◆ lo_tell()

int lo_tell ( PGconn conn,
int  fd 
)

Definition at line 515 of file fe-lobj.c.

516 {
517  int retval;
518  PQArgBlock argv[1];
519  PGresult *res;
520  int result_len;
521 
522  if (lo_initialize(conn) < 0)
523  return -1;
524 
525  argv[0].isint = 1;
526  argv[0].len = 4;
527  argv[0].u.integer = fd;
528 
530  &retval, &result_len, 1, argv, 1);
532  {
533  PQclear(res);
534  return retval;
535  }
536  else
537  {
538  PQclear(res);
539  return -1;
540  }
541 }
Oid fn_lo_tell
Definition: libpq-int.h:279

References conn, fd(), pgLobjfuncs::fn_lo_tell, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

◆ lo_tell64()

pg_int64 lo_tell64 ( PGconn conn,
int  fd 
)

Definition at line 548 of file fe-lobj.c.

549 {
550  pg_int64 retval;
551  PQArgBlock argv[1];
552  PGresult *res;
553  int result_len;
554 
555  if (lo_initialize(conn) < 0)
556  return -1;
557 
558  if (conn->lobjfuncs->fn_lo_tell64 == 0)
559  {
560  libpq_append_conn_error(conn, "cannot determine OID of function %s",
561  "lo_tell64");
562  return -1;
563  }
564 
565  argv[0].isint = 1;
566  argv[0].len = 4;
567  argv[0].u.integer = fd;
568 
570  (void *) &retval, &result_len, 0, argv, 1);
571  if (PQresultStatus(res) == PGRES_COMMAND_OK && result_len == 8)
572  {
573  PQclear(res);
574  return lo_ntoh64(retval);
575  }
576  else
577  {
578  PQclear(res);
579  return -1;
580  }
581 }
Oid fn_lo_tell64
Definition: libpq-int.h:280

References conn, fd(), pgLobjfuncs::fn_lo_tell64, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, libpq_append_conn_error(), lo_initialize(), lo_ntoh64(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

Referenced by pickout().

◆ lo_truncate()

int lo_truncate ( PGconn conn,
int  fd,
size_t  len 
)

Definition at line 131 of file fe-lobj.c.

132 {
133  PQArgBlock argv[2];
134  PGresult *res;
135  int retval;
136  int result_len;
137 
138  if (lo_initialize(conn) < 0)
139  return -1;
140 
141  /* Must check this on-the-fly because it's not there pre-8.3 */
142  if (conn->lobjfuncs->fn_lo_truncate == 0)
143  {
144  libpq_append_conn_error(conn, "cannot determine OID of function %s",
145  "lo_truncate");
146  return -1;
147  }
148 
149  /*
150  * Long ago, somebody thought it'd be a good idea to declare this function
151  * as taking size_t ... but the underlying backend function only accepts a
152  * signed int32 length. So throw error if the given value overflows
153  * int32. (A possible alternative is to automatically redirect the call
154  * to lo_truncate64; but if the caller wanted to rely on that backend
155  * function being available, he could have called lo_truncate64 for
156  * himself.)
157  */
158  if (len > (size_t) INT_MAX)
159  {
160  libpq_append_conn_error(conn, "argument of lo_truncate exceeds integer range");
161  return -1;
162  }
163 
164  argv[0].isint = 1;
165  argv[0].len = 4;
166  argv[0].u.integer = fd;
167 
168  argv[1].isint = 1;
169  argv[1].len = 4;
170  argv[1].u.integer = (int) len;
171 
173  &retval, &result_len, 1, argv, 2);
174 
176  {
177  PQclear(res);
178  return retval;
179  }
180  else
181  {
182  PQclear(res);
183  return -1;
184  }
185 }
Oid fn_lo_truncate
Definition: libpq-int.h:281

References conn, fd(), pgLobjfuncs::fn_lo_truncate, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, len, libpq_append_conn_error(), lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

◆ lo_truncate64()

int lo_truncate64 ( PGconn conn,
int  fd,
pg_int64  len 
)

Definition at line 195 of file fe-lobj.c.

196 {
197  PQArgBlock argv[2];
198  PGresult *res;
199  int retval;
200  int result_len;
201 
202  if (lo_initialize(conn) < 0)
203  return -1;
204 
205  if (conn->lobjfuncs->fn_lo_truncate64 == 0)
206  {
207  libpq_append_conn_error(conn, "cannot determine OID of function %s",
208  "lo_truncate64");
209  return -1;
210  }
211 
212  argv[0].isint = 1;
213  argv[0].len = 4;
214  argv[0].u.integer = fd;
215 
216  len = lo_hton64(len);
217  argv[1].isint = 0;
218  argv[1].len = 8;
219  argv[1].u.ptr = (int *) &len;
220 
222  &retval, &result_len, 1, argv, 2);
223 
225  {
226  PQclear(res);
227  return retval;
228  }
229  else
230  {
231  PQclear(res);
232  return -1;
233  }
234 }
Oid fn_lo_truncate64
Definition: libpq-int.h:282

References conn, fd(), pgLobjfuncs::fn_lo_truncate64, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, len, libpq_append_conn_error(), lo_hton64(), lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), PQArgBlock::ptr, res, and PQArgBlock::u.

Referenced by my_truncate().

◆ lo_unlink()

int lo_unlink ( PGconn conn,
Oid  lobjId 
)

Definition at line 589 of file fe-lobj.c.

590 {
591  PQArgBlock argv[1];
592  PGresult *res;
593  int result_len;
594  int retval;
595 
596  if (lo_initialize(conn) < 0)
597  return -1;
598 
599  argv[0].isint = 1;
600  argv[0].len = 4;
601  argv[0].u.integer = lobjId;
602 
604  &retval, &result_len, 1, argv, 1);
606  {
607  PQclear(res);
608  return retval;
609  }
610  else
611  {
612  PQclear(res);
613  return -1;
614  }
615 }
Oid fn_lo_unlink
Definition: libpq-int.h:276

References conn, pgLobjfuncs::fn_lo_unlink, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

Referenced by do_lo_unlink(), and vacuumlo().

◆ lo_write()

int lo_write ( PGconn conn,
int  fd,
const char *  buf,
size_t  len 
)

Definition at line 295 of file fe-lobj.c.

296 {
297  PQArgBlock argv[2];
298  PGresult *res;
299  int result_len;
300  int retval;
301 
302  if (lo_initialize(conn) < 0)
303  return -1;
304 
305  /*
306  * Long ago, somebody thought it'd be a good idea to declare this function
307  * as taking size_t ... but the underlying backend function only accepts a
308  * signed int32 length. So throw error if the given value overflows
309  * int32.
310  */
311  if (len > (size_t) INT_MAX)
312  {
313  libpq_append_conn_error(conn, "argument of lo_write exceeds integer range");
314  return -1;
315  }
316 
317  argv[0].isint = 1;
318  argv[0].len = 4;
319  argv[0].u.integer = fd;
320 
321  argv[1].isint = 0;
322  argv[1].len = (int) len;
323  argv[1].u.ptr = (int *) unconstify(char *, buf);
324 
326  &retval, &result_len, 1, argv, 2);
328  {
329  PQclear(res);
330  return retval;
331  }
332  else
333  {
334  PQclear(res);
335  return -1;
336  }
337 }
#define unconstify(underlying_type, expr)
Definition: c.h:1181
Oid fn_lo_write
Definition: libpq-int.h:284

References buf, conn, fd(), pgLobjfuncs::fn_lo_write, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, len, libpq_append_conn_error(), lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), PQArgBlock::ptr, res, PQArgBlock::u, and unconstify.

Referenced by lo_import_internal().

◆ pg_char_to_encoding()

int pg_char_to_encoding ( const char *  name)

Definition at line 550 of file encnames.c.

551 {
552  unsigned int nel = lengthof(pg_encname_tbl);
553  const pg_encname *base = pg_encname_tbl,
554  *last = base + nel - 1,
555  *position;
556  int result;
557  char buff[NAMEDATALEN],
558  *key;
559 
560  if (name == NULL || *name == '\0')
561  return -1;
562 
563  if (strlen(name) >= NAMEDATALEN)
564  return -1; /* it's certainly not in the table */
565 
566  key = clean_encoding_name(name, buff);
567 
568  while (last >= base)
569  {
570  position = base + ((last - base) >> 1);
571  result = key[0] - position->name[0];
572 
573  if (result == 0)
574  {
575  result = strcmp(key, position->name);
576  if (result == 0)
577  return position->encoding;
578  }
579  if (result < 0)
580  last = position - 1;
581  else
582  base = position + 1;
583  }
584  return -1;
585 }
#define lengthof(array)
Definition: c.h:724
static const pg_encname pg_encname_tbl[]
Definition: encnames.c:39
static char * clean_encoding_name(const char *key, char *newkey)
Definition: encnames.c:525
const char * name
Definition: encode.c:561
#define NAMEDATALEN

References clean_encoding_name(), sort-test::key, lengthof, name, NAMEDATALEN, and pg_encname_tbl.

Referenced by CreateConversionCommand(), length_in_encoding(), main(), PG_char_to_encoding(), pg_convert(), pg_get_utf8_id(), pg_valid_client_encoding(), pg_valid_server_encoding(), PQenv2encoding(), pqSaveParameterStatus(), ProcessCopyOptions(), processEncodingEntry(), test_enc_conversion(), and to_ascii_encname().

◆ pg_encoding_to_char()

◆ pg_valid_server_encoding_id()

int pg_valid_server_encoding_id ( int  encoding)

Definition at line 514 of file encnames.c.

515 {
517 }
#define PG_VALID_BE_ENCODING(_enc)
Definition: pg_wchar.h:281

References encoding, and PG_VALID_BE_ENCODING.

Referenced by setup_locale_encoding().

◆ PQbackendPID()

int PQbackendPID ( const PGconn conn)

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

6778 {
6779  if (!conn || conn->status != CONNECTION_OK)
6780  return 0;
6781  return conn->be_pid;
6782 }
int be_pid
Definition: libpq-int.h:470
ConnStatusType status
Definition: libpq-int.h:413

References pg_conn::be_pid, conn, CONNECTION_OK, and pg_conn::status.

Referenced by get_prompt(), libpqrcv_get_backend_pid(), main(), and StartLogStreamer().

◆ PQbinaryTuples()

int PQbinaryTuples ( const PGresult res)

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

3327 {
3328  if (!res)
3329  return 0;
3330  return res->binary;
3331 }
int binary
Definition: libpq-int.h:181

References pg_result::binary, and res.

Referenced by HandleCopyResult().

◆ PQcancel()

int PQcancel ( PGcancel cancel,
char *  errbuf,
int  errbufsize 
)

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

4350 {
4351  int save_errno = SOCK_ERRNO;
4352  pgsocket tmpsock = PGINVALID_SOCKET;
4353  int maxlen;
4354  struct
4355  {
4356  uint32 packetlen;
4358  } crp;
4359 
4360  if (!cancel)
4361  {
4362  strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
4363  /* strlcpy probably doesn't change errno, but be paranoid */
4364  SOCK_ERRNO_SET(save_errno);
4365  return false;
4366  }
4367 
4368  /*
4369  * We need to open a temporary connection to the postmaster. Do this with
4370  * only kernel calls.
4371  */
4372  if ((tmpsock = socket(cancel->raddr.addr.ss_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
4373  {
4374  strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
4375  goto cancel_errReturn;
4376  }
4377 
4378  /*
4379  * Since this connection will only be used to send a single packet of
4380  * data, we don't need NODELAY. We also don't set the socket to
4381  * nonblocking mode, because the API definition of PQcancel requires the
4382  * cancel to be sent in a blocking way.
4383  *
4384  * We do set socket options related to keepalives and other TCP timeouts.
4385  * This ensures that this function does not block indefinitely when
4386  * reasonable keepalive and timeout settings have been provided.
4387  */
4388  if (cancel->raddr.addr.ss_family != AF_UNIX &&
4389  cancel->keepalives != 0)
4390  {
4391 #ifndef WIN32
4392  if (!optional_setsockopt(tmpsock, SOL_SOCKET, SO_KEEPALIVE, 1))
4393  {
4394  strlcpy(errbuf, "PQcancel() -- setsockopt(SO_KEEPALIVE) failed: ", errbufsize);
4395  goto cancel_errReturn;
4396  }
4397 
4398 #ifdef PG_TCP_KEEPALIVE_IDLE
4399  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
4400  cancel->keepalives_idle))
4401  {
4402  strlcpy(errbuf, "PQcancel() -- setsockopt(" PG_TCP_KEEPALIVE_IDLE_STR ") failed: ", errbufsize);
4403  goto cancel_errReturn;
4404  }
4405 #endif
4406 
4407 #ifdef TCP_KEEPINTVL
4408  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_KEEPINTVL,
4409  cancel->keepalives_interval))
4410  {
4411  strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_KEEPINTVL) failed: ", errbufsize);
4412  goto cancel_errReturn;
4413  }
4414 #endif
4415 
4416 #ifdef TCP_KEEPCNT
4417  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_KEEPCNT,
4418  cancel->keepalives_count))
4419  {
4420  strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_KEEPCNT) failed: ", errbufsize);
4421  goto cancel_errReturn;
4422  }
4423 #endif
4424 
4425 #else /* WIN32 */
4426 
4427 #ifdef SIO_KEEPALIVE_VALS
4428  if (!setKeepalivesWin32(tmpsock,
4429  cancel->keepalives_idle,
4430  cancel->keepalives_interval))
4431  {
4432  strlcpy(errbuf, "PQcancel() -- WSAIoctl(SIO_KEEPALIVE_VALS) failed: ", errbufsize);
4433  goto cancel_errReturn;
4434  }
4435 #endif /* SIO_KEEPALIVE_VALS */
4436 #endif /* WIN32 */
4437 
4438  /* TCP_USER_TIMEOUT works the same way on Unix and Windows */
4439 #ifdef TCP_USER_TIMEOUT
4440  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_USER_TIMEOUT,
4441  cancel->pgtcp_user_timeout))
4442  {
4443  strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_USER_TIMEOUT) failed: ", errbufsize);
4444  goto cancel_errReturn;
4445  }
4446 #endif
4447  }
4448 
4449 retry3:
4450  if (connect(tmpsock, (struct sockaddr *) &cancel->raddr.addr,
4451  cancel->raddr.salen) < 0)
4452  {
4453  if (SOCK_ERRNO == EINTR)
4454  /* Interrupted system call - we'll just try again */
4455  goto retry3;
4456  strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
4457  goto cancel_errReturn;
4458  }
4459 
4460  /* Create and send the cancel request packet. */
4461 
4462  crp.packetlen = pg_hton32((uint32) sizeof(crp));
4463  crp.cp.cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE);
4464  crp.cp.backendPID = pg_hton32(cancel->be_pid);
4465  crp.cp.cancelAuthCode = pg_hton32(cancel->be_key);
4466 
4467 retry4:
4468  if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
4469  {
4470  if (SOCK_ERRNO == EINTR)
4471  /* Interrupted system call - we'll just try again */
4472  goto retry4;
4473  strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
4474  goto cancel_errReturn;
4475  }
4476 
4477  /*
4478  * Wait for the postmaster to close the connection, which indicates that
4479  * it's processed the request. Without this delay, we might issue another
4480  * command only to find that our cancel zaps that command instead of the
4481  * one we thought we were canceling. Note we don't actually expect this
4482  * read to obtain any data, we are just waiting for EOF to be signaled.
4483  */
4484 retry5:
4485  if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
4486  {
4487  if (SOCK_ERRNO == EINTR)
4488  /* Interrupted system call - we'll just try again */
4489  goto retry5;
4490  /* we ignore other error conditions */
4491  }
4492 
4493  /* All done */
4494  closesocket(tmpsock);
4495  SOCK_ERRNO_SET(save_errno);
4496  return true;
4497 
4498 cancel_errReturn:
4499 
4500  /*
4501  * Make sure we don't overflow the error buffer. Leave space for the \n at
4502  * the end, and for the terminating zero.
4503  */
4504  maxlen = errbufsize - strlen(errbuf) - 2;
4505  if (maxlen >= 0)
4506  {
4507  /*
4508  * We can't invoke strerror here, since it's not signal-safe. Settle
4509  * for printing the decimal value of errno. Even that has to be done
4510  * the hard way.
4511  */
4512  int val = SOCK_ERRNO;
4513  char buf[32];
4514  char *bufp;
4515 
4516  bufp = buf + sizeof(buf) - 1;
4517  *bufp = '\0';
4518  do
4519  {
4520  *(--bufp) = (val % 10) + '0';
4521  val /= 10;
4522  } while (val > 0);
4523  bufp -= 6;
4524  memcpy(bufp, "error ", 6);
4525  strncat(errbuf, bufp, maxlen);
4526  strcat(errbuf, "\n");
4527  }
4528  if (tmpsock != PGINVALID_SOCKET)
4529  closesocket(tmpsock);
4530  SOCK_ERRNO_SET(save_errno);
4531  return false;
4532 }
unsigned int uint32
Definition: c.h:442
static bool optional_setsockopt(int fd, int protoid, int optid, int value)
Definition: fe-connect.c:4317
long val
Definition: informix.c:664
#define SOCK_ERRNO
Definition: libpq-int.h:903
#define SOCK_ERRNO_SET(e)
Definition: libpq-int.h:905
#define pg_hton32(x)
Definition: pg_bswap.h:121
int pgsocket
Definition: port.h:29
#define PGINVALID_SOCKET
Definition: port.h:31
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define closesocket
Definition: port.h:349
#define CANCEL_REQUEST_CODE
Definition: pqcomm.h:138
ProtocolVersion MsgType
Definition: pqcomm.h:89
struct sockaddr_storage addr
Definition: pqcomm.h:26
socklen_t salen
Definition: pqcomm.h:27
int pgtcp_user_timeout
Definition: libpq-int.h:604
int keepalives_interval
Definition: libpq-int.h:607
int keepalives_idle
Definition: libpq-int.h:606
int keepalives_count
Definition: libpq-int.h:609
SockAddr raddr
Definition: libpq-int.h:601
int be_pid
Definition: libpq-int.h:602
int keepalives
Definition: libpq-int.h:605
int be_key
Definition: libpq-int.h:603
#define EINTR
Definition: win32_port.h:369
#define recv(s, buf, len, flags)
Definition: win32_port.h:493
#define send(s, buf, len, flags)
Definition: win32_port.h:494
#define socket(af, type, protocol)
Definition: win32_port.h:487
#define connect(s, name, namelen)
Definition: win32_port.h:491

References SockAddr::addr, pg_cancel::be_key, pg_cancel::be_pid, buf, CANCEL_REQUEST_CODE, closesocket, connect, EINTR, pg_cancel::keepalives, pg_cancel::keepalives_count, pg_cancel::keepalives_idle, pg_cancel::keepalives_interval, optional_setsockopt(), pg_hton32, PGINVALID_SOCKET, pg_cancel::pgtcp_user_timeout, pg_cancel::raddr, recv, SockAddr::salen, send, SOCK_ERRNO, SOCK_ERRNO_SET, socket, strlcpy(), and val.

Referenced by dblink_cancel_query(), DisconnectDatabase(), disconnectDatabase(), handle_sigint(), pgfdw_cancel_query(), PQrequestCancel(), ShutdownWorkersHard(), sigTermHandler(), and try_complete_step().

◆ PQclear()

void PQclear ( PGresult res)

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

719 {
720  PGresult_data *block;
721  int i;
722 
723  /* As a convenience, do nothing for a NULL pointer */
724  if (!res)
725  return;
726  /* Also, do nothing if the argument is OOM_result */
727  if ((const PGresult *) res == &OOM_result)
728  return;
729 
730  /* Close down any events we may have */
731  for (i = 0; i < res->nEvents; i++)
732  {
733  /* only send DESTROY to successfully-initialized event procs */
735  {
737 
738  evt.result = res;
739  (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
740  res->events[i].passThrough);
741  }
742  free(res->events[i].name);
743  }
744 
745  free(res->events);
746 
747  /* Free all the subsidiary blocks */
748  while ((block = res->curBlock) != NULL)
749  {
750  res->curBlock = block->next;
751  free(block);
752  }
753 
754  /* Free the top-level tuple pointer array */
755  free(res->tuples);
756 
757  /* zero out the pointer fields to catch programming errors */
758  res->attDescs = NULL;
759  res->tuples = NULL;
760  res->paramDescs = NULL;
761  res->errFields = NULL;
762  res->events = NULL;
763  res->nEvents = 0;
764  /* res->curBlock was zeroed out earlier */
765 
766  /* Free the PGresult structure itself */
767  free(res);
768 }
static const PGresult OOM_result
Definition: fe-exec.c:48
#define free(a)
Definition: header.h:65
int i
Definition: isn.c:73
@ PGEVT_RESULTDESTROY
Definition: libpq-events.h:34
void * passThrough
Definition: libpq-int.h:164
char * name
Definition: libpq-int.h:163
PGEventProc proc
Definition: libpq-int.h:162
bool resultInitialized
Definition: libpq-int.h:166
int nEvents
Definition: libpq-int.h:190
PGresAttValue ** tuples
Definition: libpq-int.h:174
PGresAttDesc * attDescs
Definition: libpq-int.h:173
PGMessageField * errFields
Definition: libpq-int.h:199
PGresParamDesc * paramDescs
Definition: libpq-int.h:178
PGEvent * events
Definition: libpq-int.h:189
PGresult_data * curBlock
Definition: libpq-int.h:210
PGresult_data * next
Definition: libpq-int.h:107

References pg_result::attDescs, pg_result::curBlock, pg_result::errFields, pg_result::events, free, i, PGEvent::name, pg_result::nEvents, pgresult_data::next, OOM_result, pg_result::paramDescs, PGEvent::passThrough, PGEVT_RESULTDESTROY, PGEvent::proc, res, PGEventResultDestroy::result, PGEvent::resultInitialized, and pg_result::tuples.

Referenced by pqClearAsyncResult(), PQcopyResult(), PQexecFinish(), PQexecStart(), pqInternalNotice(), PQmakeEmptyPGresult(), and pqRowProcessor().

◆ PQclientEncoding()

int PQclientEncoding ( const PGconn conn)

◆ PQcmdStatus()

char* PQcmdStatus ( PGresult res)

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

3582 {
3583  if (!res)
3584  return NULL;
3585  return res->cmdStatus;
3586 }
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:180

References pg_result::cmdStatus, and res.

Referenced by dblink_exec(), ecpg_process_output(), ExecQueryAndProcessResults(), materializeResult(), PrintQueryResult(), PrintQueryStatus(), and test_pipelined_insert().

◆ PQcmdTuples()

char* PQcmdTuples ( PGresult res)

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

3652 {
3653  char *p,
3654  *c;
3655 
3656  if (!res)
3657  return "";
3658 
3659  if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3660  {
3661  p = res->cmdStatus + 7;
3662  /* INSERT: skip oid and space */
3663  while (*p && *p != ' ')
3664  p++;
3665  if (*p == 0)
3666  goto interpret_error; /* no space? */
3667  p++;
3668  }
3669  else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3670  strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3671  strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3672  p = res->cmdStatus + 7;
3673  else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0 ||
3674  strncmp(res->cmdStatus, "MERGE ", 6) == 0)
3675  p = res->cmdStatus + 6;
3676  else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3677  strncmp(res->cmdStatus, "COPY ", 5) == 0)
3678  p = res->cmdStatus + 5;
3679  else
3680  return "";
3681 
3682  /* check that we have an integer (at least one digit, nothing else) */
3683  for (c = p; *c; c++)
3684  {
3685  if (!isdigit((unsigned char) *c))
3686  goto interpret_error;
3687  }
3688  if (c == p)
3689  goto interpret_error;
3690 
3691  return p;
3692 
3693 interpret_error:
3695  "could not interpret result from server: %s",
3696  res->cmdStatus);
3697  return "";
3698 }
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:933
char * c
PGNoticeHooks noticeHooks
Definition: libpq-int.h:188

References pg_result::cmdStatus, pg_result::noticeHooks, pqInternalNotice(), and res.

Referenced by ecpg_process_output(), execute_dml_stmt(), execute_foreign_modify(), and SetResultVariables().

◆ PQconndefaults()

PQconninfoOption* PQconndefaults ( void  )

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

1448 {
1449  PQExpBufferData errorBuf;
1450  PQconninfoOption *connOptions;
1451 
1452  /* We don't actually report any errors here, but callees want a buffer */
1453  initPQExpBuffer(&errorBuf);
1454  if (PQExpBufferDataBroken(errorBuf))
1455  return NULL; /* out of memory already :-( */
1456 
1457  connOptions = conninfo_init(&errorBuf);
1458  if (connOptions != NULL)
1459  {
1460  /* pass NULL errorBuf to ignore errors */
1461  if (!conninfo_add_defaults(connOptions, NULL))
1462  {
1463  PQconninfoFree(connOptions);
1464  connOptions = NULL;
1465  }
1466  }
1467 
1468  termPQExpBuffer(&errorBuf);
1469  return connOptions;
1470 }
static PQconninfoOption * conninfo_init(PQExpBuffer errorMessage)
Definition: fe-connect.c:5379
static bool conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
Definition: fe-connect.c:5806
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:6576
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67

References conninfo_add_defaults(), conninfo_init(), initPQExpBuffer(), PQconninfoFree(), PQExpBufferDataBroken, and termPQExpBuffer().

Referenced by check_pghost_envvar(), dblink_fdw_validator(), do_connect(), get_connect_string(), InitPgFdwOptions(), and main().

◆ PQconnectdb()

PGconn* PQconnectdb ( const char *  conninfo)

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

708 {
709  PGconn *conn = PQconnectStart(conninfo);
710 
711  if (conn && conn->status != CONNECTION_BAD)
712  (void) connectDBComplete(conn);
713 
714  return conn;
715 }
PGconn * PQconnectStart(const char *conninfo)
Definition: fe-connect.c:835
static int connectDBComplete(PGconn *conn)
Definition: fe-connect.c:2074

References conn, connectDBComplete(), CONNECTION_BAD, PQconnectStart(), and pg_conn::status.

Referenced by dblink_connect(), dblink_get_conn(), get_db_conn(), and main().

◆ PQconnectdbParams()

PGconn* PQconnectdbParams ( const char *const *  keywords,
const char *const *  values,
int  expand_dbname 
)

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

655 {
656  PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
657 
658  if (conn && conn->status != CONNECTION_BAD)
659  (void) connectDBComplete(conn);
660 
661  return conn;
662 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156
PGconn * PQconnectStartParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:754

References conn, connectDBComplete(), CONNECTION_BAD, PQconnectStartParams(), pg_conn::status, and values.

Referenced by connect_pg_server(), ConnectDatabase(), connectDatabase(), do_connect(), doConnect(), ECPGconnect(), GetConnection(), main(), sql_conn(), and vacuumlo().

◆ PQconnectionNeedsPassword()

int PQconnectionNeedsPassword ( const PGconn conn)

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

6795 {
6796  char *password;
6797 
6798  if (!conn)
6799  return false;
6800  password = PQpass(conn);
6801  if (conn->password_needed &&
6802  (password == NULL || password[0] == '\0'))
6803  return true;
6804  else
6805  return false;
6806 }
char * PQpass(const PGconn *conn)
Definition: fe-connect.c:6605
static char * password
Definition: streamutil.c:53
bool password_needed
Definition: libpq-int.h:454

References conn, password, pg_conn::password_needed, and PQpass().

Referenced by ConnectDatabase(), connectDatabase(), do_connect(), doConnect(), GetConnection(), main(), sql_conn(), and vacuumlo().

◆ PQconnectionUsedPassword()

int PQconnectionUsedPassword ( const PGconn conn)

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

6810 {
6811  if (!conn)
6812  return false;
6813  if (conn->password_needed)
6814  return true;
6815  else
6816  return false;
6817 }

References conn, and pg_conn::password_needed.

Referenced by connect_pg_server(), ConnectDatabase(), and dblink_security_check().

◆ PQconnectPoll()

PostgresPollingStatusType PQconnectPoll ( PGconn conn)

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

2211 {
2212  bool reset_connection_state_machine = false;
2213  bool need_new_connection = false;
2214  PGresult *res;
2215  char sebuf[PG_STRERROR_R_BUFLEN];
2216  int optval;
2217 
2218  if (conn == NULL)
2219  return PGRES_POLLING_FAILED;
2220 
2221  /* Get the new data */
2222  switch (conn->status)
2223  {
2224  /*
2225  * We really shouldn't have been polled in these two cases, but we
2226  * can handle it.
2227  */
2228  case CONNECTION_BAD:
2229  return PGRES_POLLING_FAILED;
2230  case CONNECTION_OK:
2231  return PGRES_POLLING_OK;
2232 
2233  /* These are reading states */
2235  case CONNECTION_AUTH_OK:
2237  case CONNECTION_CONSUME:
2239  {
2240  /* Load waiting data */
2241  int n = pqReadData(conn);
2242 
2243  if (n < 0)
2244  goto error_return;
2245  if (n == 0)
2246  return PGRES_POLLING_READING;
2247 
2248  break;
2249  }
2250 
2251  /* These are writing states, so we just proceed. */
2252  case CONNECTION_STARTED:
2253  case CONNECTION_MADE:
2254  break;
2255 
2256  /* Special cases: proceed without waiting. */
2258  case CONNECTION_NEEDED:
2261  break;
2262 
2263  default:
2264  libpq_append_conn_error(conn, "invalid connection state, probably indicative of memory corruption");
2265  goto error_return;
2266  }
2267 
2268 
2269 keep_going: /* We will come back to here until there is
2270  * nothing left to do. */
2271 
2272  /* Time to advance to next address, or next host if no more addresses? */
2273  if (conn->try_next_addr)
2274  {
2275  if (conn->addr_cur && conn->addr_cur->ai_next)
2276  {
2277  conn->addr_cur = conn->addr_cur->ai_next;
2278  reset_connection_state_machine = true;
2279  }
2280  else
2281  conn->try_next_host = true;
2282  conn->try_next_addr = false;
2283  }
2284 
2285  /* Time to advance to next connhost[] entry? */
2286  if (conn->try_next_host)
2287  {
2288  pg_conn_host *ch;
2289  struct addrinfo hint;
2290  int thisport;
2291  int ret;
2292  char portstr[MAXPGPATH];
2293 
2294  if (conn->whichhost + 1 < conn->nconnhost)
2295  conn->whichhost++;
2296  else
2297  {
2298  /*
2299  * Oops, no more hosts.
2300  *
2301  * If we are trying to connect in "prefer-standby" mode, then drop
2302  * the standby requirement and start over.
2303  *
2304  * Otherwise, an appropriate error message is already set up, so
2305  * we just need to set the right status.
2306  */
2308  conn->nconnhost > 0)
2309  {
2311  conn->whichhost = 0;
2312  }
2313  else
2314  goto error_return;
2315  }
2316 
2317  /* Drop any address info for previous host */
2319 
2320  /*
2321  * Look up info for the new host. On failure, log the problem in
2322  * conn->errorMessage, then loop around to try the next host. (Note
2323  * we don't clear try_next_host until we've succeeded.)
2324  */
2325  ch = &conn->connhost[conn->whichhost];
2326 
2327  /* Initialize hint structure */
2328  MemSet(&hint, 0, sizeof(hint));
2329  hint.ai_socktype = SOCK_STREAM;
2330  conn->addrlist_family = hint.ai_family = AF_UNSPEC;
2331 
2332  /* Figure out the port number we're going to use. */
2333  if (ch->port == NULL || ch->port[0] == '\0')
2334  thisport = DEF_PGPORT;
2335  else
2336  {
2337  if (!parse_int_param(ch->port, &thisport, conn, "port"))
2338  goto error_return;
2339 
2340  if (thisport < 1 || thisport > 65535)
2341  {
2342  libpq_append_conn_error(conn, "invalid port number: \"%s\"", ch->port);
2343  goto keep_going;
2344  }
2345  }
2346  snprintf(portstr, sizeof(portstr), "%d", thisport);
2347 
2348  /* Use pg_getaddrinfo_all() to resolve the address */
2349  switch (ch->type)
2350  {
2351  case CHT_HOST_NAME:
2352  ret = pg_getaddrinfo_all(ch->host, portstr, &hint,
2353  &conn->addrlist);
2354  if (ret || !conn->addrlist)
2355  {
2356  libpq_append_conn_error(conn, "could not translate host name \"%s\" to address: %s",
2357  ch->host, gai_strerror(ret));
2358  goto keep_going;
2359  }
2360  break;
2361 
2362  case CHT_HOST_ADDRESS:
2363  hint.ai_flags = AI_NUMERICHOST;
2364  ret = pg_getaddrinfo_all(ch->hostaddr, portstr, &hint,
2365  &conn->addrlist);
2366  if (ret || !conn->addrlist)
2367  {
2368  libpq_append_conn_error(conn, "could not parse network address \"%s\": %s",
2369  ch->hostaddr, gai_strerror(ret));
2370  goto keep_going;
2371  }
2372  break;
2373 
2374  case CHT_UNIX_SOCKET:
2375  conn->addrlist_family = hint.ai_family = AF_UNIX;
2376  UNIXSOCK_PATH(portstr, thisport, ch->host);
2377  if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)
2378  {
2379  libpq_append_conn_error(conn, "Unix-domain socket path \"%s\" is too long (maximum %d bytes)",
2380  portstr,
2381  (int) (UNIXSOCK_PATH_BUFLEN - 1));
2382  goto keep_going;
2383  }
2384 
2385  /*
2386  * NULL hostname tells pg_getaddrinfo_all to parse the service
2387  * name as a Unix-domain socket path.
2388  */
2389  ret = pg_getaddrinfo_all(NULL, portstr, &hint,
2390  &conn->addrlist);
2391  if (ret || !conn->addrlist)
2392  {
2393  libpq_append_conn_error(conn, "could not translate Unix-domain socket path \"%s\" to address: %s",
2394  portstr, gai_strerror(ret));
2395  goto keep_going;
2396  }
2397  break;
2398  }
2399 
2400  /* OK, scan this addrlist for a working server address */
2401  conn->addr_cur = conn->addrlist;
2402  reset_connection_state_machine = true;
2403  conn->try_next_host = false;
2404  }
2405 
2406  /* Reset connection state machine? */
2407  if (reset_connection_state_machine)
2408  {
2409  /*
2410  * (Re) initialize our connection control variables for a set of
2411  * connection attempts to a single server address. These variables
2412  * must persist across individual connection attempts, but we must
2413  * reset them when we start to consider a new server.
2414  */
2415  conn->pversion = PG_PROTOCOL(3, 0);
2416  conn->send_appname = true;
2417 #ifdef USE_SSL
2418  /* initialize these values based on SSL mode */
2419  conn->allow_ssl_try = (conn->sslmode[0] != 'd'); /* "disable" */
2420  conn->wait_ssl_try = (conn->sslmode[0] == 'a'); /* "allow" */
2421 #endif
2422 #ifdef ENABLE_GSS
2423  conn->try_gss = (conn->gssencmode[0] != 'd'); /* "disable" */
2424 #endif
2425 
2426  reset_connection_state_machine = false;
2427  need_new_connection = true;
2428  }
2429 
2430  /* Force a new connection (perhaps to the same server as before)? */
2431  if (need_new_connection)
2432  {
2433  /* Drop any existing connection */
2434  pqDropConnection(conn, true);
2435 
2436  /* Reset all state obtained from old server */
2438 
2439  /* Drop any PGresult we might have, too */
2444 
2445  /* Reset conn->status to put the state machine in the right state */
2447 
2448  need_new_connection = false;
2449  }
2450 
2451  /* Now try to advance the state machine for this connection */
2452  switch (conn->status)
2453  {
2454  case CONNECTION_NEEDED:
2455  {
2456  /*
2457  * Try to initiate a connection to one of the addresses
2458  * returned by pg_getaddrinfo_all(). conn->addr_cur is the
2459  * next one to try.
2460  *
2461  * The extra level of braces here is historical. It's not
2462  * worth reindenting this whole switch case to remove 'em.
2463  */
2464  {
2465  struct addrinfo *addr_cur = conn->addr_cur;
2466  char host_addr[NI_MAXHOST];
2467 
2468  /*
2469  * Advance to next possible host, if we've tried all of
2470  * the addresses for the current host.
2471  */
2472  if (addr_cur == NULL)
2473  {
2474  conn->try_next_host = true;
2475  goto keep_going;
2476  }
2477 
2478  /* Remember current address for possible use later */
2479  memcpy(&conn->raddr.addr, addr_cur->ai_addr,
2480  addr_cur->ai_addrlen);
2481  conn->raddr.salen = addr_cur->ai_addrlen;
2482 
2483  /*
2484  * Set connip, too. Note we purposely ignore strdup
2485  * failure; not a big problem if it fails.
2486  */
2487  if (conn->connip != NULL)
2488  {
2489  free(conn->connip);
2490  conn->connip = NULL;
2491  }
2492  getHostaddr(conn, host_addr, NI_MAXHOST);
2493  if (host_addr[0])
2494  conn->connip = strdup(host_addr);
2495 
2496  /* Try to create the socket */
2497  conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
2498  if (conn->sock == PGINVALID_SOCKET)
2499  {
2500  int errorno = SOCK_ERRNO;
2501 
2502  /*
2503  * Silently ignore socket() failure if we have more
2504  * addresses to try; this reduces useless chatter in
2505  * cases where the address list includes both IPv4 and
2506  * IPv6 but kernel only accepts one family.
2507  */
2508  if (addr_cur->ai_next != NULL ||
2509  conn->whichhost + 1 < conn->nconnhost)
2510  {
2511  conn->try_next_addr = true;
2512  goto keep_going;
2513  }
2514  emitHostIdentityInfo(conn, host_addr);
2515  libpq_append_conn_error(conn, "could not create socket: %s",
2516  SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)));
2517  goto error_return;
2518  }
2519 
2520  /*
2521  * Once we've identified a target address, all errors
2522  * except the preceding socket()-failure case should be
2523  * prefixed with host-identity information. (If the
2524  * connection succeeds, the contents of conn->errorMessage
2525  * won't matter, so this is harmless.)
2526  */
2527  emitHostIdentityInfo(conn, host_addr);
2528 
2529  /*
2530  * Select socket options: no delay of outgoing data for
2531  * TCP sockets, nonblock mode, close-on-exec. Try the
2532  * next address if any of this fails.
2533  */
2534  if (addr_cur->ai_family != AF_UNIX)
2535  {
2536  if (!connectNoDelay(conn))
2537  {
2538  /* error message already created */
2539  conn->try_next_addr = true;
2540  goto keep_going;
2541  }
2542  }
2543  if (!pg_set_noblock(conn->sock))
2544  {
2545  libpq_append_conn_error(conn, "could not set socket to nonblocking mode: %s",
2546  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2547  conn->try_next_addr = true;
2548  goto keep_going;
2549  }
2550 
2551 #ifdef F_SETFD
2552  if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
2553  {
2554  libpq_append_conn_error(conn, "could not set socket to close-on-exec mode: %s",
2555  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2556  conn->try_next_addr = true;
2557  goto keep_going;
2558  }
2559 #endif /* F_SETFD */
2560 
2561  if (addr_cur->ai_family != AF_UNIX)
2562  {
2563 #ifndef WIN32
2564  int on = 1;
2565 #endif
2566  int usekeepalives = useKeepalives(conn);
2567  int err = 0;
2568 
2569  if (usekeepalives < 0)
2570  {
2571  libpq_append_conn_error(conn, "keepalives parameter must be an integer");
2572  err = 1;
2573  }
2574  else if (usekeepalives == 0)
2575  {
2576  /* Do nothing */
2577  }
2578 #ifndef WIN32
2579  else if (setsockopt(conn->sock,
2580  SOL_SOCKET, SO_KEEPALIVE,
2581  (char *) &on, sizeof(on)) < 0)
2582  {
2583  libpq_append_conn_error(conn, "%s(%s) failed: %s",
2584  "setsockopt",
2585  "SO_KEEPALIVE",
2586  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2587  err = 1;
2588  }
2589  else if (!setKeepalivesIdle(conn)
2591  || !setKeepalivesCount(conn))
2592  err = 1;
2593 #else /* WIN32 */
2594 #ifdef SIO_KEEPALIVE_VALS
2595  else if (!prepKeepalivesWin32(conn))
2596  err = 1;
2597 #endif /* SIO_KEEPALIVE_VALS */
2598 #endif /* WIN32 */
2599  else if (!setTCPUserTimeout(conn))
2600  err = 1;
2601 
2602  if (err)
2603  {
2604  conn->try_next_addr = true;
2605  goto keep_going;
2606  }
2607  }
2608 
2609  /*----------
2610  * We have three methods of blocking SIGPIPE during
2611  * send() calls to this socket:
2612  *
2613  * - setsockopt(sock, SO_NOSIGPIPE)
2614  * - send(sock, ..., MSG_NOSIGNAL)
2615  * - setting the signal mask to SIG_IGN during send()
2616  *
2617  * The third method requires three syscalls per send,
2618  * so we prefer either of the first two, but they are
2619  * less portable. The state is tracked in the following
2620  * members of PGconn:
2621  *
2622  * conn->sigpipe_so - we have set up SO_NOSIGPIPE
2623  * conn->sigpipe_flag - we're specifying MSG_NOSIGNAL
2624  *
2625  * If we can use SO_NOSIGPIPE, then set sigpipe_so here
2626  * and we're done. Otherwise, set sigpipe_flag so that
2627  * we will try MSG_NOSIGNAL on sends. If we get an error
2628  * with MSG_NOSIGNAL, we'll clear that flag and revert to
2629  * signal masking.
2630  *----------
2631  */
2632  conn->sigpipe_so = false;
2633 #ifdef MSG_NOSIGNAL
2634  conn->sigpipe_flag = true;
2635 #else
2636  conn->sigpipe_flag = false;
2637 #endif /* MSG_NOSIGNAL */
2638 
2639 #ifdef SO_NOSIGPIPE
2640  optval = 1;
2641  if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
2642  (char *) &optval, sizeof(optval)) == 0)
2643  {
2644  conn->sigpipe_so = true;
2645  conn->sigpipe_flag = false;
2646  }
2647 #endif /* SO_NOSIGPIPE */
2648 
2649  /*
2650  * Start/make connection. This should not block, since we
2651  * are in nonblock mode. If it does, well, too bad.
2652  */
2653  if (connect(conn->sock, addr_cur->ai_addr,
2654  addr_cur->ai_addrlen) < 0)
2655  {
2656  if (SOCK_ERRNO == EINPROGRESS ||
2657 #ifdef WIN32
2658  SOCK_ERRNO == EWOULDBLOCK ||
2659 #endif
2660  SOCK_ERRNO == EINTR)
2661  {
2662  /*
2663  * This is fine - we're in non-blocking mode, and
2664  * the connection is in progress. Tell caller to
2665  * wait for write-ready on socket.
2666  */
2668  return PGRES_POLLING_WRITING;
2669  }
2670  /* otherwise, trouble */
2671  }
2672  else
2673  {
2674  /*
2675  * Hm, we're connected already --- seems the "nonblock
2676  * connection" wasn't. Advance the state machine and
2677  * go do the next stuff.
2678  */
2680  goto keep_going;
2681  }
2682 
2683  /*
2684  * This connection failed. Add the error report to
2685  * conn->errorMessage, then try the next address if any.
2686  */
2688  conn->try_next_addr = true;
2689  goto keep_going;
2690  }
2691  }
2692 
2693  case CONNECTION_STARTED:
2694  {
2695  socklen_t optlen = sizeof(optval);
2696 
2697  /*
2698  * Write ready, since we've made it here, so the connection
2699  * has been made ... or has failed.
2700  */
2701 
2702  /*
2703  * Now check (using getsockopt) that there is not an error
2704  * state waiting for us on the socket.
2705  */
2706 
2707  if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
2708  (char *) &optval, &optlen) == -1)
2709  {
2710  libpq_append_conn_error(conn, "could not get socket error status: %s",
2711  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2712  goto error_return;
2713  }
2714  else if (optval != 0)
2715  {
2716  /*
2717  * When using a nonblocking connect, we will typically see
2718  * connect failures at this point, so provide a friendly
2719  * error message.
2720  */
2721  connectFailureMessage(conn, optval);
2722 
2723  /*
2724  * Try the next address if any, just as in the case where
2725  * connect() returned failure immediately.
2726  */
2727  conn->try_next_addr = true;
2728  goto keep_going;
2729  }
2730 
2731  /* Fill in the client address */
2732  conn->laddr.salen = sizeof(conn->laddr.addr);
2733  if (getsockname(conn->sock,
2734  (struct sockaddr *) &conn->laddr.addr,
2735  &conn->laddr.salen) < 0)
2736  {
2737  libpq_append_conn_error(conn, "could not get client address from socket: %s",
2738  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2739  goto error_return;
2740  }
2741 
2742  /*
2743  * Make sure we can write before advancing to next step.
2744  */
2746  return PGRES_POLLING_WRITING;
2747  }
2748 
2749  case CONNECTION_MADE:
2750  {
2751  char *startpacket;
2752  int packetlen;
2753 
2754  /*
2755  * Implement requirepeer check, if requested and it's a
2756  * Unix-domain socket.
2757  */
2758  if (conn->requirepeer && conn->requirepeer[0] &&
2759  conn->raddr.addr.ss_family == AF_UNIX)
2760  {
2761 #ifndef WIN32
2762  char *remote_username;
2763 #endif
2764  uid_t uid;
2765  gid_t gid;
2766 
2767  errno = 0;
2768  if (getpeereid(conn->sock, &uid, &gid) != 0)
2769  {
2770  /*
2771  * Provide special error message if getpeereid is a
2772  * stub
2773  */
2774  if (errno == ENOSYS)
2775  libpq_append_conn_error(conn, "requirepeer parameter is not supported on this platform");
2776  else
2777  libpq_append_conn_error(conn, "could not get peer credentials: %s",
2778  strerror_r(errno, sebuf, sizeof(sebuf)));
2779  goto error_return;
2780  }
2781 
2782 #ifndef WIN32
2783  remote_username = pg_fe_getusername(uid,
2784  &conn->errorMessage);
2785  if (remote_username == NULL)
2786  goto error_return; /* message already logged */
2787 
2788  if (strcmp(remote_username, conn->requirepeer) != 0)
2789  {
2790  libpq_append_conn_error(conn, "requirepeer specifies \"%s\", but actual peer user name is \"%s\"",
2791  conn->requirepeer, remote_username);
2792  free(remote_username);
2793  goto error_return;
2794  }
2795  free(remote_username);
2796 #else /* WIN32 */
2797  /* should have failed with ENOSYS above */
2798  Assert(false);
2799 #endif /* WIN32 */
2800  }
2801 
2802  if (conn->raddr.addr.ss_family == AF_UNIX)
2803  {
2804  /* Don't request SSL or GSSAPI over Unix sockets */
2805 #ifdef USE_SSL
2806  conn->allow_ssl_try = false;
2807 #endif
2808 #ifdef ENABLE_GSS
2809  conn->try_gss = false;
2810 #endif
2811  }
2812 
2813 #ifdef ENABLE_GSS
2814 
2815  /*
2816  * If GSSAPI encryption is enabled, then call
2817  * pg_GSS_have_cred_cache() which will return true if we can
2818  * acquire credentials (and give us a handle to use in
2819  * conn->gcred), and then send a packet to the server asking
2820  * for GSSAPI Encryption (and skip past SSL negotiation and
2821  * regular startup below).
2822  */
2823  if (conn->try_gss && !conn->gctx)
2824  conn->try_gss = pg_GSS_have_cred_cache(&conn->gcred);
2825  if (conn->try_gss && !conn->gctx)
2826  {
2828 
2829  if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
2830  {
2831  libpq_append_conn_error(conn, "could not send GSSAPI negotiation packet: %s",
2832  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2833  goto error_return;
2834  }
2835 
2836  /* Ok, wait for response */
2838  return PGRES_POLLING_READING;
2839  }
2840  else if (!conn->gctx && conn->gssencmode[0] == 'r')
2841  {
2843  "GSSAPI encryption required but was impossible (possibly no credential cache, no server support, or using a local socket)");
2844  goto error_return;
2845  }
2846 #endif
2847 
2848 #ifdef USE_SSL
2849 
2850  /*
2851  * Enable the libcrypto callbacks before checking if SSL needs
2852  * to be done. This is done before sending the startup packet
2853  * as depending on the type of authentication done, like MD5
2854  * or SCRAM that use cryptohashes, the callbacks would be
2855  * required even without a SSL connection
2856  */
2857  if (pqsecure_initialize(conn, false, true) < 0)
2858  goto error_return;
2859 
2860  /*
2861  * If SSL is enabled and we haven't already got encryption of
2862  * some sort running, request SSL instead of sending the
2863  * startup message.
2864  */
2865  if (conn->allow_ssl_try && !conn->wait_ssl_try &&
2866  !conn->ssl_in_use
2867 #ifdef ENABLE_GSS
2868  && !conn->gssenc
2869 #endif
2870  )
2871  {
2872  ProtocolVersion pv;
2873 
2874  /*
2875  * Send the SSL request packet.
2876  *
2877  * Theoretically, this could block, but it really
2878  * shouldn't since we only got here if the socket is
2879  * write-ready.
2880  */
2882  if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
2883  {
2884  libpq_append_conn_error(conn, "could not send SSL negotiation packet: %s",
2885  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2886  goto error_return;
2887  }
2888  /* Ok, wait for response */
2890  return PGRES_POLLING_READING;
2891  }
2892 #endif /* USE_SSL */
2893 
2894  /*
2895  * Build the startup packet.
2896  */
2897  startpacket = pqBuildStartupPacket3(conn, &packetlen,
2899  if (!startpacket)
2900  {
2901  libpq_append_conn_error(conn, "out of memory");
2902  goto error_return;
2903  }
2904 
2905  /*
2906  * Send the startup packet.
2907  *
2908  * Theoretically, this could block, but it really shouldn't
2909  * since we only got here if the socket is write-ready.
2910  */
2911  if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
2912  {
2913  libpq_append_conn_error(conn, "could not send startup packet: %s",
2914  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2915  free(startpacket);
2916  goto error_return;
2917  }
2918 
2919  free(startpacket);
2920 
2922  return PGRES_POLLING_READING;
2923  }
2924 
2925  /*
2926  * Handle SSL negotiation: wait for postmaster messages and
2927  * respond as necessary.
2928  */
2930  {
2931 #ifdef USE_SSL
2932  PostgresPollingStatusType pollres;
2933 
2934  /*
2935  * On first time through, get the postmaster's response to our
2936  * SSL negotiation packet.
2937  */
2938  if (!conn->ssl_in_use)
2939  {
2940  /*
2941  * We use pqReadData here since it has the logic to
2942  * distinguish no-data-yet from connection closure. Since
2943  * conn->ssl isn't set, a plain recv() will occur.
2944  */
2945  char SSLok;
2946  int rdresult;
2947 
2948  rdresult = pqReadData(conn);
2949  if (rdresult < 0)
2950  {
2951  /* errorMessage is already filled in */
2952  goto error_return;
2953  }
2954  if (rdresult == 0)
2955  {
2956  /* caller failed to wait for data */
2957  return PGRES_POLLING_READING;
2958  }
2959  if (pqGetc(&SSLok, conn) < 0)
2960  {
2961  /* should not happen really */
2962  return PGRES_POLLING_READING;
2963  }
2964  if (SSLok == 'S')
2965  {
2966  /* mark byte consumed */
2967  conn->inStart = conn->inCursor;
2968 
2969  /*
2970  * Set up global SSL state if required. The crypto
2971  * state has already been set if libpq took care of
2972  * doing that, so there is no need to make that happen
2973  * again.
2974  */
2975  if (pqsecure_initialize(conn, true, false) != 0)
2976  goto error_return;
2977  }
2978  else if (SSLok == 'N')
2979  {
2980  /* mark byte consumed */
2981  conn->inStart = conn->inCursor;
2982  /* OK to do without SSL? */
2983  if (conn->sslmode[0] == 'r' || /* "require" */
2984  conn->sslmode[0] == 'v') /* "verify-ca" or
2985  * "verify-full" */
2986  {
2987  /* Require SSL, but server does not want it */
2988  libpq_append_conn_error(conn, "server does not support SSL, but SSL was required");
2989  goto error_return;
2990  }
2991  /* Otherwise, proceed with normal startup */
2992  conn->allow_ssl_try = false;
2993  /* We can proceed using this connection */
2995  return PGRES_POLLING_WRITING;
2996  }
2997  else if (SSLok == 'E')
2998  {
2999  /*
3000  * Server failure of some sort, such as failure to
3001  * fork a backend process. We need to process and
3002  * report the error message, which might be formatted
3003  * according to either protocol 2 or protocol 3.
3004  * Rather than duplicate the code for that, we flip
3005  * into AWAITING_RESPONSE state and let the code there
3006  * deal with it. Note we have *not* consumed the "E"
3007  * byte here.
3008  */
3010  goto keep_going;
3011  }
3012  else
3013  {
3014  libpq_append_conn_error(conn, "received invalid response to SSL negotiation: %c",
3015  SSLok);
3016  goto error_return;
3017  }
3018  }
3019 
3020  /*
3021  * Begin or continue the SSL negotiation process.
3022  */
3023  pollres = pqsecure_open_client(conn);
3024  if (pollres == PGRES_POLLING_OK)
3025  {
3026  /*
3027  * At this point we should have no data already buffered.
3028  * If we do, it was received before we performed the SSL
3029  * handshake, so it wasn't encrypted and indeed may have
3030  * been injected by a man-in-the-middle.
3031  */
3032  if (conn->inCursor != conn->inEnd)
3033  {
3034  libpq_append_conn_error(conn, "received unencrypted data after SSL response");
3035  goto error_return;
3036  }
3037 
3038  /* SSL handshake done, ready to send startup packet */
3040  return PGRES_POLLING_WRITING;
3041  }
3042  if (pollres == PGRES_POLLING_FAILED)
3043  {
3044  /*
3045  * Failed ... if sslmode is "prefer" then do a non-SSL
3046  * retry
3047  */
3048  if (conn->sslmode[0] == 'p' /* "prefer" */
3049  && conn->allow_ssl_try /* redundant? */
3050  && !conn->wait_ssl_try) /* redundant? */
3051  {
3052  /* only retry once */
3053  conn->allow_ssl_try = false;
3054  need_new_connection = true;
3055  goto keep_going;
3056  }
3057  /* Else it's a hard failure */
3058  goto error_return;
3059  }
3060  /* Else, return POLLING_READING or POLLING_WRITING status */
3061  return pollres;
3062 #else /* !USE_SSL */
3063  /* can't get here */
3064  goto error_return;
3065 #endif /* USE_SSL */
3066  }
3067 
3069  {
3070 #ifdef ENABLE_GSS
3071  PostgresPollingStatusType pollres;
3072 
3073  /*
3074  * If we haven't yet, get the postmaster's response to our
3075  * negotiation packet
3076  */
3077  if (conn->try_gss && !conn->gctx)
3078  {
3079  char gss_ok;
3080  int rdresult = pqReadData(conn);
3081 
3082  if (rdresult < 0)
3083  /* pqReadData fills in error message */
3084  goto error_return;
3085  else if (rdresult == 0)
3086  /* caller failed to wait for data */
3087  return PGRES_POLLING_READING;
3088  if (pqGetc(&gss_ok, conn) < 0)
3089  /* shouldn't happen... */
3090  return PGRES_POLLING_READING;
3091 
3092  if (gss_ok == 'E')
3093  {
3094  /*
3095  * Server failure of some sort. Assume it's a
3096  * protocol version support failure, and let's see if
3097  * we can't recover (if it's not, we'll get a better
3098  * error message on retry). Server gets fussy if we
3099  * don't hang up the socket, though.
3100  */
3101  conn->try_gss = false;
3102  need_new_connection = true;
3103  goto keep_going;
3104  }
3105 
3106  /* mark byte consumed */
3107  conn->inStart = conn->inCursor;
3108 
3109  if (gss_ok == 'N')
3110  {
3111  /* Server doesn't want GSSAPI; fall back if we can */
3112  if (conn->gssencmode[0] == 'r')
3113  {
3114  libpq_append_conn_error(conn, "server doesn't support GSSAPI encryption, but it was required");
3115  goto error_return;
3116  }
3117 
3118  conn->try_gss = false;
3119  /* We can proceed using this connection */
3121  return PGRES_POLLING_WRITING;
3122  }
3123  else if (gss_ok != 'G')
3124  {
3125  libpq_append_conn_error(conn, "received invalid response to GSSAPI negotiation: %c",
3126  gss_ok);
3127  goto error_return;
3128  }
3129  }
3130 
3131  /* Begin or continue GSSAPI negotiation */
3132  pollres = pqsecure_open_gss(conn);
3133  if (pollres == PGRES_POLLING_OK)
3134  {
3135  /*
3136  * At this point we should have no data already buffered.
3137  * If we do, it was received before we performed the GSS
3138  * handshake, so it wasn't encrypted and indeed may have
3139  * been injected by a man-in-the-middle.
3140  */
3141  if (conn->inCursor != conn->inEnd)
3142  {
3143  libpq_append_conn_error(conn, "received unencrypted data after GSSAPI encryption response");
3144  goto error_return;
3145  }
3146 
3147  /* All set for startup packet */
3149  return PGRES_POLLING_WRITING;
3150  }
3151  else if (pollres == PGRES_POLLING_FAILED &&
3152  conn->gssencmode[0] == 'p')
3153  {
3154  /*
3155  * We failed, but we can retry on "prefer". Have to drop
3156  * the current connection to do so, though.
3157  */
3158  conn->try_gss = false;
3159  need_new_connection = true;
3160  goto keep_going;
3161  }
3162  return pollres;
3163 #else /* !ENABLE_GSS */
3164  /* unreachable */
3165  goto error_return;
3166 #endif /* ENABLE_GSS */
3167  }
3168 
3169  /*
3170  * Handle authentication exchange: wait for postmaster messages
3171  * and respond as necessary.
3172  */
3174  {
3175  char beresp;
3176  int msgLength;
3177  int avail;
3178  AuthRequest areq;
3179  int res;
3180 
3181  /*
3182  * Scan the message from current point (note that if we find
3183  * the message is incomplete, we will return without advancing
3184  * inStart, and resume here next time).
3185  */
3186  conn->inCursor = conn->inStart;
3187 
3188  /* Read type byte */
3189  if (pqGetc(&beresp, conn))
3190  {
3191  /* We'll come back when there is more data */
3192  return PGRES_POLLING_READING;
3193  }
3194 
3195  /*
3196  * Validate message type: we expect only an authentication
3197  * request, NegotiateProtocolVersion, or an error here.
3198  * Anything else probably means it's not Postgres on the other
3199  * end at all.
3200  */
3201  if (!(beresp == 'R' || beresp == 'v' || beresp == 'E'))
3202  {
3203  libpq_append_conn_error(conn, "expected authentication request from server, but received %c",
3204  beresp);
3205  goto error_return;
3206  }
3207 
3208  /* Read message length word */
3209  if (pqGetInt(&msgLength, 4, conn))
3210  {
3211  /* We'll come back when there is more data */
3212  return PGRES_POLLING_READING;
3213  }
3214 
3215  /*
3216  * Try to validate message length before using it.
3217  * Authentication requests can't be very large, although GSS
3218  * auth requests may not be that small. Same for
3219  * NegotiateProtocolVersion. Errors can be a
3220  * little larger, but not huge. If we see a large apparent
3221  * length in an error, it means we're really talking to a
3222  * pre-3.0-protocol server; cope. (Before version 14, the
3223  * server also used the old protocol for errors that happened
3224  * before processing the startup packet.)
3225  */
3226  if ((beresp == 'R' || beresp == 'v') && (msgLength < 8 || msgLength > 2000))
3227  {
3228  libpq_append_conn_error(conn, "expected authentication request from server, but received %c",
3229  beresp);
3230  goto error_return;
3231  }
3232 
3233  if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
3234  {
3235  /* Handle error from a pre-3.0 server */
3236  conn->inCursor = conn->inStart + 1; /* reread data */
3238  {
3239  /* We'll come back when there is more data */
3240  return PGRES_POLLING_READING;
3241  }
3242  /* OK, we read the message; mark data consumed */
3243  conn->inStart = conn->inCursor;
3244 
3245  /*
3246  * Before 7.2, the postmaster didn't always end its
3247  * messages with a newline, so add one if needed to
3248  * conform to libpq conventions.
3249  */
3250  if (conn->errorMessage.len == 0 ||
3251  conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
3252  {
3254  }
3255 
3256  goto error_return;
3257  }
3258 
3259  /*
3260  * Can't process if message body isn't all here yet.
3261  */
3262  msgLength -= 4;
3263  avail = conn->inEnd - conn->inCursor;
3264  if (avail < msgLength)
3265  {
3266  /*
3267  * Before returning, try to enlarge the input buffer if
3268  * needed to hold the whole message; see notes in
3269  * pqParseInput3.
3270  */
3271  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
3272  conn))
3273  goto error_return;
3274  /* We'll come back when there is more data */
3275  return PGRES_POLLING_READING;
3276  }
3277 
3278  /* Handle errors. */
3279  if (beresp == 'E')
3280  {
3281  if (pqGetErrorNotice3(conn, true))
3282  {
3283  /* We'll come back when there is more data */
3284  return PGRES_POLLING_READING;
3285  }
3286  /* OK, we read the message; mark data consumed */
3287  conn->inStart = conn->inCursor;
3288 
3289  /*
3290  * If error is "cannot connect now", try the next host if
3291  * any (but we don't want to consider additional addresses
3292  * for this host, nor is there much point in changing SSL
3293  * or GSS mode). This is helpful when dealing with
3294  * standby servers that might not be in hot-standby state.
3295  */
3296  if (strcmp(conn->last_sqlstate,
3298  {
3299  conn->try_next_host = true;
3300  goto keep_going;
3301  }
3302 
3303  /* Check to see if we should mention pgpassfile */
3305 
3306 #ifdef ENABLE_GSS
3307 
3308  /*
3309  * If gssencmode is "prefer" and we're using GSSAPI, retry
3310  * without it.
3311  */
3312  if (conn->gssenc && conn->gssencmode[0] == 'p')
3313  {
3314  /* only retry once */
3315  conn->try_gss = false;
3316  need_new_connection = true;
3317  goto keep_going;
3318  }
3319 #endif
3320 
3321 #ifdef USE_SSL
3322 
3323  /*
3324  * if sslmode is "allow" and we haven't tried an SSL
3325  * connection already, then retry with an SSL connection
3326  */
3327  if (conn->sslmode[0] == 'a' /* "allow" */
3328  && !conn->ssl_in_use
3329  && conn->allow_ssl_try
3330  && conn->wait_ssl_try)
3331  {
3332  /* only retry once */
3333  conn->wait_ssl_try = false;
3334  need_new_connection = true;
3335  goto keep_going;
3336  }
3337 
3338  /*
3339  * if sslmode is "prefer" and we're in an SSL connection,
3340  * then do a non-SSL retry
3341  */
3342  if (conn->sslmode[0] == 'p' /* "prefer" */
3343  && conn->ssl_in_use
3344  && conn->allow_ssl_try /* redundant? */
3345  && !conn->wait_ssl_try) /* redundant? */
3346  {
3347  /* only retry once */
3348  conn->allow_ssl_try = false;
3349  need_new_connection = true;
3350  goto keep_going;
3351  }
3352 #endif
3353 
3354  goto error_return;
3355  }
3356  else if (beresp == 'v')
3357  {
3359  {
3360  goto error_return;
3361  }
3362  /* OK, we read the message; mark data consumed */
3363  conn->inStart = conn->inCursor;
3364  goto error_return;
3365  }
3366 
3367  /* It is an authentication request. */
3368  conn->auth_req_received = true;
3369 
3370  /* Get the type of request. */
3371  if (pqGetInt((int *) &areq, 4, conn))
3372  {
3373  goto error_return;
3374  }
3375  msgLength -= 4;
3376 
3377  /*
3378  * Process the rest of the authentication request message, and
3379  * respond to it if necessary.
3380  *
3381  * Note that conn->pghost must be non-NULL if we are going to
3382  * avoid the Kerberos code doing a hostname look-up.
3383  */
3384  res = pg_fe_sendauth(areq, msgLength, conn);
3385 
3386  /* OK, we have processed the message; mark data consumed */
3387  conn->inStart = conn->inCursor;
3388 
3389  if (res != STATUS_OK)
3390  goto error_return;
3391 
3392  /*
3393  * Just make sure that any data sent by pg_fe_sendauth is
3394  * flushed out. Although this theoretically could block, it
3395  * really shouldn't since we don't send large auth responses.
3396  */
3397  if (pqFlush(conn))
3398  goto error_return;
3399 
3400  if (areq == AUTH_REQ_OK)
3401  {
3402  /* We are done with authentication exchange */
3404 
3405  /*
3406  * Set asyncStatus so that PQgetResult will think that
3407  * what comes back next is the result of a query. See
3408  * below.
3409  */
3411  }
3412 
3413  /* Look to see if we have more data yet. */
3414  goto keep_going;
3415  }
3416 
3417  case CONNECTION_AUTH_OK:
3418  {
3419  /*
3420  * Now we expect to hear from the backend. A ReadyForQuery
3421  * message indicates that startup is successful, but we might
3422  * also get an Error message indicating failure. (Notice
3423  * messages indicating nonfatal warnings are also allowed by
3424  * the protocol, as are ParameterStatus and BackendKeyData
3425  * messages.) Easiest way to handle this is to let
3426  * PQgetResult() read the messages. We just have to fake it
3427  * out about the state of the connection, by setting
3428  * asyncStatus = PGASYNC_BUSY (done above).
3429  */
3430 
3431  if (PQisBusy(conn))
3432  return PGRES_POLLING_READING;
3433 
3434  res = PQgetResult(conn);
3435 
3436  /*
3437  * NULL return indicating we have gone to IDLE state is
3438  * expected
3439  */
3440  if (res)
3441  {
3443  libpq_append_conn_error(conn, "unexpected message from server during startup");
3444  else if (conn->send_appname &&
3445  (conn->appname || conn->fbappname))
3446  {
3447  /*
3448  * If we tried to send application_name, check to see
3449  * if the error is about that --- pre-9.0 servers will
3450  * reject it at this stage of the process. If so,
3451  * close the connection and retry without sending
3452  * application_name. We could possibly get a false
3453  * SQLSTATE match here and retry uselessly, but there
3454  * seems no great harm in that; we'll just get the
3455  * same error again if it's unrelated.
3456  */
3457  const char *sqlstate;
3458 
3460  if (sqlstate &&
3461  strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
3462  {
3463  PQclear(res);
3464  conn->send_appname = false;
3465  need_new_connection = true;
3466  goto keep_going;
3467  }
3468  }
3469 
3470  /*
3471  * if the resultStatus is FATAL, then conn->errorMessage
3472  * already has a copy of the error; needn't copy it back.
3473  * But add a newline if it's not there already, since
3474  * postmaster error messages may not have one.
3475  */
3476  if (conn->errorMessage.len <= 0 ||
3477  conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
3479  PQclear(res);
3480  goto error_return;
3481  }
3482 
3483  /* Almost there now ... */
3485  goto keep_going;
3486  }
3487 
3489  {
3490  /*
3491  * If a read-write, read-only, primary, or standby connection
3492  * is required, see if we have one.
3493  */
3496  {
3497  bool read_only_server;
3498 
3499  /*
3500  * If the server didn't report
3501  * "default_transaction_read_only" or "in_hot_standby" at
3502  * startup, we must determine its state by sending the
3503  * query "SHOW transaction_read_only". This GUC exists in
3504  * all server versions that support 3.0 protocol.
3505  */
3508  {
3509  /*
3510  * We use PQsendQueryContinue so that
3511  * conn->errorMessage does not get cleared. We need
3512  * to preserve any error messages related to previous
3513  * hosts we have tried and failed to connect to.
3514  */
3517  "SHOW transaction_read_only"))
3518  goto error_return;
3519  /* We'll return to this state when we have the answer */
3521  return PGRES_POLLING_READING;
3522  }
3523 
3524  /* OK, we can make the test */
3525  read_only_server =
3528 
3530  read_only_server : !read_only_server)
3531  {
3532  /* Wrong server state, reject and try the next host */
3534  libpq_append_conn_error(conn, "session is read-only");
3535  else
3536  libpq_append_conn_error(conn, "session is not read-only");
3537 
3538  /* Close connection politely. */
3541 
3542  /*
3543  * Try next host if any, but we don't want to consider
3544  * additional addresses for this host.
3545  */
3546  conn->try_next_host = true;
3547  goto keep_going;
3548  }
3549  }
3553  {
3554  /*
3555  * If the server didn't report "in_hot_standby" at
3556  * startup, we must determine its state by sending the
3557  * query "SELECT pg_catalog.pg_is_in_recovery()". Servers
3558  * before 9.0 don't have that function, but by the same
3559  * token they don't have any standby mode, so we may just
3560  * assume the result.
3561  */
3562  if (conn->sversion < 90000)
3564 
3566  {
3567  /*
3568  * We use PQsendQueryContinue so that
3569  * conn->errorMessage does not get cleared. We need
3570  * to preserve any error messages related to previous
3571  * hosts we have tried and failed to connect to.
3572  */
3575  "SELECT pg_catalog.pg_is_in_recovery()"))
3576  goto error_return;
3577  /* We'll return to this state when we have the answer */
3579  return PGRES_POLLING_READING;
3580  }
3581 
3582  /* OK, we can make the test */
3586  {
3587  /* Wrong server state, reject and try the next host */
3589  libpq_append_conn_error(conn, "server is in hot standby mode");
3590  else
3591  libpq_append_conn_error(conn, "server is not in hot standby mode");
3592 
3593  /* Close connection politely. */
3596 
3597  /*
3598  * Try next host if any, but we don't want to consider
3599  * additional addresses for this host.
3600  */
3601  conn->try_next_host = true;
3602  goto keep_going;
3603  }
3604  }
3605 
3606  /* We can release the address list now. */
3608 
3609  /*
3610  * Contents of conn->errorMessage are no longer interesting
3611  * (and it seems some clients expect it to be empty after a
3612  * successful connection).
3613  */
3615 
3616  /* We are open for business! */
3618  return PGRES_POLLING_OK;
3619  }
3620 
3621  case CONNECTION_CONSUME:
3622  {
3623  /*
3624  * This state just makes sure the connection is idle after
3625  * we've obtained the result of a SHOW or SELECT query. Once
3626  * we're clear, return to CONNECTION_CHECK_TARGET state to
3627  * decide what to do next. We must transiently set status =
3628  * CONNECTION_OK in order to use the result-consuming
3629  * subroutines.
3630  */
3632  if (!PQconsumeInput(conn))
3633  goto error_return;
3634 
3635  if (PQisBusy(conn))
3636  {
3638  return PGRES_POLLING_READING;
3639  }
3640 
3641  /* Call PQgetResult() again until we get a NULL result */
3642  res = PQgetResult(conn);
3643  if (res != NULL)
3644  {
3645  PQclear(res);
3647  return PGRES_POLLING_READING;
3648  }
3649 
3651  goto keep_going;
3652  }
3653 
3655  {
3656  /*
3657  * Waiting for result of "SHOW transaction_read_only". We
3658  * must transiently set status = CONNECTION_OK in order to use
3659  * the result-consuming subroutines.
3660  */
3662  if (!PQconsumeInput(conn))
3663  goto error_return;
3664 
3665  if (PQisBusy(conn))
3666  {
3668  return PGRES_POLLING_READING;
3669  }
3670 
3671  res = PQgetResult(conn);
3672  if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
3673  PQntuples(res) == 1)
3674  {
3675  char *val = PQgetvalue(res, 0, 0);
3676 
3677  /*
3678  * "transaction_read_only = on" proves that at least one
3679  * of default_transaction_read_only and in_hot_standby is
3680  * on, but we don't actually know which. We don't care
3681  * though for the purpose of identifying a read-only
3682  * session, so satisfy the CONNECTION_CHECK_TARGET code by
3683  * claiming they are both on. On the other hand, if it's
3684  * a read-write session, they are certainly both off.
3685  */
3686  if (strncmp(val, "on", 2) == 0)
3687  {
3690  }
3691  else
3692  {
3695  }
3696  PQclear(res);
3697 
3698  /* Finish reading messages before continuing */
3700  goto keep_going;
3701  }
3702 
3703  /* Something went wrong with "SHOW transaction_read_only". */
3704  PQclear(res);
3705 
3706  /* Append error report to conn->errorMessage. */
3707  libpq_append_conn_error(conn, "\"%s\" failed",
3708  "SHOW transaction_read_only");
3709 
3710  /* Close connection politely. */
3713 
3714  /* Try next host. */
3715  conn->try_next_host = true;
3716  goto keep_going;
3717  }
3718 
3720  {
3721  /*
3722  * Waiting for result of "SELECT pg_is_in_recovery()". We
3723  * must transiently set status = CONNECTION_OK in order to use
3724  * the result-consuming subroutines.
3725  */
3727  if (!PQconsumeInput(conn))
3728  goto error_return;
3729 
3730  if (PQisBusy(conn))
3731  {
3733  return PGRES_POLLING_READING;
3734  }
3735 
3736  res = PQgetResult(conn);
3737  if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
3738  PQntuples(res) == 1)
3739  {
3740  char *val = PQgetvalue(res, 0, 0);
3741 
3742  if (strncmp(val, "t", 1) == 0)
3744  else
3746  PQclear(res);
3747 
3748  /* Finish reading messages before continuing */
3750  goto keep_going;
3751  }
3752 
3753  /* Something went wrong with "SELECT pg_is_in_recovery()". */
3754  PQclear(res);
3755 
3756  /* Append error report to conn->errorMessage. */
3757  libpq_append_conn_error(conn, "\"%s\" failed",
3758  "SELECT pg_is_in_recovery()");
3759 
3760  /* Close connection politely. */
3763 
3764  /* Try next host. */
3765  conn->try_next_host = true;
3766  goto keep_going;
3767  }
3768 
3769  default:
3771  "invalid connection state %d, probably indicative of memory corruption",
3772  conn->status);
3773  goto error_return;
3774  }
3775 
3776  /* Unreachable */
3777 
3778 error_return:
3779 
3780  /*
3781  * We used to close the socket at this point, but that makes it awkward
3782  * for those above us if they wish to remove this socket from their own
3783  * records (an fd_set for example). We'll just have this socket closed
3784  * when PQfinish is called (which is compulsory even after an error, since
3785  * the connection structure must be freed).
3786  */
3788  return PGRES_POLLING_FAILED;
3789 }
#define STATUS_OK
Definition: c.h:1108
#define MemSet(start, val, len)
Definition: c.h:953
int pg_fe_sendauth(AuthRequest areq, int payloadlen, PGconn *conn)
Definition: fe-auth.c:862
char * pg_fe_getusername(uid_t user_id, PQExpBuffer errorMessage)
Definition: fe-auth.c:1072
void pqDropConnection(PGconn *conn, bool flushInput)
Definition: fe-connect.c:446
static const PQEnvironmentOption EnvironmentOptions[]
Definition: fe-connect.c:349
static void sendTerminateConn(PGconn *conn)
Definition: fe-connect.c:4064
static int setKeepalivesCount(PGconn *conn)
Definition: fe-connect.c:1868
static int useKeepalives(PGconn *conn)
Definition: fe-connect.c:1735
static void connectFailureMessage(PGconn *conn, int errorno)
Definition: fe-connect.c:1715
static void release_conn_addrinfo(PGconn *conn)
Definition: fe-connect.c:4049
#define ERRCODE_APPNAME_UNKNOWN
Definition: fe-connect.c:88
static int setKeepalivesInterval(PGconn *conn)
Definition: fe-connect.c:1833
static int setKeepalivesIdle(PGconn *conn)
Definition: fe-connect.c:1799
static void pgpassfileWarning(PGconn *conn)
Definition: fe-connect.c:7138
static bool parse_int_param(const char *value, int *result, PGconn *conn, const char *context)
Definition: fe-connect.c:1754
static void emitHostIdentityInfo(PGconn *conn, const char *host_addr)
Definition: fe-connect.c:1659
static int setTCPUserTimeout(PGconn *conn)
Definition: fe-connect.c:1965
static void pqDropServerData(PGconn *conn)
Definition: fe-connect.c:559
static int connectNoDelay(PGconn *conn)
Definition: fe-connect.c:1600
static void getHostaddr(PGconn *conn, char *host_addr, int host_addr_len)
Definition: fe-connect.c:1626
#define ERRCODE_CANNOT_CONNECT_NOW
Definition: fe-connect.c:93
int pqPacketSend(PGconn *conn, char pack_type, const void *buf, size_t buf_len)
Definition: fe-connect.c:4605
int PQsendQueryContinue(PGconn *conn, const char *query)
Definition: fe-exec.c:1424
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3310
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1953
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3705
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:776
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2000
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3295
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2031
bool pg_GSS_have_cred_cache(gss_cred_id_t *cred_out)
int pqReadData(PGconn *conn)
Definition: fe-misc.c:566
int pqFlush(PGconn *conn)
Definition: fe-misc.c:954
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 pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:352
int pqGets_append(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:143
int pqGetNegotiateProtocolVersion3(PGconn *conn)
int pqGetErrorNotice3(PGconn *conn, bool isError)
Definition: fe-protocol3.c:865
char * pqBuildStartupPacket3(PGconn *conn, int *packetlen, const PQEnvironmentOption *options)
PostgresPollingStatusType pqsecure_open_gss(PGconn *conn)
PostgresPollingStatusType pqsecure_open_client(PGconn *conn)
Definition: fe-secure.c:175
int pqsecure_initialize(PGconn *conn, bool do_ssl, bool do_crypto)
Definition: fe-secure.c:160
int pg_getaddrinfo_all(const char *hostname, const char *servname, const struct addrinfo *hintp, struct addrinfo **result)
Definition: ip.c:53
@ PGASYNC_IDLE
Definition: libpq-int.h:220
@ PGASYNC_BUSY
Definition: libpq-int.h:221
#define SOCK_STRERROR
Definition: libpq-int.h:904
@ CHT_UNIX_SOCKET
Definition: libpq-int.h:303
@ CHT_HOST_ADDRESS
Definition: libpq-int.h:302
@ CHT_HOST_NAME
Definition: libpq-int.h:301
@ PG_BOOL_YES
Definition: libpq-int.h:249
@ PG_BOOL_NO
Definition: libpq-int.h:250
@ PG_BOOL_UNKNOWN
Definition: libpq-int.h:248
@ SERVER_TYPE_STANDBY
Definition: libpq-int.h:240
@ SERVER_TYPE_PRIMARY
Definition: libpq-int.h:239
@ 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
#define MAXPGPATH
bool pg_set_noblock(pgsocket sock)
Definition: noblock.c:25
#define snprintf
Definition: port.h:238
unsigned int socklen_t
Definition: port.h:40
int getpeereid(int sock, uid_t *uid, gid_t *gid)
Definition: getpeereid.c:33
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:56
#define AUTH_REQ_OK
Definition: pqcomm.h:113
#define UNIXSOCK_PATH(path, port, sockdir)
Definition: pqcomm.h:32
#define UNIXSOCK_PATH_BUFLEN
Definition: pqcomm.h:48
#define NEGOTIATE_GSS_CODE
Definition: pqcomm.h:154
#define NEGOTIATE_SSL_CODE
Definition: pqcomm.h:153
uint32 ProtocolVersion
Definition: pqcomm.h:87
uint32 AuthRequest
Definition: pqcomm.h:127
#define PG_PROTOCOL(m, n)
Definition: pqcomm.h:77
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:378
char * host
Definition: libpq-int.h:338
char * port
Definition: libpq-int.h:340
char * hostaddr
Definition: libpq-int.h:339
pg_conn_host_type type
Definition: libpq-int.h:337
SockAddr laddr
Definition: libpq-int.h:449
bool try_next_host
Definition: libpq-int.h:463
struct addrinfo * addrlist
Definition: libpq-int.h:464
bool sigpipe_flag
Definition: libpq-int.h:456
int nconnhost
Definition: libpq-int.h:428
pgsocket sock
Definition: libpq-int.h:447
ProtocolVersion pversion
Definition: libpq-int.h:451
int addrlist_family
Definition: libpq-int.h:466
bool send_appname
Definition: libpq-int.h:467
PGTransactionStatusType xactStatus
Definition: libpq-int.h:415
int inCursor
Definition: libpq-int.h:485
PGTernaryBool in_hot_standby
Definition: libpq-int.h:476
int inEnd
Definition: libpq-int.h:486
char * fbappname
Definition: libpq-int.h:368
int inStart
Definition: libpq-int.h:484
char * connip
Definition: libpq-int.h:431
int sversion
Definition: libpq-int.h:452
bool auth_req_received
Definition: libpq-int.h:453
PGTernaryBool default_transaction_read_only
Definition: libpq-int.h:475
bool sigpipe_so
Definition: libpq-int.h:455
char * appname
Definition: libpq-int.h:367
char * sslmode
Definition: libpq-int.h:382
struct addrinfo * addr_cur
Definition: libpq-int.h:465
PQExpBufferData errorMessage
Definition: libpq-int.h:588
char * gssencmode
Definition: libpq-int.h:392
char last_sqlstate[6]
Definition: libpq-int.h:416
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:414
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:420
PGTargetServerType target_server_type
Definition: libpq-int.h:461
SockAddr raddr
Definition: libpq-int.h:450
bool try_next_addr
Definition: libpq-int.h:462
int whichhost
Definition: libpq-int.h:429
char * requirepeer
Definition: libpq-int.h:391
pg_conn_host * connhost
Definition: libpq-int.h:430
bool ssl_in_use
Definition: libpq-int.h:520
ExecStatusType resultStatus
Definition: libpq-int.h:179
#define EWOULDBLOCK
Definition: win32_port.h:375
#define EINPROGRESS
Definition: win32_port.h:381
int gid_t
Definition: win32_port.h:247
int uid_t
Definition: win32_port.h:246

References SockAddr::addr, pg_conn::addr_cur, pg_conn::addrlist, pg_conn::addrlist_family, appendPQExpBufferChar(), pg_conn::appname, Assert(), pg_conn::asyncStatus, AUTH_REQ_OK, pg_conn::auth_req_received, CHT_HOST_ADDRESS, CHT_HOST_NAME, CHT_UNIX_SOCKET, conn, connect, connectFailureMessage(), CONNECTION_AUTH_OK, CONNECTION_AWAITING_RESPONSE, CONNECTION_BAD, CONNECTION_CHECK_STANDBY, CONNECTION_CHECK_TARGET, CONNECTION_CHECK_WRITABLE, CONNECTION_CONSUME, CONNECTION_GSS_STARTUP, CONNECTION_MADE, CONNECTION_NEEDED, CONNECTION_OK, CONNECTION_SSL_STARTUP, CONNECTION_STARTED, connectNoDelay(), pg_conn::connhost, pg_conn::connip, PQExpBufferData::data, pg_conn::default_transaction_read_only, EINPROGRESS, EINTR, emitHostIdentityInfo(), EnvironmentOptions, ERRCODE_APPNAME_UNKNOWN, ERRCODE_CANNOT_CONNECT_NOW, pg_conn::errorMessage, EWOULDBLOCK, pg_conn::fbappname, free, getHostaddr(), getpeereid(), pg_conn::gssencmode, pg_conn_host::host, pg_conn_host::hostaddr, pg_conn::in_hot_standby, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, pg_conn::laddr, pg_conn::last_sqlstate, PQExpBufferData::len, libpq_append_conn_error(), MAXPGPATH, MemSet, pg_conn::nconnhost, NEGOTIATE_GSS_CODE, NEGOTIATE_SSL_CODE, parse_int_param(), PG_BOOL_NO, PG_BOOL_UNKNOWN, PG_BOOL_YES, PG_DIAG_SQLSTATE, pg_fe_getusername(), pg_fe_sendauth(), pg_getaddrinfo_all(), pg_GSS_have_cred_cache(), pg_hton32, PG_PROTOCOL, pg_set_noblock(), PG_STRERROR_R_BUFLEN, PGASYNC_BUSY, PGASYNC_IDLE, PGINVALID_SOCKET, pgpassfileWarning(), PGRES_FATAL_ERROR, PGRES_POLLING_FAILED, PGRES_POLLING_OK, PGRES_POLLING_READING, PGRES_POLLING_WRITING, PGRES_TUPLES_OK, pg_conn::pipelineStatus, pg_conn_host::port, PQ_PIPELINE_OFF, pqBuildStartupPacket3(), pqCheckInBufferSpace(), PQclear(), pqClearAsyncResult(), pqClearConnErrorState, PQconsumeInput(), pqDropConnection(), pqDropServerData(), pqFlush(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), pqGetNegotiateProtocolVersion3(), PQgetResult(), pqGets_append(), PQgetvalue(), PQisBusy(), PQntuples(), pqPacketSend(), pqReadData(), PQresultErrorField(), PQresultStatus(), pqsecure_initialize(), pqsecure_open_client(), pqsecure_open_gss(), PQsendQueryContinue(), PQTRANS_IDLE, pg_conn::pversion, pg_conn::raddr, release_conn_addrinfo(), pg_conn::requirepeer, res, pg_result::resultStatus, SockAddr::salen, pg_conn::send_appname, sendTerminateConn(), SERVER_TYPE_PREFER_STANDBY, SERVER_TYPE_PREFER_STANDBY_PASS2, SERVER_TYPE_PRIMARY, SERVER_TYPE_READ_ONLY, SERVER_TYPE_READ_WRITE, SERVER_TYPE_STANDBY, setKeepalivesCount(), setKeepalivesIdle(), setKeepalivesInterval(), setTCPUserTimeout(), pg_conn::sigpipe_flag, pg_conn::sigpipe_so, snprintf, pg_conn::sock, SOCK_ERRNO, SOCK_STRERROR, socket, pg_conn::ssl_in_use, pg_conn::sslmode, pg_conn::status, STATUS_OK, strerror_r, pg_conn::sversion, pg_conn::target_server_type, pg_conn::try_next_addr, pg_conn::try_next_host, pg_conn_host::type, UNIXSOCK_PATH, UNIXSOCK_PATH_BUFLEN, useKeepalives(), val, pg_conn::whichhost, and pg_conn::xactStatus.

Referenced by connectDBComplete(), connectDBStart(), libpqrcv_connect(), and PQresetPoll().

◆ PQconnectStart()

PGconn* PQconnectStart ( const char *  conninfo)

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

836 {
837  PGconn *conn;
838 
839  /*
840  * Allocate memory for the conn structure. Note that we also expect this
841  * to initialize conn->errorMessage to empty. All subsequent steps during
842  * connection initialization will only append to that buffer.
843  */
844  conn = makeEmptyPGconn();
845  if (conn == NULL)
846  return NULL;
847 
848  /*
849  * Parse the conninfo string
850  */
851  if (!connectOptions1(conn, conninfo))
852  return conn;
853 
854  /*
855  * Compute derived options
856  */
857  if (!connectOptions2(conn))
858  return conn;
859 
860  /*
861  * Connect to the database
862  */
863  if (!connectDBStart(conn))
864  {
865  /* Just in case we failed to set it in connectDBStart */
867  }
868 
869  return conn;
870 }
static bool connectOptions1(PGconn *conn, const char *conninfo)
Definition: fe-connect.c:921
static bool connectOptions2(PGconn *conn)
Definition: fe-connect.c:1019
static PGconn * makeEmptyPGconn(void)
Definition: fe-connect.c:3863
static int connectDBStart(PGconn *conn)
Definition: fe-connect.c:2004

References conn, connectDBStart(), CONNECTION_BAD, connectOptions1(), connectOptions2(), makeEmptyPGconn(), and pg_conn::status.

Referenced by PQconnectdb(), and PQping().

◆ PQconnectStartParams()

PGconn* PQconnectStartParams ( const char *const *  keywords,
const char *const *  values,
int  expand_dbname 
)

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

757 {
758  PGconn *conn;
759  PQconninfoOption *connOptions;
760 
761  /*
762  * Allocate memory for the conn structure. Note that we also expect this
763  * to initialize conn->errorMessage to empty. All subsequent steps during
764  * connection initialization will only append to that buffer.
765  */
766  conn = makeEmptyPGconn();
767  if (conn == NULL)
768  return NULL;
769 
770  /*
771  * Parse the conninfo arrays
772  */
773  connOptions = conninfo_array_parse(keywords, values,
774  &conn->errorMessage,
775  true, expand_dbname);
776  if (connOptions == NULL)
777  {
779  /* errorMessage is already set */
780  return conn;
781  }
782 
783  /*
784  * Move option values into conn structure
785  */
786  if (!fillPGconn(conn, connOptions))
787  {
788  PQconninfoFree(connOptions);
789  return conn;
790  }
791 
792  /*
793  * Free the option info - all is in conn now
794  */
795  PQconninfoFree(connOptions);
796 
797  /*
798  * Compute derived options
799  */
800  if (!connectOptions2(conn))
801  return conn;
802 
803  /*
804  * Connect to the database
805  */
806  if (!connectDBStart(conn))
807  {
808  /* Just in case we failed to set it in connectDBStart */
810  }
811 
812  return conn;
813 }
static PQconninfoOption * conninfo_array_parse(const char *const *keywords, const char *const *values, PQExpBuffer errorMessage, bool use_defaults, int expand_dbname)
Definition: fe-connect.c:5648
static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
Definition: fe-connect.c:881

References conn, connectDBStart(), CONNECTION_BAD, connectOptions2(), conninfo_array_parse(), pg_conn::errorMessage, fillPGconn(), makeEmptyPGconn(), PQconninfoFree(), pg_conn::status, and values.

Referenced by libpqrcv_connect(), PQconnectdbParams(), and PQpingParams().

◆ PQconninfo()

PQconninfoOption* PQconninfo ( PGconn conn)

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

6533 {
6534  PQExpBufferData errorBuf;
6535  PQconninfoOption *connOptions;
6536 
6537  if (conn == NULL)
6538  return NULL;
6539 
6540  /*
6541  * We don't actually report any errors here, but callees want a buffer,
6542  * and we prefer not to trash the conn's errorMessage.
6543  */
6544  initPQExpBuffer(&errorBuf);
6545  if (PQExpBufferDataBroken(errorBuf))
6546  return NULL; /* out of memory already :-( */
6547 
6548  connOptions = conninfo_init(&errorBuf);
6549 
6550  if (connOptions != NULL)
6551  {
6553 
6554  for (option = PQconninfoOptions; option->keyword; option++)
6555  {
6556  char **connmember;
6557 
6558  if (option->connofs < 0)
6559  continue;
6560 
6561  connmember = (char **) ((char *) conn + option->connofs);
6562 
6563  if (*connmember)
6564  conninfo_storeval(connOptions, option->keyword, *connmember,
6565  &errorBuf, true, false);
6566  }
6567  }
6568 
6569  termPQExpBuffer(&errorBuf);
6570 
6571  return connOptions;
6572 }
static PQconninfoOption * conninfo_storeval(PQconninfoOption *connOptions, const char *keyword, const char *value, PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode)
Definition: fe-connect.c:6450
static const internalPQconninfoOption PQconninfoOptions[]
Definition: fe-connect.c:188

References conn, conninfo_init(), conninfo_storeval(), initPQExpBuffer(), PQconninfoOptions, PQExpBufferDataBroken, and termPQExpBuffer().

Referenced by do_connect(), GenerateRecoveryConfig(), and libpqrcv_get_conninfo().

◆ PQconninfoFree()

void PQconninfoFree ( PQconninfoOption connOptions)

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

6577 {
6578  if (connOptions == NULL)
6579  return;
6580 
6581  for (PQconninfoOption *option = connOptions; option->keyword != NULL; option++)
6582  free(option->val);
6583  free(connOptions);
6584 }
int val
Definition: getopt_long.h:21

References free, and option::val.

Referenced by check_pghost_envvar(), connectDatabase(), connectOptions1(), conninfo_array_parse(), conninfo_parse(), conninfo_uri_parse(), dblink_connstr_check(), do_connect(), GenerateRecoveryConfig(), GetConnection(), libpqrcv_check_conninfo(), libpqrcv_get_conninfo(), PQconndefaults(), and PQconnectStartParams().

◆ PQconninfoParse()

PQconninfoOption* PQconninfoParse ( const char *  conninfo,
char **  errmsg 
)

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

5358 {
5359  PQExpBufferData errorBuf;
5360  PQconninfoOption *connOptions;
5361 
5362  if (errmsg)
5363  *errmsg = NULL; /* default */
5364  initPQExpBuffer(&errorBuf);
5365  if (PQExpBufferDataBroken(errorBuf))
5366  return NULL; /* out of memory already :-( */
5367  connOptions = parse_connection_string(conninfo, &errorBuf, false);
5368  if (connOptions == NULL && errmsg)
5369  *errmsg = errorBuf.data;
5370  else
5371  termPQExpBuffer(&errorBuf);
5372  return connOptions;
5373 }
int errmsg(const char *fmt,...)
Definition: elog.c:906
static PQconninfoOption * parse_connection_string(const char *connstr, PQExpBuffer errorMessage, bool use_defaults)
Definition: fe-connect.c:5418

References PQExpBufferData::data, errmsg(), initPQExpBuffer(), parse_connection_string(), PQExpBufferDataBroken, and termPQExpBuffer().

Referenced by connectDatabase(), dblink_connstr_check(), do_connect(), GetConnection(), libpqrcv_check_conninfo(), and main().

◆ PQconsumeInput()

int PQconsumeInput ( PGconn conn)

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

1954 {
1955  if (!conn)
1956  return 0;
1957 
1958  /*
1959  * for non-blocking connections try to flush the send-queue, otherwise we
1960  * may never get a response for something that may not have already been
1961  * sent because it's in our write buffer!
1962  */
1963  if (pqIsnonblocking(conn))
1964  {
1965  if (pqFlush(conn) < 0)
1966  return 0;
1967  }
1968 
1969  /*
1970  * Load more data, if available. We do this no matter what state we are
1971  * in, since we are probably getting called because the application wants
1972  * to get rid of a read-select condition. Note that we will NOT block
1973  * waiting for more input.
1974  */
1975  if (pqReadData(conn) < 0)
1976  return 0;
1977 
1978  /* Parsing of the data waits till later. */
1979  return 1;
1980 }
#define pqIsnonblocking(conn)
Definition: libpq-int.h:871

References conn, pqFlush(), pqIsnonblocking, and pqReadData().

Referenced by advanceConnectionState(), CopyStreamReceive(), dblink_get_notify(), dblink_is_busy(), do_sql_command_end(), ecpg_process_output(), libpqrcv_PQgetResult(), libpqrcv_receive(), main(), pgfdw_get_cleanup_result(), pgfdw_get_result(), postgresForeignAsyncNotify(), PQconnectPoll(), PrintNotifications(), StreamLogicalLog(), test_nosync(), test_pipelined_insert(), test_uniqviol(), try_complete_step(), and wait_on_slots().

◆ PQcopyResult()

PGresult* PQcopyResult ( const PGresult src,
int  flags 
)

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

316 {
317  PGresult *dest;
318  int i;
319 
320  if (!src)
321  return NULL;
322 
324  if (!dest)
325  return NULL;
326 
327  /* Always copy these over. Is cmdStatus really useful here? */
328  dest->client_encoding = src->client_encoding;
329  strcpy(dest->cmdStatus, src->cmdStatus);
330 
331  /* Wants attrs? */
332  if (flags & (PG_COPYRES_ATTRS | PG_COPYRES_TUPLES))
333  {
334  if (!PQsetResultAttrs(dest, src->numAttributes, src->attDescs))
335  {
336  PQclear(dest);
337  return NULL;
338  }
339  }
340 
341  /* Wants to copy tuples? */
342  if (flags & PG_COPYRES_TUPLES)
343  {
344  int tup,
345  field;
346 
347  for (tup = 0; tup < src->ntups; tup++)
348  {
349  for (field = 0; field < src->numAttributes; field++)
350  {
351  if (!PQsetvalue(dest, tup, field,
352  src->tuples[tup][field].value,
353  src->tuples[tup][field].len))
354  {
355  PQclear(dest);
356  return NULL;
357  }
358  }
359  }
360  }
361 
362  /* Wants to copy notice hooks? */
363  if (flags & PG_COPYRES_NOTICEHOOKS)
364  dest->noticeHooks = src->noticeHooks;
365 
366  /* Wants to copy PGEvents? */
367  if ((flags & PG_COPYRES_EVENTS) && src->nEvents > 0)
368  {
369  dest->events = dupEvents(src->events, src->nEvents,
370  &dest->memorySize);
371  if (!dest->events)
372  {
373  PQclear(dest);
374  return NULL;
375  }
376  dest->nEvents = src->nEvents;
377  }
378 
379  /* Okay, trigger PGEVT_RESULTCOPY event */
380  for (i = 0; i < dest->nEvents; i++)
381  {
382  /* We don't fire events that had some previous failure */
383  if (src->events[i].resultInitialized)
384  {
385  PGEventResultCopy evt;
386 
387  evt.src = src;
388  evt.dest = dest;
389  if (dest->events[i].proc(PGEVT_RESULTCOPY, &evt,
390  dest->events[i].passThrough))
391  dest->events[i].resultInitialized = true;
392  }
393  }
394 
395  return dest;
396 }
int PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs)
Definition: fe-exec.c:246
void PQclear(PGresult *res)
Definition: fe-exec.c:718
static PGEvent * dupEvents(PGEvent *events, int count, size_t *memSize)
Definition: fe-exec.c:405
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:157
int PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len)
Definition: fe-exec.c:449
@ PGEVT_RESULTCOPY
Definition: libpq-events.h:33
#define PG_COPYRES_TUPLES
Definition: libpq-fe.h:46
#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
const PGresult * src
Definition: libpq-events.h:60
PGresult * dest
Definition: libpq-events.h:61
int ntups
Definition: libpq-int.h:171
int numAttributes
Definition: libpq-int.h:172
int client_encoding
Definition: libpq-int.h:191
char * value
Definition: libpq-int.h:140

References pg_result::attDescs, pg_result::client_encoding, pg_result::cmdStatus, generate_unaccent_rules::dest, PGEventResultCopy::dest, dupEvents(), pg_result::events, i, pgresAttValue::len, pg_result::nEvents, pg_result::noticeHooks, pg_result::ntups, pg_result::numAttributes, PG_COPYRES_ATTRS, PG_COPYRES_EVENTS, PG_COPYRES_NOTICEHOOKS, PG_COPYRES_TUPLES, PGEVT_RESULTCOPY, PGRES_TUPLES_OK, PQclear(), PQmakeEmptyPGresult(), PQsetResultAttrs(), PQsetvalue(), PGEvent::resultInitialized, PGEventResultCopy::src, pg_result::tuples, and pgresAttValue::value.

Referenced by pqRowProcessor().

◆ PQdb()

◆ PQdefaultSSLKeyPassHook_OpenSSL()

int PQdefaultSSLKeyPassHook_OpenSSL ( char *  buf,
int  size,
PGconn conn 
)

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

1900 {
1901  if (conn && conn->sslpassword)
1902  {
1903  if (strlen(conn->sslpassword) + 1 > size)
1904  fprintf(stderr, libpq_gettext("WARNING: sslpassword truncated\n"));
1905  strncpy(buf, conn->sslpassword, size);
1906  buf[size - 1] = '\0';
1907  return strlen(buf);
1908  }
1909  else
1910  {
1911  buf[0] = '\0';
1912  return 0;
1913  }
1914 }
#define libpq_gettext(x)
Definition: libpq-int.h:882
#define fprintf
Definition: port.h:242
char * sslpassword
Definition: libpq-int.h:386

References buf, conn, fprintf, libpq_gettext, and pg_conn::sslpassword.

Referenced by PQssl_passwd_cb().

◆ PQdescribePortal()

PGresult* PQdescribePortal ( PGconn conn,
const char *  portal 
)

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

2438 {
2439  if (!PQexecStart(conn))
2440  return NULL;
2441  if (!PQsendDescribe(conn, 'P', portal))
2442  return NULL;
2443  return PQexecFinish(conn);
2444 }
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2373
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2307
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2482

References conn, PQexecFinish(), PQexecStart(), and PQsendDescribe().

◆ PQdescribePrepared()

PGresult* PQdescribePrepared ( PGconn conn,
const char *  stmt 
)

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

2419 {
2420  if (!PQexecStart(conn))
2421  return NULL;
2422  if (!PQsendDescribe(conn, 'S', stmt))
2423  return NULL;
2424  return PQexecFinish(conn);
2425 }

References conn, PQexecFinish(), PQexecStart(), and PQsendDescribe().

Referenced by DescribeQuery(), and ECPGdescribe().

◆ PQdisplayTuples()

void PQdisplayTuples ( const PGresult res,
FILE *  fp,
int  fillAlign,
const char *  fieldSep,
int  printHeader,
int  quiet 
)

Definition at line 585 of file fe-print.c.

592 {
593 #define DEFAULT_FIELD_SEP " "
594 
595  int i,
596  j;
597  int nFields;
598  int nTuples;
599  int *fLength = NULL;
600 
601  if (fieldSep == NULL)
602  fieldSep = DEFAULT_FIELD_SEP;
603 
604  /* Get some useful info about the results */
605  nFields = PQnfields(res);
606  nTuples = PQntuples(res);
607 
608  if (fp == NULL)
609  fp = stdout;
610 
611  /* Figure the field lengths to align to */
612  /* will be somewhat time consuming for very large results */
613  if (fillAlign)
614  {
615  fLength = (int *) malloc(nFields * sizeof(int));
616  if (!fLength)
617  {
618  fprintf(stderr, libpq_gettext("out of memory\n"));
619  return;
620  }
621 
622  for (j = 0; j < nFields; j++)
623  {
624  fLength[j] = strlen(PQfname(res, j));
625  for (i = 0; i < nTuples; i++)
626  {
627  int flen = PQgetlength(res, i, j);
628 
629  if (flen > fLength[j])
630  fLength[j] = flen;
631  }
632  }
633  }
634 
635  if (printHeader)
636  {
637  /* first, print out the attribute names */
638  for (i = 0; i < nFields; i++)
639  {
640  fputs(PQfname(res, i), fp);
641  if (fillAlign)
642  fill(strlen(PQfname(res, i)), fLength[i], ' ', fp);
643  fputs(fieldSep, fp);
644  }
645  fprintf(fp, "\n");
646 
647  /* Underline the attribute names */
648  for (i = 0; i < nFields; i++)
649  {
650  if (fillAlign)
651  fill(0, fLength[i], '-', fp);
652  fputs(fieldSep, fp);
653  }
654  fprintf(fp, "\n");
655  }
656 
657  /* next, print out the instances */
658  for (i = 0; i < nTuples; i++)
659  {
660  for (j = 0; j < nFields; j++)
661  {
662  fprintf(fp, "%s", PQgetvalue(res, i, j));
663  if (fillAlign)
664  fill(strlen(PQgetvalue(res, i, j)), fLength[j], ' ', fp);
665  fputs(fieldSep, fp);
666  }
667  fprintf(fp, "\n");
668  }
669 
670  if (!quiet)
671  fprintf(fp, "\nQuery returned %d row%s.\n", PQntuples(res),
672  (PQntuples(res) == 1) ? "" : "s");
673 
674  fflush(fp);
675 
676  free(fLength);
677 }
int PQgetlength(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3716
char * PQfname(const PGresult *res, int field_num)
Definition: fe-exec.c:3396
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3318
static void fill(int length, int max, char filler, FILE *fp)
Definition: fe-print.c:766
#define DEFAULT_FIELD_SEP
#define malloc(a)
Definition: header.h:50
int j
Definition: isn.c:74
static void const char fflush(stdout)

References DEFAULT_FIELD_SEP, fflush(), fill(), fprintf, free, i, j, libpq_gettext, malloc, PQfname(), PQgetlength(), PQgetvalue(), PQnfields(), PQntuples(), res, and generate_unaccent_rules::stdout.

◆ PQdsplen()

int PQdsplen ( const char *  s,
int  encoding 
)

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

1198 {
1199  return pg_encoding_dsplen(encoding, s);
1200 }
int pg_encoding_dsplen(int encoding, const char *mbstr)
Definition: wchar.c:2151

References encoding, and pg_encoding_dsplen().

Referenced by get_prompt(), pg_wcsformat(), pg_wcssize(), pg_wcswidth(), and strlen_max_width().

◆ PQencryptPassword()

char* PQencryptPassword ( const char *  passwd,
const char *  user 
)

Definition at line 1147 of file fe-auth.c.

1148 {
1149  char *crypt_pwd;
1150  const char *errstr = NULL;
1151 
1152  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1153  if (!crypt_pwd)
1154  return NULL;
1155 
1156  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd, &errstr))
1157  {
1158  free(crypt_pwd);
1159  return NULL;
1160  }
1161 
1162  return crypt_pwd;
1163 }
#define MD5_PASSWD_LEN
Definition: md5.h:26
bool pg_md5_encrypt(const char *passwd, const char *salt, size_t salt_len, char *buf, const char **errstr)
Definition: md5_common.c:144
static char * user
Definition: pg_regress.c:93

References free, malloc, MD5_PASSWD_LEN, pg_md5_encrypt(), and user.

◆ PQencryptPasswordConn()

char* PQencryptPasswordConn ( PGconn conn,
const char *  passwd,
const char *  user,
const char *  algorithm 
)

Definition at line 1190 of file fe-auth.c.

1192 {
1193 #define MAX_ALGORITHM_NAME_LEN 50
1194  char algobuf[MAX_ALGORITHM_NAME_LEN + 1];
1195  char *crypt_pwd = NULL;
1196 
1197  if (!conn)
1198  return NULL;
1199 
1201 
1202  /* If no algorithm was given, ask the server. */
1203  if (algorithm == NULL)
1204  {
1205  PGresult *res;
1206  char *val;
1207 
1208  res = PQexec(conn, "show password_encryption");
1209  if (res == NULL)
1210  {
1211  /* PQexec() should've set conn->errorMessage already */
1212  return NULL;
1213  }
1215  {
1216  /* PQexec() should've set conn->errorMessage already */
1217  PQclear(res);
1218  return NULL;
1219  }
1220  if (PQntuples(res) != 1 || PQnfields(res) != 1)
1221  {
1222  PQclear(res);
1223  libpq_append_conn_error(conn, "unexpected shape of result set returned for SHOW");
1224  return NULL;
1225  }
1226  val = PQgetvalue(res, 0, 0);
1227 
1228  if (strlen(val) > MAX_ALGORITHM_NAME_LEN)
1229  {
1230  PQclear(res);
1231  libpq_append_conn_error(conn, "password_encryption value too long");
1232  return NULL;
1233  }
1234  strcpy(algobuf, val);
1235  PQclear(res);
1236 
1237  algorithm = algobuf;
1238  }
1239 
1240  /*
1241  * Also accept "on" and "off" as aliases for "md5", because
1242  * password_encryption was a boolean before PostgreSQL 10. We refuse to
1243  * send the password in plaintext even if it was "off".
1244  */
1245  if (strcmp(algorithm, "on") == 0 ||
1246  strcmp(algorithm, "off") == 0)
1247  algorithm = "md5";
1248 
1249  /*
1250  * Ok, now we know what algorithm to use
1251  */
1252  if (strcmp(algorithm, "scram-sha-256") == 0)
1253  {
1254  const char *errstr = NULL;
1255 
1256  crypt_pwd = pg_fe_scram_build_secret(passwd, &errstr);
1257  if (!crypt_pwd)
1258  libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
1259  }
1260  else if (strcmp(algorithm, "md5") == 0)
1261  {
1262  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1263  if (crypt_pwd)
1264  {
1265  const char *errstr = NULL;
1266 
1267  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd, &errstr))
1268  {
1269  libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
1270  free(crypt_pwd);
1271  crypt_pwd = NULL;
1272  }
1273  }
1274  else
1275  libpq_append_conn_error(conn, "out of memory");
1276  }
1277  else
1278  {
1279  libpq_append_conn_error(conn, "unrecognized password encryption algorithm \"%s\"",
1280  algorithm);
1281  return NULL;
1282  }
1283 
1284  return crypt_pwd;
1285 }
char * pg_fe_scram_build_secret(const char *password, const char **errstr)
#define MAX_ALGORITHM_NAME_LEN
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2225

References conn, free, libpq_append_conn_error(), malloc, MAX_ALGORITHM_NAME_LEN, MD5_PASSWD_LEN, pg_fe_scram_build_secret(), pg_md5_encrypt(), PGRES_TUPLES_OK, PQclear(), pqClearConnErrorState, PQexec(), PQgetvalue(), PQnfields(), PQntuples(), PQresultStatus(), res, user, and val.

Referenced by exec_command_password(), and main().

◆ PQendcopy()

int PQendcopy ( PGconn conn)

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

2832 {
2833  if (!conn)
2834  return 0;
2835 
2836  return pqEndcopy3(conn);
2837 }
int pqEndcopy3(PGconn *conn)

References conn, and pqEndcopy3().

Referenced by ecpg_check_PQresult(), initGenerateDataClientSide(), and libpqrcv_endstreaming().

◆ PQenterPipelineMode()

int PQenterPipelineMode ( PGconn conn)

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

2925 {
2926  if (!conn)
2927  return 0;
2928 
2929  /* succeed with no action if already in pipeline mode */
2931  return 1;
2932 
2933  if (conn->asyncStatus != PGASYNC_IDLE)
2934  {
2935  libpq_append_conn_error(conn, "cannot enter pipeline mode, connection not idle");
2936  return 0;
2937  }
2938 
2940 
2941  return 1;
2942 }

References pg_conn::asyncStatus, conn, libpq_append_conn_error(), PGASYNC_IDLE, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, and PQ_PIPELINE_ON.

Referenced by executeMetaCommand(), test_disallowed_in_pipeline(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_pipeline_idle(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), test_transaction(), and test_uniqviol().

◆ PQenv2encoding()

int PQenv2encoding ( void  )

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

1207 {
1208  char *str;
1209  int encoding = PG_SQL_ASCII;
1210 
1211  str = getenv("PGCLIENTENCODING");
1212  if (str && *str != '\0')
1213  {
1215  if (encoding < 0)
1217  }
1218  return encoding;
1219 }
int pg_char_to_encoding(const char *name)
Definition: encnames.c:550
@ PG_SQL_ASCII
Definition: pg_wchar.h:226

References encoding, pg_char_to_encoding(), PG_SQL_ASCII, and generate_unaccent_rules::str.

Referenced by main().

◆ PQerrorMessage()

char* PQerrorMessage ( const PGconn conn)

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

6744 {
6745  if (!conn)
6746  return libpq_gettext("connection pointer is NULL\n");
6747 
6748  /*
6749  * The errorMessage buffer might be marked "broken" due to having
6750  * previously failed to allocate enough memory for the message. In that
6751  * case, tell the application we ran out of memory.
6752  */
6754  return libpq_gettext("out of memory\n");
6755 
6756  return conn->errorMessage.data;
6757 }
#define PQExpBufferBroken(str)
Definition: pqexpbuffer.h:59

References conn, PQExpBufferData::data, pg_conn::errorMessage, libpq_gettext, and PQExpBufferBroken.

Referenced by _doSetSessionAuth(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), AcceptResult(), advanceConnectionState(), BaseBackup(), check_loadable_libraries(), check_prepare_conn(), CheckCopyStreamStop(), cluster_one_database(), compile_database_list(), compile_relation_list_one_db(), connect_pg_server(), ConnectDatabase(), connectDatabase(), connectToServer(), CopyStreamPoll(), CopyStreamReceive(), CreateReplicationSlot(), dblink_connect(), dblink_error_message(), dblink_get_conn(), dblink_res_error(), dblink_send_query(), DescribeQuery(), die_on_query_failure(), do_connect(), do_lo_export(), do_lo_import(), do_lo_unlink(), doConnect(), DropReplicationSlot(), dump_lo_buf(), dumpBlobs(), dumpTableData_copy(), ecpg_check_PQresult(), ecpg_raise_backend(), ECPGconnect(), EndDBCopyMode(), exec_command_password(), ExecQueryAndProcessResults(), executeCommand(), executeQuery(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlCommandBuf(), executeStatement(), GetConnection(), GetSlotInformation(), GetTableInfo(), handleCopyIn(), handleCopyOut(), HandleEndOfCopyStream(), initGenerateDataClientSide(), libpqrcv_connect(), libpqrcv_create_slot(), libpqrcv_endstreaming(), libpqrcv_exec(), libpqrcv_identify_system(), libpqrcv_readtimelinehistoryfile(), libpqrcv_receive(), libpqrcv_send(), libpqrcv_startstreaming(), main(), my_truncate(), overwrite(), pgfdw_cancel_query(), pgfdw_report_error(), pickout(), process_queued_fetch_requests(), process_result(), ProcessXLogDataMsg(), psql_get_variable(), readCommandResponse(), ReceiveCopyData(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_command(), run_permutation(), run_reindex_command(), run_vacuum_command(), RunIdentifySystem(), sendCommand(), sendFeedback(), SendQuery(), sql_conn(), sql_exec(), start_postmaster(), StartRestoreBlob(), storeQueryResult(), StreamLogicalLog(), TableCommandResultHandler(), test_disallowed_in_pipeline(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_pipeline_idle(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), test_transaction(), test_uniqviol(), threadRun(), try_complete_step(), tryExecuteStatement(), vacuumlo(), verify_btree_slot_handler(), and verify_heap_slot_handler().

◆ PQescapeBytea()

unsigned char* PQescapeBytea ( const unsigned char *  from,
size_t  from_length,
size_t *  to_length 
)

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

4303 {
4304  return PQescapeByteaInternal(NULL, from, from_length, to_length,
4306  false /* can't use hex */ );
4307 }