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:2866
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3244
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::@165 u
Oid fn_lo_close
Definition: libpq-int.h:273
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:489

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 dumpLOs(), EndRestoreLO(), 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 StartRestoreLO().

◆ 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:1260
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:868
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 dumpLOs(), exportFile(), importFile(), lo_export(), lo_import_internal(), my_truncate(), overwrite(), pickout(), and StartRestoreLO().

◆ 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:1232
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:772
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:571
#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()

const char* pg_encoding_to_char ( int  encoding)

◆ 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 7054 of file fe-connect.c.

7055 {
7056  if (!conn || conn->status != CONNECTION_OK)
7057  return 0;
7058  return conn->be_pid;
7059 }
int be_pid
Definition: libpq-int.h:480
ConnStatusType status
Definition: libpq-int.h:415

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 3330 of file fe-exec.c.

3331 {
3332  if (!res)
3333  return 0;
3334  return res->binary;
3335 }
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 4626 of file fe-connect.c.

4627 {
4628  int save_errno = SOCK_ERRNO;
4629  pgsocket tmpsock = PGINVALID_SOCKET;
4630  int maxlen;
4631  struct
4632  {
4633  uint32 packetlen;
4635  } crp;
4636 
4637  if (!cancel)
4638  {
4639  strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
4640  /* strlcpy probably doesn't change errno, but be paranoid */
4641  SOCK_ERRNO_SET(save_errno);
4642  return false;
4643  }
4644 
4645  /*
4646  * We need to open a temporary connection to the postmaster. Do this with
4647  * only kernel calls.
4648  */
4649  if ((tmpsock = socket(cancel->raddr.addr.ss_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
4650  {
4651  strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
4652  goto cancel_errReturn;
4653  }
4654 
4655  /*
4656  * Since this connection will only be used to send a single packet of
4657  * data, we don't need NODELAY. We also don't set the socket to
4658  * nonblocking mode, because the API definition of PQcancel requires the
4659  * cancel to be sent in a blocking way.
4660  *
4661  * We do set socket options related to keepalives and other TCP timeouts.
4662  * This ensures that this function does not block indefinitely when
4663  * reasonable keepalive and timeout settings have been provided.
4664  */
4665  if (cancel->raddr.addr.ss_family != AF_UNIX &&
4666  cancel->keepalives != 0)
4667  {
4668 #ifndef WIN32
4669  if (!optional_setsockopt(tmpsock, SOL_SOCKET, SO_KEEPALIVE, 1))
4670  {
4671  strlcpy(errbuf, "PQcancel() -- setsockopt(SO_KEEPALIVE) failed: ", errbufsize);
4672  goto cancel_errReturn;
4673  }
4674 
4675 #ifdef PG_TCP_KEEPALIVE_IDLE
4676  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
4677  cancel->keepalives_idle))
4678  {
4679  strlcpy(errbuf, "PQcancel() -- setsockopt(" PG_TCP_KEEPALIVE_IDLE_STR ") failed: ", errbufsize);
4680  goto cancel_errReturn;
4681  }
4682 #endif
4683 
4684 #ifdef TCP_KEEPINTVL
4685  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_KEEPINTVL,
4686  cancel->keepalives_interval))
4687  {
4688  strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_KEEPINTVL) failed: ", errbufsize);
4689  goto cancel_errReturn;
4690  }
4691 #endif
4692 
4693 #ifdef TCP_KEEPCNT
4694  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_KEEPCNT,
4695  cancel->keepalives_count))
4696  {
4697  strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_KEEPCNT) failed: ", errbufsize);
4698  goto cancel_errReturn;
4699  }
4700 #endif
4701 
4702 #else /* WIN32 */
4703 
4704 #ifdef SIO_KEEPALIVE_VALS
4705  if (!setKeepalivesWin32(tmpsock,
4706  cancel->keepalives_idle,
4707  cancel->keepalives_interval))
4708  {
4709  strlcpy(errbuf, "PQcancel() -- WSAIoctl(SIO_KEEPALIVE_VALS) failed: ", errbufsize);
4710  goto cancel_errReturn;
4711  }
4712 #endif /* SIO_KEEPALIVE_VALS */
4713 #endif /* WIN32 */
4714 
4715  /* TCP_USER_TIMEOUT works the same way on Unix and Windows */
4716 #ifdef TCP_USER_TIMEOUT
4717  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_USER_TIMEOUT,
4718  cancel->pgtcp_user_timeout))
4719  {
4720  strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_USER_TIMEOUT) failed: ", errbufsize);
4721  goto cancel_errReturn;
4722  }
4723 #endif
4724  }
4725 
4726 retry3:
4727  if (connect(tmpsock, (struct sockaddr *) &cancel->raddr.addr,
4728  cancel->raddr.salen) < 0)
4729  {
4730  if (SOCK_ERRNO == EINTR)
4731  /* Interrupted system call - we'll just try again */
4732  goto retry3;
4733  strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
4734  goto cancel_errReturn;
4735  }
4736 
4737  /* Create and send the cancel request packet. */
4738 
4739  crp.packetlen = pg_hton32((uint32) sizeof(crp));
4740  crp.cp.cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE);
4741  crp.cp.backendPID = pg_hton32(cancel->be_pid);
4742  crp.cp.cancelAuthCode = pg_hton32(cancel->be_key);
4743 
4744 retry4:
4745  if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
4746  {
4747  if (SOCK_ERRNO == EINTR)
4748  /* Interrupted system call - we'll just try again */
4749  goto retry4;
4750  strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
4751  goto cancel_errReturn;
4752  }
4753 
4754  /*
4755  * Wait for the postmaster to close the connection, which indicates that
4756  * it's processed the request. Without this delay, we might issue another
4757  * command only to find that our cancel zaps that command instead of the
4758  * one we thought we were canceling. Note we don't actually expect this
4759  * read to obtain any data, we are just waiting for EOF to be signaled.
4760  */
4761 retry5:
4762  if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
4763  {
4764  if (SOCK_ERRNO == EINTR)
4765  /* Interrupted system call - we'll just try again */
4766  goto retry5;
4767  /* we ignore other error conditions */
4768  }
4769 
4770  /* All done */
4771  closesocket(tmpsock);
4772  SOCK_ERRNO_SET(save_errno);
4773  return true;
4774 
4775 cancel_errReturn:
4776 
4777  /*
4778  * Make sure we don't overflow the error buffer. Leave space for the \n at
4779  * the end, and for the terminating zero.
4780  */
4781  maxlen = errbufsize - strlen(errbuf) - 2;
4782  if (maxlen >= 0)
4783  {
4784  /*
4785  * We can't invoke strerror here, since it's not signal-safe. Settle
4786  * for printing the decimal value of errno. Even that has to be done
4787  * the hard way.
4788  */
4789  int val = SOCK_ERRNO;
4790  char buf[32];
4791  char *bufp;
4792 
4793  bufp = buf + sizeof(buf) - 1;
4794  *bufp = '\0';
4795  do
4796  {
4797  *(--bufp) = (val % 10) + '0';
4798  val /= 10;
4799  } while (val > 0);
4800  bufp -= 6;
4801  memcpy(bufp, "error ", 6);
4802  strncat(errbuf, bufp, maxlen);
4803  strcat(errbuf, "\n");
4804  }
4805  if (tmpsock != PGINVALID_SOCKET)
4806  closesocket(tmpsock);
4807  SOCK_ERRNO_SET(save_errno);
4808  return false;
4809 }
unsigned int uint32
Definition: c.h:490
static bool optional_setsockopt(int fd, int protoid, int optid, int value)
Definition: fe-connect.c:4594
long val
Definition: informix.c:664
#define SOCK_ERRNO
Definition: libpq-int.h:916
#define SOCK_ERRNO_SET(e)
Definition: libpq-int.h:918
#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:139
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:617
int keepalives_interval
Definition: libpq-int.h:620
int keepalives_idle
Definition: libpq-int.h:619
int keepalives_count
Definition: libpq-int.h:622
SockAddr raddr
Definition: libpq-int.h:614
int be_pid
Definition: libpq-int.h:615
int keepalives
Definition: libpq-int.h:618
int be_key
Definition: libpq-int.h:616
#define EINTR
Definition: win32_port.h:376
#define recv(s, buf, len, flags)
Definition: win32_port.h:500
#define send(s, buf, len, flags)
Definition: win32_port.h:501
#define socket(af, type, protocol)
Definition: win32_port.h:494
#define connect(s, name, namelen)
Definition: win32_port.h:498

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 3585 of file fe-exec.c.

3586 {
3587  if (!res)
3588  return NULL;
3589  return res->cmdStatus;
3590 }
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 3655 of file fe-exec.c.

3656 {
3657  char *p,
3658  *c;
3659 
3660  if (!res)
3661  return "";
3662 
3663  if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3664  {
3665  p = res->cmdStatus + 7;
3666  /* INSERT: skip oid and space */
3667  while (*p && *p != ' ')
3668  p++;
3669  if (*p == 0)
3670  goto interpret_error; /* no space? */
3671  p++;
3672  }
3673  else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3674  strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3675  strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3676  p = res->cmdStatus + 7;
3677  else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0 ||
3678  strncmp(res->cmdStatus, "MERGE ", 6) == 0)
3679  p = res->cmdStatus + 6;
3680  else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3681  strncmp(res->cmdStatus, "COPY ", 5) == 0)
3682  p = res->cmdStatus + 5;
3683  else
3684  return "";
3685 
3686  /* check that we have an integer (at least one digit, nothing else) */
3687  for (c = p; *c; c++)
3688  {
3689  if (!isdigit((unsigned char) *c))
3690  goto interpret_error;
3691  }
3692  if (c == p)
3693  goto interpret_error;
3694 
3695  return p;
3696 
3697 interpret_error:
3699  "could not interpret result from server: %s",
3700  res->cmdStatus);
3701  return "";
3702 }
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 1665 of file fe-connect.c.

