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 *string, 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 *ps)
 
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:2911
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3265
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:856
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::@170 u
Oid fn_lo_close
Definition: libpq-int.h:271
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:476

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

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

◆ lo_creat()

Oid lo_creat ( PGconn conn,
int  mode 
)

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

445 {
446  PQArgBlock argv[1];
447  PGresult *res;
448  int retval;
449  int result_len;
450 
451  if (lo_initialize(conn) < 0)
452  return InvalidOid;
453 
454  argv[0].isint = 1;
455  argv[0].len = 4;
456  argv[0].u.integer = mode;
458  &retval, &result_len, 1, argv, 1);
460  {
461  PQclear(res);
462  return (Oid) retval;
463  }
464  else
465  {
466  PQclear(res);
467  return InvalidOid;
468  }
469 }
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:272

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 480 of file fe-lobj.c.

481 {
482  PQArgBlock argv[1];
483  PGresult *res;
484  int retval;
485  int result_len;
486 
487  if (lo_initialize(conn) < 0)
488  return InvalidOid;
489 
490  /* Must check this on-the-fly because it's not there pre-8.1 */
491  if (conn->lobjfuncs->fn_lo_create == 0)
492  {
494  libpq_gettext("cannot determine OID of function %s\n"),
495  "lo_create");
496  return InvalidOid;
497  }
498 
499  argv[0].isint = 1;
500  argv[0].len = 4;
501  argv[0].u.integer = lobjId;
503  &retval, &result_len, 1, argv, 1);
505  {
506  PQclear(res);
507  return (Oid) retval;
508  }
509  else
510  {
511  PQclear(res);
512  return InvalidOid;
513  }
514 }
#define libpq_gettext(x)
Definition: libpq-int.h:878
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
Oid fn_lo_create
Definition: libpq-int.h:273
PQExpBufferData errorMessage
Definition: libpq-int.h:585

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

Referenced by lo_import_internal(), and StartRestoreBlob().

◆ lo_export()

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

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

759 {
760  int result = 1;
761  int fd;
762  int nbytes,
763  tmp;
764  char buf[LO_BUFSIZE];
765  int lobj;
766  char sebuf[PG_STRERROR_R_BUFLEN];
767 
768  /*
769  * open the large object.
770  */
771  lobj = lo_open(conn, lobjId, INV_READ);
772  if (lobj == -1)
773  {
774  /* we assume lo_open() already set a suitable error message */
775  return -1;
776  }
777 
778  /*
779  * create the file to be written to
780  */
781  fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC | PG_BINARY, 0666);
782  if (fd < 0)
783  {
784  /* We must do lo_close before setting the errorMessage */
785  int save_errno = errno;
786 
787  (void) lo_close(conn, lobj);
788  /* deliberately overwrite any error from lo_close */
791  libpq_gettext("could not open file \"%s\": %s\n"),
792  filename,
793  strerror_r(save_errno, sebuf, sizeof(sebuf)));
794  return -1;
795  }
796 
797  /*
798  * read in from the large object and write to the file
799  */
800  while ((nbytes = lo_read(conn, lobj, buf, LO_BUFSIZE)) > 0)
801  {
802  tmp = write(fd, buf, nbytes);
803  if (tmp != nbytes)
804  {
805  /* We must do lo_close before setting the errorMessage */
806  int save_errno = errno;
807 
808  (void) lo_close(conn, lobj);
809  (void) close(fd);
810  /* deliberately overwrite any error from lo_close */
813  libpq_gettext("could not write to file \"%s\": %s\n"),
814  filename,
815  strerror_r(save_errno, sebuf, sizeof(sebuf)));
816  return -1;
817  }
818  }
819 
820  /*
821  * If lo_read() failed, we are now in an aborted transaction so there's no
822  * need for lo_close(); furthermore, if we tried it we'd overwrite the
823  * useful error result with a useless one. So skip lo_close() if we got a
824  * failure result.
825  */
826  if (nbytes < 0 ||
827  lo_close(conn, lobj) != 0)
828  {
829  /* assume lo_read() or lo_close() left a suitable error message */
830  result = -1;
831  }
832 
833  /* if we already failed, don't overwrite that msg with a close error */
834  if (close(fd) != 0 && result >= 0)
835  {
837  libpq_gettext("could not write to file \"%s\": %s\n"),
838  filename, strerror_r(errno, sebuf, sizeof(sebuf)));
839  result = -1;
840  }
841 
842  return result;
843 }
#define PG_BINARY
Definition: c.h:1279
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:248
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:851
static char * filename
Definition: pg_dumpall.c:94
static char * buf
Definition: pg_test_fsync.c:67
#define PG_STRERROR_R_BUFLEN
Definition: port.h:243
#define strerror_r
Definition: port.h:242