1666 {
1667  PQExpBufferData errorBuf;
1668  PQconninfoOption *connOptions;
1669 
1670  /* We don't actually report any errors here, but callees want a buffer */
1671  initPQExpBuffer(&errorBuf);
1672  if (PQExpBufferDataBroken(errorBuf))
1673  return NULL; /* out of memory already :-( */
1674 
1675  connOptions = conninfo_init(&errorBuf);
1676  if (connOptions != NULL)
1677  {
1678  /* pass NULL errorBuf to ignore errors */
1679  if (!conninfo_add_defaults(connOptions, NULL))
1680  {
1681  PQconninfoFree(connOptions);
1682  connOptions = NULL;
1683  }
1684  }
1685 
1686  termPQExpBuffer(&errorBuf);
1687  return connOptions;
1688 }
static PQconninfoOption * conninfo_init(PQExpBuffer errorMessage)
Definition: fe-connect.c:5656
static bool conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
Definition: fe-connect.c:6083
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:6853
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 719 of file fe-connect.c.

720 {
721  PGconn *conn = PQconnectStart(conninfo);
722 
723  if (conn && conn->status != CONNECTION_BAD)
724  (void) connectDBComplete(conn);
725 
726  return conn;
727 }
PGconn * PQconnectStart(const char *conninfo)
Definition: fe-connect.c:847
static int connectDBComplete(PGconn *conn)
Definition: fe-connect.c:2292

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

Referenced by get_db_conn(), and main().

◆ PQconnectdbParams()

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

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

667 {
668  PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
669 
670  if (conn && conn->status != CONNECTION_BAD)
671  (void) connectDBComplete(conn);
672 
673  return conn;
674 }
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:766

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

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

◆ PQconnectionNeedsPassword()

int PQconnectionNeedsPassword ( const PGconn conn)

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

7072 {
7073  char *password;
7074 
7075  if (!conn)
7076  return false;
7077  password = PQpass(conn);
7078  if (conn->password_needed &&
7079  (password == NULL || password[0] == '\0'))
7080  return true;
7081  else
7082  return false;
7083 }
char * PQpass(const PGconn *conn)
Definition: fe-connect.c:6882
static char * password
Definition: streamutil.c:53
bool password_needed
Definition: libpq-int.h:456

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 7086 of file fe-connect.c.

7087 {
7088  if (!conn)
7089  return false;
7090  if (conn->password_needed)
7091  return true;
7092  else
7093  return false;
7094 }

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 2428 of file fe-connect.c.

2429 {
2430  bool reset_connection_state_machine = false;
2431  bool need_new_connection = false;
2432  PGresult *res;
2433  char sebuf[PG_STRERROR_R_BUFLEN];
2434  int optval;
2435 
2436  if (conn == NULL)
2437  return PGRES_POLLING_FAILED;
2438 
2439  /* Get the new data */
2440  switch (conn->status)
2441  {
2442  /*
2443  * We really shouldn't have been polled in these two cases, but we
2444  * can handle it.
2445  */
2446  case CONNECTION_BAD:
2447  return PGRES_POLLING_FAILED;
2448  case CONNECTION_OK:
2449  return PGRES_POLLING_OK;
2450 
2451  /* These are reading states */
2453  case CONNECTION_AUTH_OK:
2455  case CONNECTION_CONSUME:
2457  {
2458  /* Load waiting data */
2459  int n = pqReadData(conn);
2460 
2461  if (n < 0)
2462  goto error_return;
2463  if (n == 0)
2464  return PGRES_POLLING_READING;
2465 
2466  break;
2467  }
2468 
2469  /* These are writing states, so we just proceed. */
2470  case CONNECTION_STARTED:
2471  case CONNECTION_MADE:
2472  break;
2473 
2474  /* Special cases: proceed without waiting. */
2476  case CONNECTION_NEEDED:
2479  break;
2480 
2481  default:
2482  libpq_append_conn_error(conn, "invalid connection state, probably indicative of memory corruption");
2483  goto error_return;
2484  }
2485 
2486 
2487 keep_going: /* We will come back to here until there is
2488  * nothing left to do. */
2489 
2490  /* Time to advance to next address, or next host if no more addresses? */
2491  if (conn->try_next_addr)
2492  {
2493  if (conn->addr_cur && conn->addr_cur->ai_next)
2494  {
2495  conn->addr_cur = conn->addr_cur->ai_next;
2496  reset_connection_state_machine = true;
2497  }
2498  else
2499  conn->try_next_host = true;
2500  conn->try_next_addr = false;
2501  }
2502 
2503  /* Time to advance to next connhost[] entry? */
2504  if (conn->try_next_host)
2505  {
2506  pg_conn_host *ch;
2507  struct addrinfo hint;
2508  int thisport;
2509  int ret;
2510  char portstr[MAXPGPATH];
2511 
2512  if (conn->whichhost + 1 < conn->nconnhost)
2513  conn->whichhost++;
2514  else
2515  {
2516  /*
2517  * Oops, no more hosts.
2518  *
2519  * If we are trying to connect in "prefer-standby" mode, then drop
2520  * the standby requirement and start over.
2521  *
2522  * Otherwise, an appropriate error message is already set up, so
2523  * we just need to set the right status.
2524  */
2526  conn->nconnhost > 0)
2527  {
2529  conn->whichhost = 0;
2530  }
2531  else
2532  goto error_return;
2533  }
2534 
2535  /* Drop any address info for previous host */
2537 
2538  /*
2539  * Look up info for the new host. On failure, log the problem in
2540  * conn->errorMessage, then loop around to try the next host. (Note
2541  * we don't clear try_next_host until we've succeeded.)
2542  */
2543  ch = &conn->connhost[conn->whichhost];
2544 
2545  /* Initialize hint structure */
2546  MemSet(&hint, 0, sizeof(hint));
2547  hint.ai_socktype = SOCK_STREAM;
2548  conn->addrlist_family = hint.ai_family = AF_UNSPEC;
2549 
2550  /* Figure out the port number we're going to use. */
2551  if (ch->port == NULL || ch->port[0] == '\0')
2552  thisport = DEF_PGPORT;
2553  else
2554  {
2555  if (!parse_int_param(ch->port, &thisport, conn, "port"))
2556  goto error_return;
2557 
2558  if (thisport < 1 || thisport > 65535)
2559  {
2560  libpq_append_conn_error(conn, "invalid port number: \"%s\"", ch->port);
2561  goto keep_going;
2562  }
2563  }
2564  snprintf(portstr, sizeof(portstr), "%d", thisport);
2565 
2566  /* Use pg_getaddrinfo_all() to resolve the address */
2567  switch (ch->type)
2568  {
2569  case CHT_HOST_NAME:
2570  ret = pg_getaddrinfo_all(ch->host, portstr, &hint,
2571  &conn->addrlist);
2572  if (ret || !conn->addrlist)
2573  {
2574  libpq_append_conn_error(conn, "could not translate host name \"%s\" to address: %s",
2575  ch->host, gai_strerror(ret));
2576  goto keep_going;
2577  }
2578  break;
2579 
2580  case CHT_HOST_ADDRESS:
2581  hint.ai_flags = AI_NUMERICHOST;
2582  ret = pg_getaddrinfo_all(ch->hostaddr, portstr, &hint,
2583  &conn->addrlist);
2584  if (ret || !conn->addrlist)
2585  {
2586  libpq_append_conn_error(conn, "could not parse network address \"%s\": %s",
2587  ch->hostaddr, gai_strerror(ret));
2588  goto keep_going;
2589  }
2590  break;
2591 
2592  case CHT_UNIX_SOCKET:
2593  conn->addrlist_family = hint.ai_family = AF_UNIX;
2594  UNIXSOCK_PATH(portstr, thisport, ch->host);
2595  if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)
2596  {
2597  libpq_append_conn_error(conn, "Unix-domain socket path \"%s\" is too long (maximum %d bytes)",
2598  portstr,
2599  (int) (UNIXSOCK_PATH_BUFLEN - 1));
2600  goto keep_going;
2601  }
2602 
2603  /*
2604  * NULL hostname tells pg_getaddrinfo_all to parse the service
2605  * name as a Unix-domain socket path.
2606  */
2607  ret = pg_getaddrinfo_all(NULL, portstr, &hint,
2608  &conn->addrlist);
2609  if (ret || !conn->addrlist)
2610  {
2611  libpq_append_conn_error(conn, "could not translate Unix-domain socket path \"%s\" to address: %s",
2612  portstr, gai_strerror(ret));
2613  goto keep_going;
2614  }
2615  break;
2616  }
2617 
2618  /* OK, scan this addrlist for a working server address */
2619  conn->addr_cur = conn->addrlist;
2620  reset_connection_state_machine = true;
2621  conn->try_next_host = false;
2622  }
2623 
2624  /* Reset connection state machine? */
2625  if (reset_connection_state_machine)
2626  {
2627  /*
2628  * (Re) initialize our connection control variables for a set of
2629  * connection attempts to a single server address. These variables
2630  * must persist across individual connection attempts, but we must
2631  * reset them when we start to consider a new server.
2632  */
2633  conn->pversion = PG_PROTOCOL(3, 0);
2634  conn->send_appname = true;
2635 #ifdef USE_SSL
2636  /* initialize these values based on SSL mode */
2637  conn->allow_ssl_try = (conn->sslmode[0] != 'd'); /* "disable" */
2638  conn->wait_ssl_try = (conn->sslmode[0] == 'a'); /* "allow" */
2639 #endif
2640 #ifdef ENABLE_GSS
2641  conn->try_gss = (conn->gssencmode[0] != 'd'); /* "disable" */
2642 #endif
2643 
2644  reset_connection_state_machine = false;
2645  need_new_connection = true;
2646  }
2647 
2648  /* Force a new connection (perhaps to the same server as before)? */
2649  if (need_new_connection)
2650  {
2651  /* Drop any existing connection */
2652  pqDropConnection(conn, true);
2653 
2654  /* Reset all state obtained from old server */
2656 
2657  /* Drop any PGresult we might have, too */
2662 
2663  /* Reset conn->status to put the state machine in the right state */
2665 
2666  need_new_connection = false;
2667  }
2668 
2669  /* Now try to advance the state machine for this connection */
2670  switch (conn->status)
2671  {
2672  case CONNECTION_NEEDED:
2673  {
2674  /*
2675  * Try to initiate a connection to one of the addresses
2676  * returned by pg_getaddrinfo_all(). conn->addr_cur is the
2677  * next one to try.
2678  *
2679  * The extra level of braces here is historical. It's not
2680  * worth reindenting this whole switch case to remove 'em.
2681  */
2682  {
2683  struct addrinfo *addr_cur = conn->addr_cur;
2684  char host_addr[NI_MAXHOST];
2685  int sock_type;
2686 
2687  /*
2688  * Advance to next possible host, if we've tried all of
2689  * the addresses for the current host.
2690  */
2691  if (addr_cur == NULL)
2692  {
2693  conn->try_next_host = true;
2694  goto keep_going;
2695  }
2696 
2697  /* Remember current address for possible use later */
2698  memcpy(&conn->raddr.addr, addr_cur->ai_addr,
2699  addr_cur->ai_addrlen);
2700  conn->raddr.salen = addr_cur->ai_addrlen;
2701 
2702  /*
2703  * Set connip, too. Note we purposely ignore strdup
2704  * failure; not a big problem if it fails.
2705  */
2706  if (conn->connip != NULL)
2707  {
2708  free(conn->connip);
2709  conn->connip = NULL;
2710  }
2711  getHostaddr(conn, host_addr, NI_MAXHOST);
2712  if (host_addr[0])
2713  conn->connip = strdup(host_addr);
2714 
2715  /* Try to create the socket */
2716  sock_type = SOCK_STREAM;
2717 #ifdef SOCK_CLOEXEC
2718 
2719  /*
2720  * Atomically mark close-on-exec, if possible on this
2721  * platform, so that there isn't a window where a
2722  * subprogram executed by another thread inherits the
2723  * socket. See fallback code below.
2724  */
2725  sock_type |= SOCK_CLOEXEC;
2726 #endif
2727 #ifdef SOCK_NONBLOCK
2728 
2729  /*
2730  * We might as well skip a system call for nonblocking
2731  * mode too, if we can.
2732  */
2733  sock_type |= SOCK_NONBLOCK;
2734 #endif
2735  conn->sock = socket(addr_cur->ai_family, sock_type, 0);
2736  if (conn->sock == PGINVALID_SOCKET)
2737  {
2738  int errorno = SOCK_ERRNO;
2739 
2740  /*
2741  * Silently ignore socket() failure if we have more
2742  * addresses to try; this reduces useless chatter in
2743  * cases where the address list includes both IPv4 and
2744  * IPv6 but kernel only accepts one family.
2745  */
2746  if (addr_cur->ai_next != NULL ||
2747  conn->whichhost + 1 < conn->nconnhost)
2748  {
2749  conn->try_next_addr = true;
2750  goto keep_going;
2751  }
2752  emitHostIdentityInfo(conn, host_addr);
2753  libpq_append_conn_error(conn, "could not create socket: %s",
2754  SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)));
2755  goto error_return;
2756  }
2757 
2758  /*
2759  * Once we've identified a target address, all errors
2760  * except the preceding socket()-failure case should be
2761  * prefixed with host-identity information. (If the
2762  * connection succeeds, the contents of conn->errorMessage
2763  * won't matter, so this is harmless.)
2764  */
2765  emitHostIdentityInfo(conn, host_addr);
2766 
2767  /*
2768  * Select socket options: no delay of outgoing data for
2769  * TCP sockets, nonblock mode, close-on-exec. Try the
2770  * next address if any of this fails.
2771  */
2772  if (addr_cur->ai_family != AF_UNIX)
2773  {
2774  if (!connectNoDelay(conn))
2775  {
2776  /* error message already created */
2777  conn->try_next_addr = true;
2778  goto keep_going;
2779  }
2780  }
2781 #ifndef SOCK_NONBLOCK
2782  if (!pg_set_noblock(conn->sock))
2783  {
2784  libpq_append_conn_error(conn, "could not set socket to nonblocking mode: %s",
2785  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2786  conn->try_next_addr = true;
2787  goto keep_going;
2788  }
2789 #endif
2790 
2791 #ifndef SOCK_CLOEXEC
2792 #ifdef F_SETFD
2793  if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
2794  {
2795  libpq_append_conn_error(conn, "could not set socket to close-on-exec mode: %s",
2796  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2797  conn->try_next_addr = true;
2798  goto keep_going;
2799  }
2800 #endif /* F_SETFD */
2801 #endif
2802 
2803  if (addr_cur->ai_family != AF_UNIX)
2804  {
2805 #ifndef WIN32
2806  int on = 1;
2807 #endif
2808  int usekeepalives = useKeepalives(conn);
2809  int err = 0;
2810 
2811  if (usekeepalives < 0)
2812  {
2813  libpq_append_conn_error(conn, "keepalives parameter must be an integer");
2814  err = 1;
2815  }
2816  else if (usekeepalives == 0)
2817  {
2818  /* Do nothing */
2819  }
2820 #ifndef WIN32
2821  else if (setsockopt(conn->sock,
2822  SOL_SOCKET, SO_KEEPALIVE,
2823  (char *) &on, sizeof(on)) < 0)
2824  {
2825  libpq_append_conn_error(conn, "%s(%s) failed: %s",
2826  "setsockopt",
2827  "SO_KEEPALIVE",
2828  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2829  err = 1;
2830  }
2831  else if (!setKeepalivesIdle(conn)
2833  || !setKeepalivesCount(conn))
2834  err = 1;
2835 #else /* WIN32 */
2836 #ifdef SIO_KEEPALIVE_VALS
2837  else if (!prepKeepalivesWin32(conn))
2838  err = 1;
2839 #endif /* SIO_KEEPALIVE_VALS */
2840 #endif /* WIN32 */
2841  else if (!setTCPUserTimeout(conn))
2842  err = 1;
2843 
2844  if (err)
2845  {
2846  conn->try_next_addr = true;
2847  goto keep_going;
2848  }
2849  }
2850 
2851  /*----------
2852  * We have three methods of blocking SIGPIPE during
2853  * send() calls to this socket:
2854  *
2855  * - setsockopt(sock, SO_NOSIGPIPE)
2856  * - send(sock, ..., MSG_NOSIGNAL)
2857  * - setting the signal mask to SIG_IGN during send()
2858  *
2859  * The third method requires three syscalls per send,
2860  * so we prefer either of the first two, but they are
2861  * less portable. The state is tracked in the following
2862  * members of PGconn:
2863  *
2864  * conn->sigpipe_so - we have set up SO_NOSIGPIPE
2865  * conn->sigpipe_flag - we're specifying MSG_NOSIGNAL
2866  *
2867  * If we can use SO_NOSIGPIPE, then set sigpipe_so here
2868  * and we're done. Otherwise, set sigpipe_flag so that
2869  * we will try MSG_NOSIGNAL on sends. If we get an error
2870  * with MSG_NOSIGNAL, we'll clear that flag and revert to
2871  * signal masking.
2872  *----------
2873  */
2874  conn->sigpipe_so = false;
2875 #ifdef MSG_NOSIGNAL
2876  conn->sigpipe_flag = true;
2877 #else
2878  conn->sigpipe_flag = false;
2879 #endif /* MSG_NOSIGNAL */
2880 
2881 #ifdef SO_NOSIGPIPE
2882  optval = 1;
2883  if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
2884  (char *) &optval, sizeof(optval)) == 0)
2885  {
2886  conn->sigpipe_so = true;
2887  conn->sigpipe_flag = false;
2888  }
2889 #endif /* SO_NOSIGPIPE */
2890 
2891  /*
2892  * Start/make connection. This should not block, since we
2893  * are in nonblock mode. If it does, well, too bad.
2894  */
2895  if (connect(conn->sock, addr_cur->ai_addr,
2896  addr_cur->ai_addrlen) < 0)
2897  {
2898  if (SOCK_ERRNO == EINPROGRESS ||
2899 #ifdef WIN32
2900  SOCK_ERRNO == EWOULDBLOCK ||
2901 #endif
2902  SOCK_ERRNO == EINTR)
2903  {
2904  /*
2905  * This is fine - we're in non-blocking mode, and
2906  * the connection is in progress. Tell caller to
2907  * wait for write-ready on socket.
2908  */
2910  return PGRES_POLLING_WRITING;
2911  }
2912  /* otherwise, trouble */
2913  }
2914  else
2915  {
2916  /*
2917  * Hm, we're connected already --- seems the "nonblock
2918  * connection" wasn't. Advance the state machine and
2919  * go do the next stuff.
2920  */
2922  goto keep_going;
2923  }
2924 
2925  /*
2926  * This connection failed. Add the error report to
2927  * conn->errorMessage, then try the next address if any.
2928  */
2930  conn->try_next_addr = true;
2931  goto keep_going;
2932  }
2933  }
2934 
2935  case CONNECTION_STARTED:
2936  {
2937  socklen_t optlen = sizeof(optval);
2938 
2939  /*
2940  * Write ready, since we've made it here, so the connection
2941  * has been made ... or has failed.
2942  */
2943 
2944  /*
2945  * Now check (using getsockopt) that there is not an error
2946  * state waiting for us on the socket.
2947  */
2948 
2949  if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
2950  (char *) &optval, &optlen) == -1)
2951  {
2952  libpq_append_conn_error(conn, "could not get socket error status: %s",
2953  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2954  goto error_return;
2955  }
2956  else if (optval != 0)
2957  {
2958  /*
2959  * When using a nonblocking connect, we will typically see
2960  * connect failures at this point, so provide a friendly
2961  * error message.
2962  */
2963  connectFailureMessage(conn, optval);
2964 
2965  /*
2966  * Try the next address if any, just as in the case where
2967  * connect() returned failure immediately.
2968  */
2969  conn->try_next_addr = true;
2970  goto keep_going;
2971  }
2972 
2973  /* Fill in the client address */
2974  conn->laddr.salen = sizeof(conn->laddr.addr);
2975  if (getsockname(conn->sock,
2976  (struct sockaddr *) &conn->laddr.addr,
2977  &conn->laddr.salen) < 0)
2978  {
2979  libpq_append_conn_error(conn, "could not get client address from socket: %s",
2980  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2981  goto error_return;
2982  }
2983 
2984  /*
2985  * Make sure we can write before advancing to next step.
2986  */
2988  return PGRES_POLLING_WRITING;
2989  }
2990 
2991  case CONNECTION_MADE:
2992  {
2993  char *startpacket;
2994  int packetlen;
2995 
2996  /*
2997  * Implement requirepeer check, if requested and it's a
2998  * Unix-domain socket.
2999  */
3000  if (conn->requirepeer && conn->requirepeer[0] &&
3001  conn->raddr.addr.ss_family == AF_UNIX)
3002  {
3003 #ifndef WIN32
3004  char *remote_username;
3005 #endif
3006  uid_t uid;
3007  gid_t gid;
3008 
3009  errno = 0;
3010  if (getpeereid(conn->sock, &uid, &gid) != 0)
3011  {
3012  /*
3013  * Provide special error message if getpeereid is a
3014  * stub
3015  */
3016  if (errno == ENOSYS)
3017  libpq_append_conn_error(conn, "requirepeer parameter is not supported on this platform");
3018  else
3019  libpq_append_conn_error(conn, "could not get peer credentials: %s",
3020  strerror_r(errno, sebuf, sizeof(sebuf)));
3021  goto error_return;
3022  }
3023 
3024 #ifndef WIN32
3025  remote_username = pg_fe_getusername(uid,
3026  &conn->errorMessage);
3027  if (remote_username == NULL)
3028  goto error_return; /* message already logged */
3029 
3030  if (strcmp(remote_username, conn->requirepeer) != 0)
3031  {
3032  libpq_append_conn_error(conn, "requirepeer specifies \"%s\", but actual peer user name is \"%s\"",
3033  conn->requirepeer, remote_username);
3034  free(remote_username);
3035  goto error_return;
3036  }
3037  free(remote_username);
3038 #else /* WIN32 */
3039  /* should have failed with ENOSYS above */
3040  Assert(false);
3041 #endif /* WIN32 */
3042  }
3043 
3044  if (conn->raddr.addr.ss_family == AF_UNIX)
3045  {
3046  /* Don't request SSL or GSSAPI over Unix sockets */
3047 #ifdef USE_SSL
3048  conn->allow_ssl_try = false;
3049 #endif
3050 #ifdef ENABLE_GSS
3051  conn->try_gss = false;
3052 #endif
3053  }
3054 
3055 #ifdef ENABLE_GSS
3056 
3057  /*
3058  * If GSSAPI encryption is enabled, then call
3059  * pg_GSS_have_cred_cache() which will return true if we can
3060  * acquire credentials (and give us a handle to use in
3061  * conn->gcred), and then send a packet to the server asking
3062  * for GSSAPI Encryption (and skip past SSL negotiation and
3063  * regular startup below).
3064  */
3065  if (conn->try_gss && !conn->gctx)
3066  conn->try_gss = pg_GSS_have_cred_cache(&conn->gcred);
3067  if (conn->try_gss && !conn->gctx)
3068  {
3070 
3071  if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
3072  {
3073  libpq_append_conn_error(conn, "could not send GSSAPI negotiation packet: %s",
3074  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3075  goto error_return;
3076  }
3077 
3078  /* Ok, wait for response */
3080  return PGRES_POLLING_READING;
3081  }
3082  else if (!conn->gctx && conn->gssencmode[0] == 'r')
3083  {
3085  "GSSAPI encryption required but was impossible (possibly no credential cache, no server support, or using a local socket)");
3086  goto error_return;
3087  }
3088 #endif
3089 
3090 #ifdef USE_SSL
3091 
3092  /*
3093  * Enable the libcrypto callbacks before checking if SSL needs
3094  * to be done. This is done before sending the startup packet
3095  * as depending on the type of authentication done, like MD5
3096  * or SCRAM that use cryptohashes, the callbacks would be
3097  * required even without a SSL connection
3098  */
3099  if (pqsecure_initialize(conn, false, true) < 0)
3100  goto error_return;
3101 
3102  /*
3103  * If SSL is enabled and we haven't already got encryption of
3104  * some sort running, request SSL instead of sending the
3105  * startup message.
3106  */
3107  if (conn->allow_ssl_try && !conn->wait_ssl_try &&
3108  !conn->ssl_in_use
3109 #ifdef ENABLE_GSS
3110  && !conn->gssenc
3111 #endif
3112  )
3113  {
3114  ProtocolVersion pv;
3115 
3116  /*
3117  * Send the SSL request packet.
3118  *
3119  * Theoretically, this could block, but it really
3120  * shouldn't since we only got here if the socket is
3121  * write-ready.
3122  */
3124  if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
3125  {
3126  libpq_append_conn_error(conn, "could not send SSL negotiation packet: %s",
3127  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3128  goto error_return;
3129  }
3130  /* Ok, wait for response */
3132  return PGRES_POLLING_READING;
3133  }
3134 #endif /* USE_SSL */
3135 
3136  /*
3137  * Build the startup packet.
3138  */
3139  startpacket = pqBuildStartupPacket3(conn, &packetlen,
3141  if (!startpacket)
3142  {
3143  libpq_append_conn_error(conn, "out of memory");
3144  goto error_return;
3145  }
3146 
3147  /*
3148  * Send the startup packet.
3149  *
3150  * Theoretically, this could block, but it really shouldn't
3151  * since we only got here if the socket is write-ready.
3152  */
3153  if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
3154  {
3155  libpq_append_conn_error(conn, "could not send startup packet: %s",
3156  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3157  free(startpacket);
3158  goto error_return;
3159  }
3160 
3161  free(startpacket);
3162 
3164  return PGRES_POLLING_READING;
3165  }
3166 
3167  /*
3168  * Handle SSL negotiation: wait for postmaster messages and
3169  * respond as necessary.
3170  */
3172  {
3173 #ifdef USE_SSL
3174  PostgresPollingStatusType pollres;
3175 
3176  /*
3177  * On first time through, get the postmaster's response to our
3178  * SSL negotiation packet.
3179  */
3180  if (!conn->ssl_in_use)
3181  {
3182  /*
3183  * We use pqReadData here since it has the logic to
3184  * distinguish no-data-yet from connection closure. Since
3185  * conn->ssl isn't set, a plain recv() will occur.
3186  */
3187  char SSLok;
3188  int rdresult;
3189 
3190  rdresult = pqReadData(conn);
3191  if (rdresult < 0)
3192  {
3193  /* errorMessage is already filled in */
3194  goto error_return;
3195  }
3196  if (rdresult == 0)
3197  {
3198  /* caller failed to wait for data */
3199  return PGRES_POLLING_READING;
3200  }
3201  if (pqGetc(&SSLok, conn) < 0)
3202  {
3203  /* should not happen really */
3204  return PGRES_POLLING_READING;
3205  }
3206  if (SSLok == 'S')
3207  {
3208  /* mark byte consumed */
3209  conn->inStart = conn->inCursor;
3210 
3211  /*
3212  * Set up global SSL state if required. The crypto
3213  * state has already been set if libpq took care of
3214  * doing that, so there is no need to make that happen
3215  * again.
3216  */
3217  if (pqsecure_initialize(conn, true, false) != 0)
3218  goto error_return;
3219  }
3220  else if (SSLok == 'N')
3221  {
3222  /* mark byte consumed */
3223  conn->inStart = conn->inCursor;
3224  /* OK to do without SSL? */
3225  if (conn->sslmode[0] == 'r' || /* "require" */
3226  conn->sslmode[0] == 'v') /* "verify-ca" or
3227  * "verify-full" */
3228  {
3229  /* Require SSL, but server does not want it */
3230  libpq_append_conn_error(conn, "server does not support SSL, but SSL was required");
3231  goto error_return;
3232  }
3233  /* Otherwise, proceed with normal startup */
3234  conn->allow_ssl_try = false;
3235  /* We can proceed using this connection */
3237  return PGRES_POLLING_WRITING;
3238  }
3239  else if (SSLok == 'E')
3240  {
3241  /*
3242  * Server failure of some sort, such as failure to
3243  * fork a backend process. We need to process and
3244  * report the error message, which might be formatted
3245  * according to either protocol 2 or protocol 3.
3246  * Rather than duplicate the code for that, we flip
3247  * into AWAITING_RESPONSE state and let the code there
3248  * deal with it. Note we have *not* consumed the "E"
3249  * byte here.
3250  */
3252  goto keep_going;
3253  }
3254  else
3255  {
3256  libpq_append_conn_error(conn, "received invalid response to SSL negotiation: %c",
3257  SSLok);
3258  goto error_return;
3259  }
3260  }
3261 
3262  /*
3263  * Begin or continue the SSL negotiation process.
3264  */
3265  pollres = pqsecure_open_client(conn);
3266  if (pollres == PGRES_POLLING_OK)
3267  {
3268  /*
3269  * At this point we should have no data already buffered.
3270  * If we do, it was received before we performed the SSL
3271  * handshake, so it wasn't encrypted and indeed may have
3272  * been injected by a man-in-the-middle.
3273  */
3274  if (conn->inCursor != conn->inEnd)
3275  {
3276  libpq_append_conn_error(conn, "received unencrypted data after SSL response");
3277  goto error_return;
3278  }
3279 
3280  /* SSL handshake done, ready to send startup packet */
3282  return PGRES_POLLING_WRITING;
3283  }
3284  if (pollres == PGRES_POLLING_FAILED)
3285  {
3286  /*
3287  * Failed ... if sslmode is "prefer" then do a non-SSL
3288  * retry
3289  */
3290  if (conn->sslmode[0] == 'p' /* "prefer" */
3291  && conn->allow_ssl_try /* redundant? */
3292  && !conn->wait_ssl_try) /* redundant? */
3293  {
3294  /* only retry once */
3295  conn->allow_ssl_try = false;
3296  need_new_connection = true;
3297  goto keep_going;
3298  }
3299  /* Else it's a hard failure */
3300  goto error_return;
3301  }
3302  /* Else, return POLLING_READING or POLLING_WRITING status */
3303  return pollres;
3304 #else /* !USE_SSL */
3305  /* can't get here */
3306  goto error_return;
3307 #endif /* USE_SSL */
3308  }
3309 
3311  {
3312 #ifdef ENABLE_GSS
3313  PostgresPollingStatusType pollres;
3314 
3315  /*
3316  * If we haven't yet, get the postmaster's response to our
3317  * negotiation packet
3318  */
3319  if (conn->try_gss && !conn->gctx)
3320  {
3321  char gss_ok;
3322  int rdresult = pqReadData(conn);
3323 
3324  if (rdresult < 0)
3325  /* pqReadData fills in error message */
3326  goto error_return;
3327  else if (rdresult == 0)
3328  /* caller failed to wait for data */
3329  return PGRES_POLLING_READING;
3330  if (pqGetc(&gss_ok, conn) < 0)
3331  /* shouldn't happen... */
3332  return PGRES_POLLING_READING;
3333 
3334  if (gss_ok == 'E')
3335  {
3336  /*
3337  * Server failure of some sort. Assume it's a
3338  * protocol version support failure, and let's see if
3339  * we can't recover (if it's not, we'll get a better
3340  * error message on retry). Server gets fussy if we
3341  * don't hang up the socket, though.
3342  */
3343  conn->try_gss = false;
3344  need_new_connection = true;
3345  goto keep_going;
3346  }
3347 
3348  /* mark byte consumed */
3349  conn->inStart = conn->inCursor;
3350 
3351  if (gss_ok == 'N')
3352  {
3353  /* Server doesn't want GSSAPI; fall back if we can */
3354  if (conn->gssencmode[0] == 'r')
3355  {
3356  libpq_append_conn_error(conn, "server doesn't support GSSAPI encryption, but it was required");
3357  goto error_return;
3358  }
3359 
3360  conn->try_gss = false;
3361  /* We can proceed using this connection */
3363  return PGRES_POLLING_WRITING;
3364  }
3365  else if (gss_ok != 'G')
3366  {
3367  libpq_append_conn_error(conn, "received invalid response to GSSAPI negotiation: %c",
3368  gss_ok);
3369  goto error_return;
3370  }
3371  }
3372 
3373  /* Begin or continue GSSAPI negotiation */
3374  pollres = pqsecure_open_gss(conn);
3375  if (pollres == PGRES_POLLING_OK)
3376  {
3377  /*
3378  * At this point we should have no data already buffered.
3379  * If we do, it was received before we performed the GSS
3380  * handshake, so it wasn't encrypted and indeed may have
3381  * been injected by a man-in-the-middle.
3382  */
3383  if (conn->inCursor != conn->inEnd)
3384  {
3385  libpq_append_conn_error(conn, "received unencrypted data after GSSAPI encryption response");
3386  goto error_return;
3387  }
3388 
3389  /* All set for startup packet */
3391  return PGRES_POLLING_WRITING;
3392  }
3393  else if (pollres == PGRES_POLLING_FAILED)
3394  {
3395  if (conn->gssencmode[0] == 'p')
3396  {
3397  /*
3398  * We failed, but we can retry on "prefer". Have to
3399  * drop the current connection to do so, though.
3400  */
3401  conn->try_gss = false;
3402  need_new_connection = true;
3403  goto keep_going;
3404  }
3405  /* Else it's a hard failure */
3406  goto error_return;
3407  }
3408  /* Else, return POLLING_READING or POLLING_WRITING status */
3409  return pollres;
3410 #else /* !ENABLE_GSS */
3411  /* unreachable */
3412  goto error_return;
3413 #endif /* ENABLE_GSS */
3414  }
3415 
3416  /*
3417  * Handle authentication exchange: wait for postmaster messages
3418  * and respond as necessary.
3419  */
3421  {
3422  char beresp;
3423  int msgLength;
3424  int avail;
3425  AuthRequest areq;
3426  int res;
3427 
3428  /*
3429  * Scan the message from current point (note that if we find
3430  * the message is incomplete, we will return without advancing
3431  * inStart, and resume here next time).
3432  */
3433  conn->inCursor = conn->inStart;
3434 
3435  /* Read type byte */
3436  if (pqGetc(&beresp, conn))
3437  {
3438  /* We'll come back when there is more data */
3439  return PGRES_POLLING_READING;
3440  }
3441 
3442  /*
3443  * Validate message type: we expect only an authentication
3444  * request, NegotiateProtocolVersion, or an error here.
3445  * Anything else probably means it's not Postgres on the other
3446  * end at all.
3447  */
3448  if (!(beresp == 'R' || beresp == 'v' || beresp == 'E'))
3449  {
3450  libpq_append_conn_error(conn, "expected authentication request from server, but received %c",
3451  beresp);
3452  goto error_return;
3453  }
3454 
3455  /* Read message length word */
3456  if (pqGetInt(&msgLength, 4, conn))
3457  {
3458  /* We'll come back when there is more data */
3459  return PGRES_POLLING_READING;
3460  }
3461 
3462  /*
3463  * Try to validate message length before using it.
3464  *
3465  * Authentication requests can't be very large, although GSS
3466  * auth requests may not be that small. Same for
3467  * NegotiateProtocolVersion.
3468  *
3469  * Errors can be a little larger, but not huge. If we see a
3470  * large apparent length in an error, it means we're really
3471  * talking to a pre-3.0-protocol server; cope. (Before
3472  * version 14, the server also used the old protocol for
3473  * errors that happened before processing the startup packet.)
3474  */
3475  if (beresp == 'R' && (msgLength < 8 || msgLength > 2000))
3476  {
3477  libpq_append_conn_error(conn, "received invalid authentication request");
3478  goto error_return;
3479  }
3480  if (beresp == 'v' && (msgLength < 8 || msgLength > 2000))
3481  {
3482  libpq_append_conn_error(conn, "received invalid protocol negotiation message");
3483  goto error_return;
3484  }
3485 
3486 #define MAX_ERRLEN 30000
3487  if (beresp == 'E' && (msgLength < 8 || msgLength > MAX_ERRLEN))
3488  {
3489  /* Handle error from a pre-3.0 server */
3490  conn->inCursor = conn->inStart + 1; /* reread data */
3492  {
3493  /*
3494  * We may not have authenticated the server yet, so
3495  * don't let the buffer grow forever.
3496  */
3497  avail = conn->inEnd - conn->inCursor;
3498  if (avail > MAX_ERRLEN)
3499  {
3500  libpq_append_conn_error(conn, "received invalid error message");
3501  goto error_return;
3502  }
3503 
3504  /* We'll come back when there is more data */
3505  return PGRES_POLLING_READING;
3506  }
3507  /* OK, we read the message; mark data consumed */
3508  conn->inStart = conn->inCursor;
3509 
3510  /*
3511  * Before 7.2, the postmaster didn't always end its
3512  * messages with a newline, so add one if needed to
3513  * conform to libpq conventions.
3514  */
3515  if (conn->errorMessage.len == 0 ||
3516  conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
3517  {
3519  }
3520 
3521  goto error_return;
3522  }
3523 #undef MAX_ERRLEN
3524 
3525  /*
3526  * Can't process if message body isn't all here yet.
3527  *
3528  * After this check passes, any further EOF during parsing
3529  * implies that the server sent a bad/truncated message.
3530  * Reading more bytes won't help in that case, so don't return
3531  * PGRES_POLLING_READING after this point.
3532  */
3533  msgLength -= 4;
3534  avail = conn->inEnd - conn->inCursor;
3535  if (avail < msgLength)
3536  {
3537  /*
3538  * Before returning, try to enlarge the input buffer if
3539  * needed to hold the whole message; see notes in
3540  * pqParseInput3.
3541  */
3542  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
3543  conn))
3544  goto error_return;
3545  /* We'll come back when there is more data */
3546  return PGRES_POLLING_READING;
3547  }
3548 
3549  /* Handle errors. */
3550  if (beresp == 'E')
3551  {
3552  if (pqGetErrorNotice3(conn, true))
3553  {
3554  libpq_append_conn_error(conn, "received invalid error message");
3555  goto error_return;
3556  }
3557  /* OK, we read the message; mark data consumed */
3558  conn->inStart = conn->inCursor;
3559 
3560  /*
3561  * If error is "cannot connect now", try the next host if
3562  * any (but we don't want to consider additional addresses
3563  * for this host, nor is there much point in changing SSL
3564  * or GSS mode). This is helpful when dealing with
3565  * standby servers that might not be in hot-standby state.
3566  */
3567  if (strcmp(conn->last_sqlstate,
3569  {
3570  conn->try_next_host = true;
3571  goto keep_going;
3572  }
3573 
3574  /* Check to see if we should mention pgpassfile */
3576 
3577 #ifdef ENABLE_GSS
3578 
3579  /*
3580  * If gssencmode is "prefer" and we're using GSSAPI, retry
3581  * without it.
3582  */
3583  if (conn->gssenc && conn->gssencmode[0] == 'p')
3584  {
3585  /* only retry once */
3586  conn->try_gss = false;
3587  need_new_connection = true;
3588  goto keep_going;
3589  }
3590 #endif
3591 
3592 #ifdef USE_SSL
3593 
3594  /*
3595  * if sslmode is "allow" and we haven't tried an SSL
3596  * connection already, then retry with an SSL connection
3597  */
3598  if (conn->sslmode[0] == 'a' /* "allow" */
3599  && !conn->ssl_in_use
3600  && conn->allow_ssl_try
3601  && conn->wait_ssl_try)
3602  {
3603  /* only retry once */
3604  conn->wait_ssl_try = false;
3605  need_new_connection = true;
3606  goto keep_going;
3607  }
3608 
3609  /*
3610  * if sslmode is "prefer" and we're in an SSL connection,
3611  * then do a non-SSL retry
3612  */
3613  if (conn->sslmode[0] == 'p' /* "prefer" */
3614  && conn->ssl_in_use
3615  && conn->allow_ssl_try /* redundant? */
3616  && !conn->wait_ssl_try) /* redundant? */
3617  {
3618  /* only retry once */
3619  conn->allow_ssl_try = false;
3620  need_new_connection = true;
3621  goto keep_going;
3622  }
3623 #endif
3624 
3625  goto error_return;
3626  }
3627  else if (beresp == 'v')
3628  {
3630  {
3631  libpq_append_conn_error(conn, "received invalid protocol negotiation message");
3632  goto error_return;
3633  }
3634  /* OK, we read the message; mark data consumed */
3635  conn->inStart = conn->inCursor;
3636  goto error_return;
3637  }
3638 
3639  /* It is an authentication request. */
3640  conn->auth_req_received = true;
3641 
3642  /* Get the type of request. */
3643  if (pqGetInt((int *) &areq, 4, conn))
3644  {
3645  /* can't happen because we checked the length already */
3646  libpq_append_conn_error(conn, "received invalid authentication request");
3647  goto error_return;
3648  }
3649  msgLength -= 4;
3650 
3651  /*
3652  * Process the rest of the authentication request message, and
3653  * respond to it if necessary.
3654  *
3655  * Note that conn->pghost must be non-NULL if we are going to
3656  * avoid the Kerberos code doing a hostname look-up.
3657  */
3658  res = pg_fe_sendauth(areq, msgLength, conn);
3659 
3660  /* OK, we have processed the message; mark data consumed */
3661  conn->inStart = conn->inCursor;
3662 
3663  if (res != STATUS_OK)
3664  goto error_return;
3665 
3666  /*
3667  * Just make sure that any data sent by pg_fe_sendauth is
3668  * flushed out. Although this theoretically could block, it
3669  * really shouldn't since we don't send large auth responses.
3670  */
3671  if (pqFlush(conn))
3672  goto error_return;
3673 
3674  if (areq == AUTH_REQ_OK)
3675  {
3676  /* We are done with authentication exchange */
3678 
3679  /*
3680  * Set asyncStatus so that PQgetResult will think that
3681  * what comes back next is the result of a query. See
3682  * below.
3683  */
3685  }
3686 
3687  /* Look to see if we have more data yet. */
3688  goto keep_going;
3689  }
3690 
3691  case CONNECTION_AUTH_OK:
3692  {
3693  /*
3694  * Now we expect to hear from the backend. A ReadyForQuery
3695  * message indicates that startup is successful, but we might
3696  * also get an Error message indicating failure. (Notice
3697  * messages indicating nonfatal warnings are also allowed by
3698  * the protocol, as are ParameterStatus and BackendKeyData
3699  * messages.) Easiest way to handle this is to let
3700  * PQgetResult() read the messages. We just have to fake it
3701  * out about the state of the connection, by setting
3702  * asyncStatus = PGASYNC_BUSY (done above).
3703  */
3704 
3705  if (PQisBusy(conn))
3706  return PGRES_POLLING_READING;
3707 
3708  res = PQgetResult(conn);
3709 
3710  /*
3711  * NULL return indicating we have gone to IDLE state is
3712  * expected
3713  */
3714  if (res)
3715  {
3717  libpq_append_conn_error(conn, "unexpected message from server during startup");
3718  else if (conn->send_appname &&
3719  (conn->appname || conn->fbappname))
3720  {
3721  /*
3722  * If we tried to send application_name, check to see
3723  * if the error is about that --- pre-9.0 servers will
3724  * reject it at this stage of the process. If so,
3725  * close the connection and retry without sending
3726  * application_name. We could possibly get a false
3727  * SQLSTATE match here and retry uselessly, but there
3728  * seems no great harm in that; we'll just get the
3729  * same error again if it's unrelated.
3730  */
3731  const char *sqlstate;
3732 
3734  if (sqlstate &&
3735  strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
3736  {
3737  PQclear(res);
3738  conn->send_appname = false;
3739  need_new_connection = true;
3740  goto keep_going;
3741  }
3742  }
3743 
3744  /*
3745  * if the resultStatus is FATAL, then conn->errorMessage
3746  * already has a copy of the error; needn't copy it back.
3747  * But add a newline if it's not there already, since
3748  * postmaster error messages may not have one.
3749  */
3750  if (conn->errorMessage.len <= 0 ||
3751  conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
3753  PQclear(res);
3754  goto error_return;
3755  }
3756 
3757  /* Almost there now ... */
3759  goto keep_going;
3760  }
3761 
3763  {
3764  /*
3765  * If a read-write, read-only, primary, or standby connection
3766  * is required, see if we have one.
3767  */
3770  {
3771  bool read_only_server;
3772 
3773  /*
3774  * If the server didn't report
3775  * "default_transaction_read_only" or "in_hot_standby" at
3776  * startup, we must determine its state by sending the
3777  * query "SHOW transaction_read_only". This GUC exists in
3778  * all server versions that support 3.0 protocol.
3779  */
3782  {
3783  /*
3784  * We use PQsendQueryContinue so that
3785  * conn->errorMessage does not get cleared. We need
3786  * to preserve any error messages related to previous
3787  * hosts we have tried and failed to connect to.
3788  */
3791  "SHOW transaction_read_only"))
3792  goto error_return;
3793  /* We'll return to this state when we have the answer */
3795  return PGRES_POLLING_READING;
3796  }
3797 
3798  /* OK, we can make the test */
3799  read_only_server =
3802 
3804  read_only_server : !read_only_server)
3805  {
3806  /* Wrong server state, reject and try the next host */
3808  libpq_append_conn_error(conn, "session is read-only");
3809  else
3810  libpq_append_conn_error(conn, "session is not read-only");
3811 
3812  /* Close connection politely. */
3815 
3816  /*
3817  * Try next host if any, but we don't want to consider
3818  * additional addresses for this host.
3819  */
3820  conn->try_next_host = true;
3821  goto keep_going;
3822  }
3823  }
3827  {
3828  /*
3829  * If the server didn't report "in_hot_standby" at
3830  * startup, we must determine its state by sending the
3831  * query "SELECT pg_catalog.pg_is_in_recovery()". Servers
3832  * before 9.0 don't have that function, but by the same
3833  * token they don't have any standby mode, so we may just
3834  * assume the result.
3835  */
3836  if (conn->sversion < 90000)
3838 
3840  {
3841  /*
3842  * We use PQsendQueryContinue so that
3843  * conn->errorMessage does not get cleared. We need
3844  * to preserve any error messages related to previous
3845  * hosts we have tried and failed to connect to.
3846  */
3849  "SELECT pg_catalog.pg_is_in_recovery()"))
3850  goto error_return;
3851  /* We'll return to this state when we have the answer */
3853  return PGRES_POLLING_READING;
3854  }
3855 
3856  /* OK, we can make the test */
3860  {
3861  /* Wrong server state, reject and try the next host */
3863  libpq_append_conn_error(conn, "server is in hot standby mode");
3864  else
3865  libpq_append_conn_error(conn, "server is not in hot standby mode");
3866 
3867  /* Close connection politely. */
3870 
3871  /*
3872  * Try next host if any, but we don't want to consider
3873  * additional addresses for this host.
3874  */
3875  conn->try_next_host = true;
3876  goto keep_going;
3877  }
3878  }
3879 
3880  /* We can release the address list now. */
3882 
3883  /*
3884  * Contents of conn->errorMessage are no longer interesting
3885  * (and it seems some clients expect it to be empty after a
3886  * successful connection).
3887  */
3889 
3890  /* We are open for business! */
3892  return PGRES_POLLING_OK;
3893  }
3894 
3895  case CONNECTION_CONSUME:
3896  {
3897  /*
3898  * This state just makes sure the connection is idle after
3899  * we've obtained the result of a SHOW or SELECT query. Once
3900  * we're clear, return to CONNECTION_CHECK_TARGET state to
3901  * decide what to do next. We must transiently set status =
3902  * CONNECTION_OK in order to use the result-consuming
3903  * subroutines.
3904  */
3906  if (!PQconsumeInput(conn))
3907  goto error_return;
3908 
3909  if (PQisBusy(conn))
3910  {
3912  return PGRES_POLLING_READING;
3913  }
3914 
3915  /* Call PQgetResult() again until we get a NULL result */
3916  res = PQgetResult(conn);
3917  if (res != NULL)
3918  {
3919  PQclear(res);
3921  return PGRES_POLLING_READING;
3922  }
3923 
3925  goto keep_going;
3926  }
3927 
3929  {
3930  /*
3931  * Waiting for result of "SHOW transaction_read_only". We
3932  * must transiently set status = CONNECTION_OK in order to use
3933  * the result-consuming subroutines.
3934  */
3936  if (!PQconsumeInput(conn))
3937  goto error_return;
3938 
3939  if (PQisBusy(conn))
3940  {
3942  return PGRES_POLLING_READING;
3943  }
3944 
3945  res = PQgetResult(conn);
3946  if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
3947  PQntuples(res) == 1)
3948  {
3949  char *val = PQgetvalue(res, 0, 0);
3950 
3951  /*
3952  * "transaction_read_only = on" proves that at least one
3953  * of default_transaction_read_only and in_hot_standby is
3954  * on, but we don't actually know which. We don't care
3955  * though for the purpose of identifying a read-only
3956  * session, so satisfy the CONNECTION_CHECK_TARGET code by
3957  * claiming they are both on. On the other hand, if it's
3958  * a read-write session, they are certainly both off.
3959  */
3960  if (strncmp(val, "on", 2) == 0)
3961  {
3964  }
3965  else
3966  {
3969  }
3970  PQclear(res);
3971 
3972  /* Finish reading messages before continuing */
3974  goto keep_going;
3975  }
3976 
3977  /* Something went wrong with "SHOW transaction_read_only". */
3978  PQclear(res);
3979 
3980  /* Append error report to conn->errorMessage. */
3981  libpq_append_conn_error(conn, "\"%s\" failed",
3982  "SHOW transaction_read_only");
3983 
3984  /* Close connection politely. */
3987 
3988  /* Try next host. */
3989  conn->try_next_host = true;
3990  goto keep_going;
3991  }
3992 
3994  {
3995  /*
3996  * Waiting for result of "SELECT pg_is_in_recovery()". We
3997  * must transiently set status = CONNECTION_OK in order to use
3998  * the result-consuming subroutines.
3999  */
4001  if (!PQconsumeInput(conn))
4002  goto error_return;
4003 
4004  if (PQisBusy(conn))
4005  {
4007  return PGRES_POLLING_READING;
4008  }
4009 
4010  res = PQgetResult(conn);
4011  if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
4012  PQntuples(res) == 1)
4013  {
4014  char *val = PQgetvalue(res, 0, 0);
4015 
4016  if (strncmp(val, "t", 1) == 0)
4018  else
4020  PQclear(res);
4021 
4022  /* Finish reading messages before continuing */
4024  goto keep_going;
4025  }
4026 
4027  /* Something went wrong with "SELECT pg_is_in_recovery()". */
4028  PQclear(res);
4029 
4030  /* Append error report to conn->errorMessage. */
4031  libpq_append_conn_error(conn, "\"%s\" failed",
4032  "SELECT pg_is_in_recovery()");
4033 
4034  /* Close connection politely. */
4037 
4038  /* Try next host. */
4039  conn->try_next_host = true;
4040  goto keep_going;
4041  }
4042 
4043  default:
4045  "invalid connection state %d, probably indicative of memory corruption",
4046  conn->status);
4047  goto error_return;
4048  }
4049 
4050  /* Unreachable */
4051 
4052 error_return:
4053 
4054  /*
4055  * We used to close the socket at this point, but that makes it awkward
4056  * for those above us if they wish to remove this socket from their own
4057  * records (an fd_set for example). We'll just have this socket closed
4058  * when PQfinish is called (which is compulsory even after an error, since
4059  * the connection structure must be freed).
4060  */
4062  return PGRES_POLLING_FAILED;
4063 }
#define STATUS_OK
Definition: c.h:1159
#define MemSet(start, val, len)
Definition: c.h:1004
void err(int eval, const char *fmt,...)
Definition: err.c:43
int pg_fe_sendauth(AuthRequest areq, int payloadlen, PGconn *conn)
Definition: fe-auth.c:952
char * pg_fe_getusername(uid_t user_id, PQExpBuffer errorMessage)
Definition: fe-auth.c:1160
#define MAX_ERRLEN
void pqDropConnection(PGconn *conn, bool flushInput)
Definition: fe-connect.c:456
static const PQEnvironmentOption EnvironmentOptions[]
Definition: fe-connect.c:359
static void sendTerminateConn(PGconn *conn)
Definition: fe-connect.c:4341
static int setKeepalivesCount(PGconn *conn)
Definition: fe-connect.c:2086
static int useKeepalives(PGconn *conn)
Definition: fe-connect.c:1953
static void connectFailureMessage(PGconn *conn, int errorno)
Definition: fe-connect.c:1933
static void release_conn_addrinfo(PGconn *conn)
Definition: fe-connect.c:4326
#define ERRCODE_APPNAME_UNKNOWN
Definition: fe-connect.c:88
static int setKeepalivesInterval(PGconn *conn)
Definition: fe-connect.c:2051
static int setKeepalivesIdle(PGconn *conn)
Definition: fe-connect.c:2017
static void pgpassfileWarning(PGconn *conn)
Definition: fe-connect.c:7415
static bool parse_int_param(const char *value, int *result, PGconn *conn, const char *context)
Definition: fe-connect.c:1972
static void emitHostIdentityInfo(PGconn *conn, const char *host_addr)
Definition: fe-connect.c:1877
static int setTCPUserTimeout(PGconn *conn)
Definition: fe-connect.c:2183
static void pqDropServerData(PGconn *conn)
Definition: fe-connect.c:569
static int connectNoDelay(PGconn *conn)
Definition: fe-connect.c:1818
static void getHostaddr(PGconn *conn, char *host_addr, int host_addr_len)
Definition: fe-connect.c:1844
#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:4882
int PQsendQueryContinue(PGconn *conn, const char *query)
Definition: fe-exec.c:1428
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3314
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1957
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3709
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:776
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2004
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3299
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2035
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:917
@ 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:155
#define NEGOTIATE_SSL_CODE
Definition: pqcomm.h:154
uint32 ProtocolVersion
Definition: pqcomm.h:87
uint32 AuthRequest
Definition: pqcomm.h:128
#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:451
bool try_next_host
Definition: libpq-int.h:473
struct addrinfo * addrlist
Definition: libpq-int.h:474
bool sigpipe_flag
Definition: libpq-int.h:458
int nconnhost
Definition: libpq-int.h:430
pgsocket sock
Definition: libpq-int.h:449
ProtocolVersion pversion
Definition: libpq-int.h:453
int addrlist_family
Definition: libpq-int.h:476
bool send_appname
Definition: libpq-int.h:477
PGTransactionStatusType xactStatus
Definition: libpq-int.h:417
int inCursor
Definition: libpq-int.h:495
PGTernaryBool in_hot_standby
Definition: libpq-int.h:486
int inEnd
Definition: libpq-int.h:496
char * fbappname
Definition: libpq-int.h:368
int inStart
Definition: libpq-int.h:494
char * connip
Definition: libpq-int.h:433
int sversion
Definition: libpq-int.h:454
bool auth_req_received
Definition: libpq-int.h:455
PGTernaryBool default_transaction_read_only
Definition: libpq-int.h:485
bool sigpipe_so
Definition: libpq-int.h:457
char * appname
Definition: libpq-int.h:367
char * sslmode
Definition: libpq-int.h:382
struct addrinfo * addr_cur
Definition: libpq-int.h:475
PQExpBufferData errorMessage
Definition: libpq-int.h:601
char * gssencmode
Definition: libpq-int.h:393
char last_sqlstate[6]
Definition: libpq-int.h:418
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:416
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:422
PGTargetServerType target_server_type
Definition: libpq-int.h:471
SockAddr raddr
Definition: libpq-int.h:452
bool try_next_addr
Definition: libpq-int.h:472
int whichhost
Definition: libpq-int.h:431
char * requirepeer
Definition: libpq-int.h:392
pg_conn_host * connhost
Definition: libpq-int.h:432
bool ssl_in_use
Definition: libpq-int.h:531
ExecStatusType resultStatus
Definition: libpq-int.h:179
#define EWOULDBLOCK
Definition: win32_port.h:382
#define EINPROGRESS
Definition: win32_port.h:388
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, err(), 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(), MAX_ERRLEN, 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(), libpqsrv_connect_internal(), and PQresetPoll().