References appendPQExpBuffer(), buf, close, conn, pg_conn::errorMessage, fd(), filename, INV_READ, libpq_gettext, 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 634 of file fe-lobj.c.

635 {
637 }
static Oid lo_import_internal(PGconn *conn, const char *filename, Oid oid)
Definition: fe-lobj.c:655

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 649 of file fe-lobj.c.

650 {
651  return lo_import_internal(conn, filename, lobjId);
652 }

References conn, filename, and lo_import_internal().

◆ lo_lseek()

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

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

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

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 390 of file fe-lobj.c.

391 {
392  PQArgBlock argv[3];
393  PGresult *res;
394  pg_int64 retval;
395  int result_len;
396 
397  if (lo_initialize(conn) < 0)
398  return -1;
399 
400  if (conn->lobjfuncs->fn_lo_lseek64 == 0)
401  {
403  libpq_gettext("cannot determine OID of function %s\n"),
404  "lo_lseek64");
405  return -1;
406  }
407 
408  argv[0].isint = 1;
409  argv[0].len = 4;
410  argv[0].u.integer = fd;
411 
412  offset = lo_hton64(offset);
413  argv[1].isint = 0;
414  argv[1].len = 8;
415  argv[1].u.ptr = (int *) &offset;
416 
417  argv[2].isint = 1;
418  argv[2].len = 4;
419  argv[2].u.integer = whence;
420 
422  (void *) &retval, &result_len, 0, argv, 3);
423  if (PQresultStatus(res) == PGRES_COMMAND_OK && result_len == 8)
424  {
425  PQclear(res);
426  return lo_ntoh64(retval);
427  }
428  else
429  {
430  PQclear(res);
431  return -1;
432  }
433 }
static pg_int64 lo_ntoh64(pg_int64 net64)
Definition: fe-lobj.c:1071
static pg_int64 lo_hton64(pg_int64 host64)
Definition: fe-lobj.c:1046
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:276

References appendPQExpBuffer(), conn, pg_conn::errorMessage, fd(), pgLobjfuncs::fn_lo_lseek64, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, libpq_gettext, 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:270

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

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

◆ lo_read()

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

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

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

References appendPQExpBufferStr(), buf, conn, pg_conn::errorMessage, fd(), pgLobjfuncs::fn_lo_read, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, len, libpq_gettext, 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 522 of file fe-lobj.c.

523 {
524  int retval;
525  PQArgBlock argv[1];
526  PGresult *res;
527  int result_len;
528 
529  if (lo_initialize(conn) < 0)
530  return -1;
531 
532  argv[0].isint = 1;
533  argv[0].len = 4;
534  argv[0].u.integer = fd;
535 
537  &retval, &result_len, 1, argv, 1);
539  {
540  PQclear(res);
541  return retval;
542  }
543  else
544  {
545  PQclear(res);
546  return -1;
547  }
548 }
Oid fn_lo_tell
Definition: libpq-int.h:277

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 555 of file fe-lobj.c.

556 {
557  pg_int64 retval;
558  PQArgBlock argv[1];
559  PGresult *res;
560  int result_len;
561 
562  if (lo_initialize(conn) < 0)
563  return -1;
564 
565  if (conn->lobjfuncs->fn_lo_tell64 == 0)
566  {
568  libpq_gettext("cannot determine OID of function %s\n"),
569  "lo_tell64");
570  return -1;
571  }
572 
573  argv[0].isint = 1;
574  argv[0].len = 4;
575  argv[0].u.integer = fd;
576 
578  (void *) &retval, &result_len, 0, argv, 1);
579  if (PQresultStatus(res) == PGRES_COMMAND_OK && result_len == 8)
580  {
581  PQclear(res);
582  return lo_ntoh64(retval);
583  }
584  else
585  {
586  PQclear(res);
587  return -1;
588  }
589 }
Oid fn_lo_tell64
Definition: libpq-int.h:278

References appendPQExpBuffer(), conn, pg_conn::errorMessage, fd(), pgLobjfuncs::fn_lo_tell64, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, libpq_gettext, 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  {
145  libpq_gettext("cannot determine OID of function %s\n"),
146  "lo_truncate");
147  return -1;
148  }
149 
150  /*
151  * Long ago, somebody thought it'd be a good idea to declare this function
152  * as taking size_t ... but the underlying backend function only accepts a
153  * signed int32 length. So throw error if the given value overflows
154  * int32. (A possible alternative is to automatically redirect the call
155  * to lo_truncate64; but if the caller wanted to rely on that backend
156  * function being available, he could have called lo_truncate64 for
157  * himself.)
158  */
159  if (len > (size_t) INT_MAX)
160  {
162  libpq_gettext("argument of lo_truncate exceeds integer range\n"));
163  return -1;
164  }
165 
166  argv[0].isint = 1;
167  argv[0].len = 4;
168  argv[0].u.integer = fd;
169 
170  argv[1].isint = 1;
171  argv[1].len = 4;
172  argv[1].u.integer = (int) len;
173 
175  &retval, &result_len, 1, argv, 2);
176 
178  {
179  PQclear(res);
180  return retval;
181  }
182  else
183  {
184  PQclear(res);
185  return -1;
186  }
187 }
Oid fn_lo_truncate
Definition: libpq-int.h:279