◆ PQconnectStart()

PGconn* PQconnectStart ( const char *  conninfo)

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

848 {
849  PGconn *conn;
850 
851  /*
852  * Allocate memory for the conn structure. Note that we also expect this
853  * to initialize conn->errorMessage to empty. All subsequent steps during
854  * connection initialization will only append to that buffer.
855  */
856  conn = makeEmptyPGconn();
857  if (conn == NULL)
858  return NULL;
859 
860  /*
861  * Parse the conninfo string
862  */
863  if (!connectOptions1(conn, conninfo))
864  return conn;
865 
866  /*
867  * Compute derived options
868  */
869  if (!connectOptions2(conn))
870  return conn;
871 
872  /*
873  * Connect to the database
874  */
875  if (!connectDBStart(conn))
876  {
877  /* Just in case we failed to set it in connectDBStart */
879  }
880 
881  return conn;
882 }
static bool connectOptions1(PGconn *conn, const char *conninfo)
Definition: fe-connect.c:933
static bool connectOptions2(PGconn *conn)
Definition: fe-connect.c:1031
static PGconn * makeEmptyPGconn(void)
Definition: fe-connect.c:4137
static int connectDBStart(PGconn *conn)
Definition: fe-connect.c:2222

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

Referenced by libpqsrv_connect(), PQconnectdb(), and PQping().