References appendPQExpBuffer(), appendPQExpBufferStr(), conn, pg_conn::errorMessage, fd(), pgLobjfuncs::fn_lo_truncate, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, len, libpq_gettext, 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 197 of file fe-lobj.c.

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

References appendPQExpBuffer(), conn, pg_conn::errorMessage, fd(), pgLobjfuncs::fn_lo_truncate64, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, len, libpq_gettext, 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 597 of file fe-lobj.c.

598 {
599  PQArgBlock argv[1];
600  PGresult *res;
601  int result_len;
602  int retval;
603 
604  if (lo_initialize(conn) < 0)
605  return -1;
606 
607  argv[0].isint = 1;
608  argv[0].len = 4;
609  argv[0].u.integer = lobjId;
610 
612  &retval, &result_len, 1, argv, 1);
614  {
615  PQclear(res);
616  return retval;
617  }
618  else
619  {
620  PQclear(res);
621  return -1;
622  }
623 }
Oid fn_lo_unlink
Definition: libpq-int.h:274

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 299 of file fe-lobj.c.

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

References appendPQExpBufferStr(), buf, conn, pg_conn::errorMessage, fd(), pgLobjfuncs::fn_lo_write, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, len, libpq_gettext, 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:745
static const pg_encname pg_encname_tbl[]
Definition: encnames.c:39
static char * clean_encoding_name(const char *key, char *newkey)
Definition: encnames.c:525
const char * name
Definition: encode.c:561
#define NAMEDATALEN

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

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

◆ pg_encoding_to_char()

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:279

References encoding, and PG_VALID_BE_ENCODING.

Referenced by setup_locale_encoding().

◆ PQbackendPID()

int PQbackendPID ( const PGconn conn)

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

6870 {
6871  if (!conn || conn->status != CONNECTION_OK)
6872  return 0;
6873  return conn->be_pid;
6874 }
int be_pid
Definition: libpq-int.h:467
ConnStatusType status
Definition: libpq-int.h:410

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

3352 {
3353  if (!res)
3354  return 0;
3355  return res->binary;
3356 }
int binary
Definition: libpq-int.h:180

References pg_result::binary, and res.

Referenced by HandleCopyResult().

◆ PQcancel()

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

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