◆ PQconnectStartParams()

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

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

769 {
770  PGconn *conn;
771  PQconninfoOption *connOptions;
772 
773  /*
774  * Allocate memory for the conn structure. Note that we also expect this
775  * to initialize conn->errorMessage to empty. All subsequent steps during
776  * connection initialization will only append to that buffer.
777  */
778  conn = makeEmptyPGconn();
779  if (conn == NULL)
780  return NULL;
781 
782  /*
783  * Parse the conninfo arrays
784  */
785  connOptions = conninfo_array_parse(keywords, values,
786  &conn->errorMessage,
787  true, expand_dbname);
788  if (connOptions == NULL)
789  {
791  /* errorMessage is already set */
792  return conn;
793  }
794 
795  /*
796  * Move option values into conn structure
797  */
798  if (!fillPGconn(conn, connOptions))
799  {
800  PQconninfoFree(connOptions);
801  return conn;
802  }
803 
804  /*
805  * Free the option info - all is in conn now
806  */
807  PQconninfoFree(connOptions);
808 
809  /*
810  * Compute derived options
811  */
812  if (!connectOptions2(conn))
813  return conn;
814 
815  /*
816  * Connect to the database
817  */
818  if (!connectDBStart(conn))
819  {
820  /* Just in case we failed to set it in connectDBStart */
822  }
823 
824  return conn;
825 }
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:5925
static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
Definition: fe-connect.c:893

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

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

◆ PQconninfo()

PQconninfoOption* PQconninfo ( PGconn conn)

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

6810 {
6811  PQExpBufferData errorBuf;
6812  PQconninfoOption *connOptions;
6813 
6814  if (conn == NULL)
6815  return NULL;
6816 
6817  /*
6818  * We don't actually report any errors here, but callees want a buffer,
6819  * and we prefer not to trash the conn's errorMessage.
6820  */
6821  initPQExpBuffer(&errorBuf);
6822  if (PQExpBufferDataBroken(errorBuf))
6823  return NULL; /* out of memory already :-( */
6824 
6825  connOptions = conninfo_init(&errorBuf);
6826 
6827  if (connOptions != NULL)
6828  {
6830 
6831  for (option = PQconninfoOptions; option->keyword; option++)
6832  {
6833  char **connmember;
6834 
6835  if (option->connofs < 0)
6836  continue;
6837 
6838  connmember = (char **) ((char *) conn + option->connofs);
6839 
6840  if (*connmember)
6841  conninfo_storeval(connOptions, option->keyword, *connmember,
6842  &errorBuf, true, false);
6843  }
6844  }
6845 
6846  termPQExpBuffer(&errorBuf);
6847 
6848  return connOptions;
6849 }
static PQconninfoOption * conninfo_storeval(PQconninfoOption *connOptions, const char *keyword, const char *value, PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode)
Definition: fe-connect.c:6727
static const internalPQconninfoOption PQconninfoOptions[]
Definition: fe-connect.c:190

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 6853 of file fe-connect.c.