4418 {
4419  int save_errno = SOCK_ERRNO;
4420  pgsocket tmpsock = PGINVALID_SOCKET;
4421  int maxlen;
4422  struct
4423  {
4424  uint32 packetlen;
4426  } crp;
4427 
4428  if (!cancel)
4429  {
4430  strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
4431  /* strlcpy probably doesn't change errno, but be paranoid */
4432  SOCK_ERRNO_SET(save_errno);
4433  return false;
4434  }
4435 
4436  /*
4437  * We need to open a temporary connection to the postmaster. Do this with
4438  * only kernel calls.
4439  */
4440  if ((tmpsock = socket(cancel->raddr.addr.ss_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
4441  {
4442  strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
4443  goto cancel_errReturn;
4444  }
4445 
4446  /*
4447  * Since this connection will only be used to send a single packet of
4448  * data, we don't need NODELAY. We also don't set the socket to
4449  * nonblocking mode, because the API definition of PQcancel requires the
4450  * cancel to be sent in a blocking way.
4451  *
4452  * We do set socket options related to keepalives and other TCP timeouts.
4453  * This ensures that this function does not block indefinitely when
4454  * reasonable keepalive and timeout settings have been provided.
4455  */
4456  if (cancel->raddr.addr.ss_family != AF_UNIX &&
4457  cancel->keepalives != 0)
4458  {
4459 #ifndef WIN32
4460  if (!optional_setsockopt(tmpsock, SOL_SOCKET, SO_KEEPALIVE, 1))
4461  {
4462  strlcpy(errbuf, "PQcancel() -- setsockopt(SO_KEEPALIVE) failed: ", errbufsize);
4463  goto cancel_errReturn;
4464  }
4465 
4466 #ifdef PG_TCP_KEEPALIVE_IDLE
4467  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
4468  cancel->keepalives_idle))
4469  {
4470  strlcpy(errbuf, "PQcancel() -- setsockopt(" PG_TCP_KEEPALIVE_IDLE_STR ") failed: ", errbufsize);
4471  goto cancel_errReturn;
4472  }
4473 #endif
4474 
4475 #ifdef TCP_KEEPINTVL
4476  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_KEEPINTVL,
4477  cancel->keepalives_interval))
4478  {
4479  strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_KEEPINTVL) failed: ", errbufsize);
4480  goto cancel_errReturn;
4481  }
4482 #endif
4483 
4484 #ifdef TCP_KEEPCNT
4485  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_KEEPCNT,
4486  cancel->keepalives_count))
4487  {
4488  strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_KEEPCNT) failed: ", errbufsize);
4489  goto cancel_errReturn;
4490  }
4491 #endif
4492 
4493 #else /* WIN32 */
4494 
4495 #ifdef SIO_KEEPALIVE_VALS
4496  if (!setKeepalivesWin32(tmpsock,
4497  cancel->keepalives_idle,
4498  cancel->keepalives_interval))
4499  {
4500  strlcpy(errbuf, "PQcancel() -- WSAIoctl(SIO_KEEPALIVE_VALS) failed: ", errbufsize);
4501  goto cancel_errReturn;
4502  }
4503 #endif /* SIO_KEEPALIVE_VALS */
4504 #endif /* WIN32 */
4505 
4506  /* TCP_USER_TIMEOUT works the same way on Unix and Windows */
4507 #ifdef TCP_USER_TIMEOUT
4508  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_USER_TIMEOUT,
4509  cancel->pgtcp_user_timeout))
4510  {
4511  strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_USER_TIMEOUT) failed: ", errbufsize);
4512  goto cancel_errReturn;
4513  }
4514 #endif
4515  }
4516 
4517 retry3:
4518  if (connect(tmpsock, (struct sockaddr *) &cancel->raddr.addr,
4519  cancel->raddr.salen) < 0)
4520  {
4521  if (SOCK_ERRNO == EINTR)
4522  /* Interrupted system call - we'll just try again */
4523  goto retry3;
4524  strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
4525  goto cancel_errReturn;
4526  }
4527 
4528  /* Create and send the cancel request packet. */
4529 
4530  crp.packetlen = pg_hton32((uint32) sizeof(crp));
4531  crp.cp.cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE);
4532  crp.cp.backendPID = pg_hton32(cancel->be_pid);
4533  crp.cp.cancelAuthCode = pg_hton32(cancel->be_key);
4534 
4535 retry4:
4536  if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
4537  {
4538  if (SOCK_ERRNO == EINTR)
4539  /* Interrupted system call - we'll just try again */
4540  goto retry4;
4541  strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
4542  goto cancel_errReturn;
4543  }
4544 
4545  /*
4546  * Wait for the postmaster to close the connection, which indicates that
4547  * it's processed the request. Without this delay, we might issue another
4548  * command only to find that our cancel zaps that command instead of the
4549  * one we thought we were canceling. Note we don't actually expect this
4550  * read to obtain any data, we are just waiting for EOF to be signaled.
4551  */
4552 retry5:
4553  if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
4554  {
4555  if (SOCK_ERRNO == EINTR)
4556  /* Interrupted system call - we'll just try again */
4557  goto retry5;
4558  /* we ignore other error conditions */
4559  }
4560 
4561  /* All done */
4562  closesocket(tmpsock);
4563  SOCK_ERRNO_SET(save_errno);
4564  return true;
4565 
4566 cancel_errReturn:
4567 
4568  /*
4569  * Make sure we don't overflow the error buffer. Leave space for the \n at
4570  * the end, and for the terminating zero.
4571  */
4572  maxlen = errbufsize - strlen(errbuf) - 2;
4573  if (maxlen >= 0)
4574  {
4575  /*
4576  * We can't invoke strerror here, since it's not signal-safe. Settle
4577  * for printing the decimal value of errno. Even that has to be done
4578  * the hard way.
4579  */
4580  int val = SOCK_ERRNO;
4581  char buf[32];
4582  char *bufp;
4583 
4584  bufp = buf + sizeof(buf) - 1;
4585  *bufp = '\0';
4586  do
4587  {
4588  *(--bufp) = (val % 10) + '0';
4589  val /= 10;
4590  } while (val > 0);
4591  bufp -= 6;
4592  memcpy(bufp, "error ", 6);
4593  strncat(errbuf, bufp, maxlen);
4594  strcat(errbuf, "\n");
4595  }
4596  if (tmpsock != PGINVALID_SOCKET)
4597  closesocket(tmpsock);
4598  SOCK_ERRNO_SET(save_errno);
4599  return false;
4600 }
unsigned int uint32
Definition: c.h:452
static bool optional_setsockopt(int fd, int protoid, int optid, int value)
Definition: fe-connect.c:4385
long val
Definition: informix.c:664
#define SOCK_ERRNO
Definition: libpq-int.h:891
#define SOCK_ERRNO_SET(e)
Definition: libpq-int.h:893
#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:342
#define CANCEL_REQUEST_CODE
Definition: pqcomm.h:176
ProtocolVersion MsgType
Definition: pqcomm.h:127
struct sockaddr_storage addr
Definition: pqcomm.h:64
socklen_t salen
Definition: pqcomm.h:65
int pgtcp_user_timeout
Definition: libpq-int.h:601
int keepalives_interval
Definition: libpq-int.h:604
int keepalives_idle
Definition: libpq-int.h:603
int keepalives_count
Definition: libpq-int.h:606
SockAddr raddr
Definition: libpq-int.h:598
int be_pid
Definition: libpq-int.h:599
int keepalives
Definition: libpq-int.h:602
int be_key
Definition: libpq-int.h:600
#define EINTR
Definition: win32_port.h:351
#define recv(s, buf, len, flags)
Definition: win32_port.h:475
#define send(s, buf, len, flags)
Definition: win32_port.h:476
#define socket(af, type, protocol)
Definition: win32_port.h:469
#define connect(s, name, namelen)
Definition: win32_port.h:473

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:163
char * name
Definition: libpq-int.h:162
PGEventProc proc
Definition: libpq-int.h:161
bool resultInitialized
Definition: libpq-int.h:165
int nEvents
Definition: libpq-int.h:189
PGresAttValue ** tuples
Definition: libpq-int.h:173
PGresAttDesc * attDescs
Definition: libpq-int.h:172
PGMessageField * errFields
Definition: libpq-int.h:198
PGresParamDesc * paramDescs
Definition: libpq-int.h:177
PGEvent * events
Definition: libpq-int.h:188
PGresult_data * curBlock
Definition: libpq-int.h:209
PGresult_data * next
Definition: libpq-int.h:106

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

3607 {
3608  if (!res)
3609  return NULL;
3610  return res->cmdStatus;
3611 }
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:179

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

3677 {
3678  char *p,
3679  *c;
3680 
3681  if (!res)
3682  return "";
3683 
3684  if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3685  {
3686  p = res->cmdStatus + 7;
3687  /* INSERT: skip oid and space */
3688  while (*p && *p != ' ')
3689  p++;
3690  if (*p == 0)
3691  goto interpret_error; /* no space? */
3692  p++;
3693  }
3694  else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3695  strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3696  strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3697  p = res->cmdStatus + 7;
3698  else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0 ||
3699  strncmp(res->cmdStatus, "MERGE ", 6) == 0)
3700  p = res->cmdStatus + 6;
3701  else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3702  strncmp(res->cmdStatus, "COPY ", 5) == 0)
3703  p = res->cmdStatus + 5;
3704  else
3705  return "";
3706 
3707  /* check that we have an integer (at least one digit, nothing else) */
3708  for (c = p; *c; c++)
3709  {
3710  if (!isdigit((unsigned char) *c))
3711  goto interpret_error;
3712  }
3713  if (c == p)
3714  goto interpret_error;
3715 
3716  return p;
3717 
3718 interpret_error:
3720  "could not interpret result from server: %s",
3721  res->cmdStatus);
3722  return "";
3723 }
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:935
char * c
PGNoticeHooks noticeHooks
Definition: libpq-int.h:187

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

1470 {
1471  PQExpBufferData errorBuf;
1472  PQconninfoOption *connOptions;
1473 
1474  /* We don't actually report any errors here, but callees want a buffer */
1475  initPQExpBuffer(&errorBuf);
1476  if (PQExpBufferDataBroken(errorBuf))
1477  return NULL; /* out of memory already :-( */
1478 
1479  connOptions = conninfo_init(&errorBuf);
1480  if (connOptions != NULL)
1481  {
1482  /* pass NULL errorBuf to ignore errors */
1483  if (!conninfo_add_defaults(connOptions, NULL))
1484  {
1485  PQconninfoFree(connOptions);
1486  connOptions = NULL;
1487  }
1488  }
1489 
1490  termPQExpBuffer(&errorBuf);
1491  return connOptions;
1492 }
static PQconninfoOption * conninfo_init(PQExpBuffer errorMessage)
Definition: fe-connect.c:5459
static bool conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
Definition: fe-connect.c:5893
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:6668
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131
#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 710 of file fe-connect.c.

711 {
712  PGconn *conn = PQconnectStart(conninfo);
713 
714  if (conn && conn->status != CONNECTION_BAD)
715  (void) connectDBComplete(conn);
716 
717  return conn;
718 }
PGconn * PQconnectStart(const char *conninfo)
Definition: fe-connect.c:838
static int connectDBComplete(PGconn *conn)
Definition: fe-connect.c:2112

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

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

◆ PQconnectdbParams()

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

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