6854 {
6855  if (connOptions == NULL)
6856  return;
6857 
6858  for (PQconninfoOption *option = connOptions; option->keyword != NULL; option++)
6859  free(option->val);
6860  free(connOptions);
6861 }
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 5634 of file fe-connect.c.

5635 {
5636  PQExpBufferData errorBuf;
5637  PQconninfoOption *connOptions;
5638 
5639  if (errmsg)
5640  *errmsg = NULL; /* default */
5641  initPQExpBuffer(&errorBuf);
5642  if (PQExpBufferDataBroken(errorBuf))
5643  return NULL; /* out of memory already :-( */
5644  connOptions = parse_connection_string(conninfo, &errorBuf, false);
5645  if (connOptions == NULL && errmsg)
5646  *errmsg = errorBuf.data;
5647  else
5648  termPQExpBuffer(&errorBuf);
5649  return connOptions;
5650 }
int errmsg(const char *fmt,...)
Definition: elog.c:1069
static PQconninfoOption * parse_connection_string(const char *connstr, PQExpBuffer errorMessage, bool use_defaults)
Definition: fe-connect.c:5695

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 1957 of file fe-exec.c.

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

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 1942 of file fe-secure-openssl.c.

1943 {
1944  if (conn && conn->sslpassword)
1945  {
1946  if (strlen(conn->sslpassword) + 1 > size)
1947  fprintf(stderr, libpq_gettext("WARNING: sslpassword truncated\n"));
1948  strncpy(buf, conn->sslpassword, size);
1949  buf[size - 1] = '\0';
1950  return strlen(buf);
1951  }
1952  else
1953  {
1954  buf[0] = '\0';
1955  return 0;
1956  }
1957 }
#define libpq_gettext(x)
Definition: libpq-int.h:895
#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 2441 of file fe-exec.c.