658 {
659  PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
660 
661  if (conn && conn->status != CONNECTION_BAD)
662  (void) connectDBComplete(conn);
663 
664  return conn;
665 }
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:757

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

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

◆ PQconnectionNeedsPassword()

int PQconnectionNeedsPassword ( const PGconn conn)

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

6887 {
6888  char *password;
6889 
6890  if (!conn)
6891  return false;
6892  password = PQpass(conn);
6893  if (conn->password_needed &&
6894  (password == NULL || password[0] == '\0'))
6895  return true;
6896  else
6897  return false;
6898 }
char * PQpass(const PGconn *conn)
Definition: fe-connect.c:6697
static char * password
Definition: streamutil.c:53
bool password_needed
Definition: libpq-int.h:451

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

6902 {
6903  if (!conn)
6904  return false;
6905  if (conn->password_needed)
6906  return true;
6907  else
6908  return false;
6909 }

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

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

References SockAddr::addr, pg_conn::addr_cur, pg_conn::addrlist, pg_conn::addrlist_family, addrinfo::ai_addr, addrinfo::ai_addrlen, addrinfo::ai_family, addrinfo::ai_flags, addrinfo::ai_next, AI_NUMERICHOST, addrinfo::ai_socktype, appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), pg_conn::appname, Assert(), pg_conn::asyncStatus, AUTH_REQ_OK, pg_conn::auth_req_received, CHT_HOST_ADDRESS, CHT_HOST_NAME, CHT_UNIX_SOCKET, conn, connect, connectFailureMessage(), CONNECTION_AUTH_OK, CONNECTION_AWAITING_RESPONSE, CONNECTION_BAD, CONNECTION_CHECK_STANDBY, CONNECTION_CHECK_TARGET, CONNECTION_CHECK_WRITABLE, CONNECTION_CONSUME, CONNECTION_GSS_STARTUP, CONNECTION_MADE, CONNECTION_NEEDED, CONNECTION_OK, CONNECTION_SSL_STARTUP, CONNECTION_STARTED, connectNoDelay(), pg_conn::connhost, pg_conn::connip, PQExpBufferData::data, pg_conn::default_transaction_read_only, EINPROGRESS, EINTR, emitHostIdentityInfo(), EnvironmentOptions, ERRCODE_APPNAME_UNKNOWN, ERRCODE_CANNOT_CONNECT_NOW, pg_conn::errorMessage, EWOULDBLOCK, pg_conn::fbappname, free, gai_strerror, 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_gettext, MAXPGPATH, MemSet, pg_conn::nconnhost, NEGOTIATE_GSS_CODE, NEGOTIATE_SSL_CODE, NI_MAXHOST, 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(), PQgetResult(), pqGets_append(), PQgetvalue(), PQisBusy(), PQntuples(), pqPacketSend(), pqReadData(), PQresultErrorField(), PQresultStatus(), pqsecure_initialize(), pqsecure_open_client(), pqsecure_open_gss(), PQsendQueryContinue(), PQTRANS_IDLE, pg_conn::pversion, pg_conn::raddr, release_conn_addrinfo(), pg_conn::requirepeer, res, pg_result::resultStatus, SockAddr::salen, pg_conn::send_appname, sendTerminateConn(), SERVER_TYPE_PREFER_STANDBY, SERVER_TYPE_PREFER_STANDBY_PASS2, SERVER_TYPE_PRIMARY, SERVER_TYPE_READ_ONLY, SERVER_TYPE_READ_WRITE, SERVER_TYPE_STANDBY, setKeepalivesCount(), setKeepalivesIdle(), setKeepalivesInterval(), setTCPUserTimeout(), pg_conn::sigpipe_flag, pg_conn::sigpipe_so, snprintf, pg_conn::sock, SOCK_ERRNO, SOCK_STRERROR, socket, pg_conn::ssl_in_use, pg_conn::sslmode, pg_conn::status, STATUS_OK, strerror_r, pg_conn::sversion, pg_conn::target_server_type, pg_conn::try_next_addr, pg_conn::try_next_host, pg_conn_host::type, UNIXSOCK_PATH, UNIXSOCK_PATH_BUFLEN, useKeepalives(), val, pg_conn::whichhost, and pg_conn::xactStatus.

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

◆ PQconnectStart()

PGconn* PQconnectStart ( const char *  conninfo)

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

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

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

Referenced by PQconnectdb(), and PQping().

◆ PQconnectStartParams()

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

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

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

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

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

◆ PQconninfo()

PQconninfoOption* PQconninfo ( PGconn conn)

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

6625 {
6626  PQExpBufferData errorBuf;
6627  PQconninfoOption *connOptions;
6628 
6629  if (conn == NULL)
6630  return NULL;
6631 
6632  /*
6633  * We don't actually report any errors here, but callees want a buffer,
6634  * and we prefer not to trash the conn's errorMessage.
6635  */
6636  initPQExpBuffer(&errorBuf);
6637  if (PQExpBufferDataBroken(errorBuf))
6638  return NULL; /* out of memory already :-( */
6639 
6640  connOptions = conninfo_init(&errorBuf);
6641 
6642  if (connOptions != NULL)
6643  {
6645 
6646  for (option = PQconninfoOptions; option->keyword; option++)
6647  {
6648  char **connmember;
6649 
6650  if (option->connofs < 0)
6651  continue;
6652 
6653  connmember = (char **) ((char *) conn + option->connofs);
6654 
6655  if (*connmember)
6656  conninfo_storeval(connOptions, option->keyword, *connmember,
6657  &errorBuf, true, false);
6658  }
6659  }
6660 
6661  termPQExpBuffer(&errorBuf);
6662 
6663  return connOptions;
6664 }
static PQconninfoOption * conninfo_storeval(PQconninfoOption *connOptions, const char *keyword, const char *value, PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode)
Definition: fe-connect.c:6542
static const internalPQconninfoOption PQconninfoOptions[]
Definition: fe-connect.c:191

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

6669 {
6670  if (connOptions == NULL)
6671  return;
6672 
6673  for (PQconninfoOption *option = connOptions; option->keyword != NULL; option++)
6674  free(option->val);
6675  free(connOptions);
6676 }
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 5437 of file fe-connect.c.

5438 {
5439  PQExpBufferData errorBuf;
5440  PQconninfoOption *connOptions;
5441 
5442  if (errmsg)
5443  *errmsg = NULL; /* default */
5444  initPQExpBuffer(&errorBuf);
5445  if (PQExpBufferDataBroken(errorBuf))
5446  return NULL; /* out of memory already :-( */
5447  connOptions = parse_connection_string(conninfo, &errorBuf, false);
5448  if (connOptions == NULL && errmsg)
5449  *errmsg = errorBuf.data;
5450  else
5451  termPQExpBuffer(&errorBuf);
5452  return connOptions;
5453 }
int errmsg(const char *fmt,...)
Definition: elog.c:904
static PQconninfoOption * parse_connection_string(const char *conninfo, PQExpBuffer errorMessage, bool use_defaults)
Definition: fe-connect.c:5499

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

2001 {
2002  if (!conn)
2003  return 0;
2004 
2005  /*
2006  * for non-blocking connections try to flush the send-queue, otherwise we
2007  * may never get a response for something that may not have already been
2008  * sent because it's in our write buffer!
2009  */
2010  if (pqIsnonblocking(conn))
2011  {
2012  if (pqFlush(conn) < 0)
2013  return 0;
2014  }
2015 
2016  /*
2017  * Load more data, if available. We do this no matter what state we are
2018  * in, since we are probably getting called because the application wants
2019  * to get rid of a read-select condition. Note that we will NOT block
2020  * waiting for more input.
2021  */
2022  if (pqReadData(conn) < 0)
2023  return 0;
2024 
2025  /* Parsing of the data waits till later. */
2026  return 1;
2027 }
#define pqIsnonblocking(conn)
Definition: libpq-int.h:867

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:170
int numAttributes
Definition: libpq-int.h:171
int client_encoding
Definition: libpq-int.h:190
char * value
Definition: libpq-int.h:139

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

1940 {
1941  if (conn->sslpassword)
1942  {
1943  if (strlen(conn->sslpassword) + 1 > size)
1944  fprintf(stderr, libpq_gettext("WARNING: sslpassword truncated\n"));
1945  strncpy(buf, conn->sslpassword, size);
1946  buf[size - 1] = '\0';
1947  return strlen(buf);
1948  }
1949  else
1950  {
1951  buf[0] = '\0';
1952  return 0;
1953  }
1954 }
#define fprintf
Definition: port.h:229
char * sslpassword
Definition: libpq-int.h:383

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

2484 {
2485  if (!PQexecStart(conn))
2486  return NULL;
2487  if (!PQsendDescribe(conn, 'P', portal))
2488  return NULL;
2489  return PQexecFinish(conn);
2490 }
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2419
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2351
static int PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
Definition: fe-exec.c:2528

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

◆ PQdescribePrepared()

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

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

2465 {
2466  if (!PQexecStart(conn))
2467  return NULL;
2468  if (!PQsendDescribe(conn, 'S', stmt))
2469  return NULL;
2470  return PQexecFinish(conn);
2471 }

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

Referenced by DescribeQuery(), and ECPGdescribe().

◆ PQdisplayTuples()

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

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

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