2442 {
2443  if (!PQexecStart(conn))
2444  return NULL;
2445  if (!PQsendDescribe(conn, 'P', portal))
2446  return NULL;
2447  return PQexecFinish(conn);
2448 }
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2377
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2311
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2486

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

◆ PQdescribePrepared()

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

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

2423 {
2424  if (!PQexecStart(conn))
2425  return NULL;
2426  if (!PQsendDescribe(conn, 'S', stmt))
2427  return NULL;
2428  return PQexecFinish(conn);
2429 }
#define stmt
Definition: indent_codes.h:59

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

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:3720
char * PQfname(const PGresult *res, int field_num)
Definition: fe-exec.c:3400
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3322
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 1235 of file fe-auth.c.

1236 {
1237  char *crypt_pwd;
1238  const char *errstr = NULL;
1239 
1240  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1241  if (!crypt_pwd)
1242  return NULL;
1243 
1244  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd, &errstr))
1245  {
1246  free(crypt_pwd);
1247  return NULL;
1248  }
1249 
1250  return crypt_pwd;
1251 }
#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 1278 of file fe-auth.c.

1280 {
1281 #define MAX_ALGORITHM_NAME_LEN 50
1282  char algobuf[MAX_ALGORITHM_NAME_LEN + 1];
1283  char *crypt_pwd = NULL;
1284 
1285  if (!conn)
1286  return NULL;
1287 
1289 
1290  /* If no algorithm was given, ask the server. */
1291  if (algorithm == NULL)
1292  {
1293  PGresult *res;
1294  char *val;
1295 
1296  res = PQexec(conn, "show password_encryption");
1297  if (res == NULL)
1298  {
1299  /* PQexec() should've set conn->errorMessage already */
1300  return NULL;
1301  }
1303  {
1304  /* PQexec() should've set conn->errorMessage already */
1305  PQclear(res);
1306  return NULL;
1307  }
1308  if (PQntuples(res) != 1 || PQnfields(res) != 1)
1309  {
1310  PQclear(res);
1311  libpq_append_conn_error(conn, "unexpected shape of result set returned for SHOW");
1312  return NULL;
1313  }
1314  val = PQgetvalue(res, 0, 0);
1315 
1316  if (strlen(val) > MAX_ALGORITHM_NAME_LEN)
1317  {
1318  PQclear(res);
1319  libpq_append_conn_error(conn, "password_encryption value too long");
1320  return NULL;
1321  }
1322  strcpy(algobuf, val);
1323  PQclear(res);
1324 
1325  algorithm = algobuf;
1326  }
1327 
1328  /*
1329  * Also accept "on" and "off" as aliases for "md5", because
1330  * password_encryption was a boolean before PostgreSQL 10. We refuse to
1331  * send the password in plaintext even if it was "off".
1332  */
1333  if (strcmp(algorithm, "on") == 0 ||
1334  strcmp(algorithm, "off") == 0)
1335  algorithm = "md5";
1336 
1337  /*
1338  * Ok, now we know what algorithm to use
1339  */
1340  if (strcmp(algorithm, "scram-sha-256") == 0)
1341  {
1342  const char *errstr = NULL;
1343 
1344  crypt_pwd = pg_fe_scram_build_secret(passwd,
1346  &errstr);
1347  if (!crypt_pwd)
1348  libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
1349  }
1350  else if (strcmp(algorithm, "md5") == 0)
1351  {
1352  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1353  if (crypt_pwd)
1354  {
1355  const char *errstr = NULL;
1356 
1357  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd, &errstr))
1358  {
1359  libpq_append_conn_error(conn, "could not encrypt password: %s", errstr);
1360  free(crypt_pwd);
1361  crypt_pwd = NULL;
1362  }
1363  }
1364  else
1365  libpq_append_conn_error(conn, "out of memory");
1366  }
1367  else
1368  {
1369  libpq_append_conn_error(conn, "unrecognized password encryption algorithm \"%s\"",
1370  algorithm);
1371  return NULL;
1372  }
1373 
1374  return crypt_pwd;
1375 }
char * pg_fe_scram_build_secret(const char *password, int iterations, const char **errstr)
#define MAX_ALGORITHM_NAME_LEN
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2229
int scram_sha_256_iterations
Definition: libpq-int.h:528

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, pg_conn::scram_sha_256_iterations, user, and val.

Referenced by exec_command_password(), and main().

◆ PQendcopy()

int PQendcopy ( PGconn conn)

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

2836 {
2837  if (!conn)
2838  return 0;
2839 
2840  return pqEndcopy3(conn);
2841 }
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 2928 of file fe-exec.c.

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

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 7020 of file fe-connect.c.

7021 {
7022  if (!conn)
7023  return libpq_gettext("connection pointer is NULL\n");
7024 
7025  /*
7026  * The errorMessage buffer might be marked "broken" due to having
7027  * previously failed to allocate enough memory for the message. In that
7028  * case, tell the application we ran out of memory.
7029  */
7030  if (PQExpBufferBroken(&conn->