1206 {
1207  return pg_encoding_dsplen(encoding, s);
1208 }
int pg_encoding_dsplen(int encoding, const char *mbstr)
Definition: wchar.c:2150

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 1181 of file fe-auth.c.

1182 {
1183  char *crypt_pwd;
1184  const char *errstr = NULL;
1185 
1186  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1187  if (!crypt_pwd)
1188  return NULL;
1189 
1190  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd, &errstr))
1191  {
1192  free(crypt_pwd);
1193  return NULL;
1194  }
1195 
1196  return crypt_pwd;
1197 }
#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:95

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 1224 of file fe-auth.c.

1226 {
1227 #define MAX_ALGORITHM_NAME_LEN 50
1228  char algobuf[MAX_ALGORITHM_NAME_LEN + 1];
1229  char *crypt_pwd = NULL;
1230 
1231  if (!conn)
1232  return NULL;
1233 
1235 
1236  /* If no algorithm was given, ask the server. */
1237  if (algorithm == NULL)
1238  {
1239  PGresult *res;
1240  char *val;
1241 
1242  res = PQexec(conn, "show password_encryption");
1243  if (res == NULL)
1244  {
1245  /* PQexec() should've set conn->errorMessage already */
1246  return NULL;
1247  }
1249  {
1250  /* PQexec() should've set conn->errorMessage already */
1251  PQclear(res);
1252  return NULL;
1253  }
1254  if (PQntuples(res) != 1 || PQnfields(res) != 1)
1255  {
1256  PQclear(res);
1258  libpq_gettext("unexpected shape of result set returned for SHOW\n"));
1259  return NULL;
1260  }
1261  val = PQgetvalue(res, 0, 0);
1262 
1263  if (strlen(val) > MAX_ALGORITHM_NAME_LEN)
1264  {
1265  PQclear(res);
1267  libpq_gettext("password_encryption value too long\n"));
1268  return NULL;
1269  }
1270  strcpy(algobuf, val);
1271  PQclear(res);
1272 
1273  algorithm = algobuf;
1274  }
1275 
1276  /*
1277  * Also accept "on" and "off" as aliases for "md5", because
1278  * password_encryption was a boolean before PostgreSQL 10. We refuse to
1279  * send the password in plaintext even if it was "off".
1280  */
1281  if (strcmp(algorithm, "on") == 0 ||
1282  strcmp(algorithm, "off") == 0)
1283  algorithm = "md5";
1284 
1285  /*
1286  * Ok, now we know what algorithm to use
1287  */
1288  if (strcmp(algorithm, "scram-sha-256") == 0)
1289  {
1290  const char *errstr = NULL;
1291 
1292  crypt_pwd = pg_fe_scram_build_secret(passwd, &errstr);
1293  if (!crypt_pwd)
1295  libpq_gettext("could not encrypt password: %s\n"),
1296  errstr);
1297  }
1298  else if (strcmp(algorithm, "md5") == 0)
1299  {
1300  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1301  if (crypt_pwd)
1302  {
1303  const char *errstr = NULL;
1304 
1305  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd, &errstr))
1306  {
1308  libpq_gettext("could not encrypt password: %s\n"),
1309  errstr);
1310  free(crypt_pwd);
1311  crypt_pwd = NULL;
1312  }
1313  }
1314  else
1316  libpq_gettext("out of memory\n"));
1317  }
1318  else
1319  {
1321  libpq_gettext("unrecognized password encryption algorithm \"%s\"\n"),
1322  algorithm);
1323  return NULL;
1324  }
1325 
1326  return crypt_pwd;
1327 }
char * pg_fe_scram_build_secret(const char *password, const char **errstr)
#define MAX_ALGORITHM_NAME_LEN
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2269

References appendPQExpBuffer(), appendPQExpBufferStr(), conn, pg_conn::errorMessage, free, libpq_gettext, malloc, MAX_ALGORITHM_NAME_LEN, MD5_PASSWD_LEN, pg_fe_scram_build_secret(), pg_md5_encrypt(), PGRES_TUPLES_OK, PQclear(), pqClearConnErrorState, PQexec(), PQgetvalue(), PQnfields(), PQntuples(), PQresultStatus(), res, user, and val.

Referenced by exec_command_password(), and main().

◆ PQendcopy()

int PQendcopy ( PGconn conn)

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

2881 {
2882  if (!conn)
2883  return 0;
2884 
2885  return pqEndcopy3(conn);
2886 }
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 2975 of file fe-exec.c.

2976 {
2977  if (!conn)
2978  return 0;
2979 
2980  /* succeed with no action if already in pipeline mode */
2982  return 1;
2983 
2984  if (conn->asyncStatus != PGASYNC_IDLE)
2985  {
2987  libpq_gettext("cannot enter pipeline mode, connection not idle\n"));
2988  return 0;
2989  }
2990 
2991  conn->pipelineStatus =